Passing URL params with Jquery into php - php

I'v been trying for last 2 hours to pass parameters from my jquery to PHP.
I cannot seem to figure this out.
So my code goes following
var something = getUrlParameter('month');
function Refresh()
{
$.ajax({
type: 'POST',
url: 'getCalendar.php',
data: {test:something},
success: function(data){
if(data != null) $("#calendarDiv").html(data)
}
});
}
getUrlParameter is
function getUrlParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}​
I just cant seem to be able to pass anything to my php file.
Thanks.
My goal is to pass ?month=something&year=something into PHP file, so I can based on that display calendar.
Url of example:
http://chanceity.com/calendartest.html
But it doesn't work because my php file is not getting those params.

$.ajax({
type: 'POST',
url: 'getCalendar.php',
cache: false,
dataType:'json',
data: "data=" + {test:something},
success: function(data)
{
$("#calendarDiv").html(data)
},
error:function()
{
$("#calendarDiv").html('Could not get results')
}
});
and next go to your php file get the results and echo the variable back thats it
$value = htmlentities($_GET['data']);
if(!empty($value))
{
$results = 'action you want to do ';
}
else
{
$results = '';
}
echo json_encode($results);

You can also do it with just javascript
function myJavascriptFunction() {
var javascriptVariable = "John";
window.location.href = "myphpfile.php?name=" + javascriptVariable;
}

Related

jQuery use ajax and json to switch page with button

Hi so I have a JS file with a function for my button, this button get value from different checkbox in a table. But now i want to get these value on another page (for invoice treatement).
Here is my Script :
$("#boutonfacturer").click(function () {
var checked = $('input[name="id_commande[]"]:checked');
var tab = [];
var jsonobj = {};
checked.each(function () {
var value = $(this).val();
jsonobj.value = value;
tab.push(jsonobj);
});
var data= { recup : tab };
console.log(data);
$.ajax({
type: 'POST',
url: 'genererfacture-facture_groupee.html',
data: data,
success: function (msg) {
if (msg.error === 'OK') {
console.log('SUCCESS');
}
else {
console.log('ERROR' + msg.error);
}
}
}).done(function(msg) {
console.log( "Data Saved: " + msg );
});
});
i use an MVC architecture so there is my controller :
public function facture_groupee() {
$_POST['recup'];
var_dump($_POST['recup']);
console.log(recup);
$this->getBody()->setTitre("Facture de votre commande");
$this->getBody()->setContenu(Container::loader());
$this->getBody()->setContenu(GenererFacture::facture_groupee());
and for now my view is useless to show.
I have probably make mistake in my code.
Thank you.
Nevermind after thinking, I have used my ajax.php page which get my another page thanks to a window.location :
my JS :
$("#boutonfacturer").click(function () {
var checked = $('input[name="id_commande[]"]:checked');
var tab = [];
checked.each(function () {
var value = $(this).val();
tab.push(value);
});
var data = {recup: tab};
console.log(data);
$.ajax({
type: 'POST',
url: 'ajax.php?action=facture_groupee',
data: data,
success: function (idfac) {
console.log("Data Saved: " + idfac);
var id_fac = idfac;
window.location = "ajax.php?action=facture_groupee=" + id_fac;
}
});
});
my php :
public function facture_groupee() {
foreach ($_POST['recup'] as $p){
echo $p; }

Array size is always 1 in ajax

I have a function which gets the value of each checked checkbox i was able to get the value successfully by using an alert example it results to 1,2,3 which is correct but when i get it from php the array size is always 1.
HTML CODE:
function doit() {
var p = [];
$('input.cb').each(function () {
if ($(this).is(':checked')) {
p.push($(this).attr('rel'));
}
});
$.ajax( {
url:'page.php',
type:'POST',
data: {list:p},
success: function(res) {
alert(res);
}
});
alert(p)
}
PHP CODE:
<?php
$list = $_POST['list'];
echo count($list);
?>
Use this code :
var jsonData = JSON.stringify(p);
$.ajax( {
url:'page.php',
type:'POST',
data: {list:jsonData},
success: function(res) {
alert(res);
}
});
And in PHP :
$list = json_decode($_POST['list']);

Simple ajax function in cakephp 2.x not working

I am new to cakephp and trying to implement AJAX . I have a view add.ctp in which I have written the following lines :
$('#office_type').change(function(){
var office_id = $('#office_type').val();
if(office_id > 0) {
var data = office_id;
var url_to_call = "http://localhost/testpage/officenames/get_office_names_by_catagory/";
$.ajax({
type: "GET",
url: url_to_call,
data = data,
//dataType: "json",
success: function(msg){
alert(msg);
}
});
}
});
And the function get_office_names_by_catagory() within OfficenamesController.php is:
public function get_office_name_by_catagory($type = '') {
Configure::write("debug",0);
if(isset($_GET['type']) && trim($_GET['type']) != ''){
$type = $_GET['type'];
$conditions = array("Officename.office_type"=> $type);
$recursive = -1;
$office_names = $this->Officename->find("all",array("conditions"=>$conditions,"recursive"=>$recursive));
}
$this->layout = 'ajax';
//return json_encode($office_names);
return 'Hello !';
}
But unfortunately, its not alerting anything ! Whats wrong ?
Could be caused by two issues:
1) In your js snippet, you are querying
http://localhost/testpage/officenames/get_office_names_by_catagory/.
Note the plural 'names' in get_office_names_by_category. In the PHP snippet, you've defined an action get_office_name_by_catagory. Note the singular 'name'.
2) You may need to set your headers appropriately so the full page doesn't render on an AJAX request: Refer to this link.
I think, you have specified data in wrong format:
$.ajax({
type: "GET",
url: url_to_call,
data = data, // i guess, here is the problem
//dataType: "json",
success: function(msg){
alert(msg);
}
});
To
$.ajax({
type: "GET",
url: url_to_call,
data: { name: "John", location: "Boston" }, //example
success: function(msg){
alert(msg);
}
});
You should specify the data in key:value format.
$('#office_type').change(function(){
var office_id = $('#office_type').val();
if(office_id > 0) {
var data = office_id;
var url_to_call = "http://localhost/testpage/officenames/get_office_name_by_catagory/"+office_id;
$.ajax({
type: "GET",
url: url_to_call,
success: function(msg){
alert(msg);
}
});
}
});
In your action
public function get_office_name_by_catagory($type = '') {
$this->autoRender = false;
Configure::write("debug",0);
if(!empty($type)){
$conditions = array("Officename.office_type"=> $type);
$recursive = -1;
$office_names = $this->Officename->find("all",array("conditions"=>$conditions,"recursive"=>$recursive));
}
$this->layout = 'ajax';
//return json_encode($office_names);
echo 'Hello !';
exit;
}
See what I have done is I have changed your request to function get_office_name_by_catagory, as there is one paramenter $type is already defined in the function, so if I have the request by /get_office_name_by_catagory/2 then you will find value in $type in action.
So no need to use $_GET and rest everything is fine!
Try this,
remove type from ajax and try.
$('#office_type').change(function(){
var office_id = $('#office_type').val();
if(office_id > 0) {
var data = office_id;
var url_to_call = yourlink +office_id;
**$.ajax({
url: url_to_call,
success: function(msg){
alert(msg);
}
});**
}
});
In your action
public function get_office_name_by_catagory($type = '') {
$this->autoRender = false;
Configure::write("debug",0);
if(!empty($type)){
$conditions = array("Officename.office_type"=> $type);
$recursive = -1;
$office_names = $this->Officename->find("all",array("conditions"=>$conditions,"recursive"=>$recursive));
}
$this->layout = 'ajax';
//return json_encode($office_names);
echo 'Hello !';
}

jquery passing variables to php file

acctually i am not familier much with jquery.. i got this jquery script this is passing variables to the file which is showing data in json format.. but here i'm unable to show that data..plz see this piece of code
$(document).ready(function() {
var globalRequest = 0;
$('#search').bind('keyup', function(event) {
if (event.keyCode == 13) {
searchAction();
}
});
$('#search-link').bind('click', function(event) {
searchAction();
});
var searchAction = function() {
var value = $('#search').val();
var cat = $('#category').val();
var country = $('#country').val();
var page = $('#page').val();
var resultContainer = $('#results');
if (value.length < 3 && globalRequest == 1) {
return;
}
_gaq.push(['_trackEvent', 'Search', 'Execute', 'Page Search', value]);
globalRequest = 1;
$.ajax({
url: "search.php",
dataType: 'json',
type: 'GET',
data: "q="+value+"&category="+cat+"&country="+country+"&page="+page,
success: function(data){
globalRequest = 0;
resultContainer.fadeOut('fast', function() {
resultContainer.html('');
console.log(data.length);
for (var x in data) {
if (!data[x].price)
data[x].price = 'kA';
if (!data[x].img)
data[x].img = 'assets/images/no.gif';
var html = '<div class="res-container">';
html += '<h2>'+data[x].Title+'</h2>';
html += '<img src="'+data[x].img+'">';
html += '<h3>Price: '+data[x].price+'</h3>';
html += '</div>';
resultContainer.append(html);
}
resultContainer.fadeIn('fast');
});
}
});
};
});
in search.php data is in simple echo.. how to get data from search.php and show here..
sorry for bad english
First,
you shouldn't concatenate your parameters but use a hashmap:
$.ajax({
url: "search.php",
dataType: 'json',
type: 'GET',
data: {
q : value,
category : cat,
country : country,
page : page }
As your method is (type: 'GET'), just use the ($_GET[param] method) in the php file
<?php
$value = htmlentities($_GET['q']);
$category = htmlentities($_GET['category ']);
$country = htmlentities($_GET['country ']);
In the js callback function, this is how you log the whole response ('something' is a tag) :
success: function(data){
var $xml = $(data);
console.log($xml); // show the whole response
console.log($xml.find('something')); // show a part of the response : <something>value</something>
});
It is a bit hard to understand what your problem is but my guess is that you need to json encode the data before echoing it back in search.php.
simplified example......
eg.
<?php
$somevar = $_GET['a']
$anothervar = $_GET['b']
//Do whatever
$prepare = array('a'=>$result1,'b'=>$result2) //etc..
$json = json_encode($prepare);
echo $json;
exit();
?>
Then you can access the results in the javascript with:
success: function(data){
var obj = $.parseJSON(data);
alert(data.a);
$("#some_element").html(data.b);
}

Send JSON with jQuery AJAX

Why isn't this PHP getting my links array?
function check_links() {
$matches = $this->input->get('links');
if($matches == true) {
echo json_encode('matches is true');
} else {
echo json_encode('matches is false');
}
//echo json_encode($matches);
}
The JS
var linksStr = $("#links").val();
var matches = linksStr.match(/\bhttps?:\/\/[^\s]+/gi);
alert(matches.length);
for(var i = 0; i < matches.length; i++) {
alert(matches[i]);
}
var links = JSON.stringify(matches);
$.ajax({
type: 'GET',
dataType: 'json',
cache: false,
data: links,
url: 'publishlinks/check_links',
success:
function(response) {
alert(response);
}
})
I'm confused a bit with what is trying to be achieved here.
But the JSON.stringify needs to be assigned to a value,
var links = JSON.stringify(matches);
like links
var links = 'links='+JSON.stringify(matches);
Then in your function, $matches should now contain your json-encoded links.
So you can use that,
function check_links() {
$matches = $this->input->get('links');
...
$matches = json_decode($matches); // do stuff
....

Categories