Sending two variables in a single AJAX request - php

I have a page that gets the user from $_POST. It is something like this:
$login=$_POST['name'];
Then when I click a button it makes an AJAX request like the following:
var id = $(this).val();
var dataString = 'Empresa=' + id;
$.ajax({
type: "POST",
url: "processemp.php",
data: dataString,
success: function (html) {
This works fine but I need to send $login with the request too. How can I send two variables at once?

You can try one of the two solutions below, but please note that the script should be written in the PHP page, not in a separate javascript file.
The data option of jQuery.ajax() accepts two types of form: PlanObject or String.
data
Type: PlainObject or String Data to be sent to the server. It is
converted to a query string, if not already a string. It's appended to
the url for GET-requests. See processData option to prevent this
automatic processing. Object must be Key/Value pairs. If value is an
Array, jQuery serializes multiple values with same key based on the
value of the traditional setting (described below).
As a plain object,
var id = $(this).val();
$.ajax({
type: "POST",
url: "processemp.php",
data: {
Empresa : id,
login : '<?php echo $login; ?>'
},
success: function(html){
}
});
As a query string,
var id = $(this).val();
$.ajax({
type: "POST",
url: "processemp.php",
data: 'Empresa=' + id + '&login= <?php echo $login; ?>',
success: function(html){
}
});

Related

Data sent through AJAX not available in $_POST

My Javascript code is the following:
function on(logged_user) {
alert(logged_user);
$.ajax({
url: "update_stats.php",
type: "POST",
data: logged_user
});
}
update_stats.php contains
<?php
$logged_user = $_POST["logged_user"];
?>
but I can see that $logged_user is just an empty string (I'm inserting it into a database table)
Your data parameter for the $.ajax call is not in the right format. From the manual:
The data option can contain either a query string of the form
key1=value1&key2=value2, or an object of the form {key1: 'value1',
key2: 'value2'}
You should change that line to:
data: { logged_user : logged_user },
or
data: 'logged_user=' + logged_user,
just try this:
function on(logged_user) {
alert(logged_user);
$.ajax({
type : 'POST',
url : update_stats.php,
data : logged_user,
dataType : 'json',
encode : true
});
}
Its not javascript , its a jquery ajax, so please include a jquery library.
and change your function like this
Syntax to pass the values like,
data: '{ "key":' + value+ ', "key":"value" }',
or
data = "key=" + value
or
data: JSON.stringify({ key: value, key: value}),
function on(logged_user) {
var dataString = "logged_user=" + logged_user
$.ajax({
type: "POST",
url: "update_stats.php",
data: dataString,
cache: false,
success: function(result) {
alert(result)
}
})
}
You need to pass data in key - value format to get accesible by $_POST, $_GET and $_REQUEST array variables in php.
data: {'logged_user' : data: logged_user}
You can access raw input like JSON data or text data which not in the key value format you can use file_get_contents("php://input") to access data.

PHP-AJAX: How to pass URL variable through Ajax

I have set an Ajax call for Pagination. I need to pass one more vaiable which is stored in the URL
URL
http://thisite.com/pagetitl/?id=12 **// where 'id=' is a variable I want to pass.**
Ajax Call
function page(page) {
var dataString = '&page=' + page; // pagination with ajax
pag.ajax({
type: "GET",
url: "cmn_pg.php",
data: dataString,
success: function (ccc) {
pag("#search_results").html(ccc);
}
});
}
I have tried to GET it in PHP file $id=$_GET[id], but wont work.
I ask how to pass it with AJAX because I'm quite new to AJAX.
If you are building your query string manually then:
dataString = 'page=' + encodeURIComponent(page);
but you are using jQuery, so don't build it manually:
url: "cmn_pg.php",
data: {
"page": page
},
success: function (ccc) {
(You also need to use the right name for it in PHP: <?php $id = $_GET['page'] ?>)
You can pass via url like this
pag.ajax
({
type: "GET",
url: "cmn_pg.php?page="+page,
success: function(ccc)
{
pag("#search_results").html(ccc);
}
});
Or
pag.ajax
({
type: "post",
url: "cmn_pg.php",
data: {'data':dataString},//You can add as many datas seperated by comma to pass more values
success: function(ccc)
{
pag("#search_results").html(ccc);
}
});
And in php
$dataString = $_POST['data'];
You named the variable "page" and try to access it via "id" in PHP. You have to create the query string liek this:
var dataString = '&id=' + page;
Alertnitavly you can use pass an object to the "data" parameter andjQUery does the transformationf for you. Sample:
data: { id: page },
Data to be sent to the server. It is converted to a query string, if
not already a string. It's appended to the url for GET-requests. See
processData option to prevent this automatic processing. Object must
be Key/Value pairs. If value is an Array, jQuery serializes multiple
values with same key based on the value of the traditional setting
(described below).
Soruce: http://api.jquery.com/jQuery.ajax/
Try this,
pag.ajax({
type: "GET",
url: "cmn_pg.php",
data: {
page: page, // your page number
id:12// your id to send
},
success: function (ccc) {
pag("#search_results").html(ccc);
}
});
function page(page) {
var dataString = '&page=' + page; // pagination with ajax pag.ajax
({
type: "GET",
url: "cmn_pg.php",
data: {
page: page
},
success: function(ccc) {
pag("#search_results").html(ccc);
}
});
if more data is there to pass add to data variable as given bellow :-
data : {page:page,data2:data2},

php returns empty variables on ajax post

I am trying to get the hang of php and ajax post. I am posting simple user input via text box to a php page. The php page takes the user input, counts words and sends it back as response. However it can't receive the data, comes back saying. Why is this how do I fix it?
This is my jQuery ajax post code
var dataString = name;
$.ajax({
type: "POST",
url: "test_get.php",
data: dataString,
success: function(response) {
alert(response);
}
});
return false;
});
});
This is my PHP code
// if data are received via POST, with index of 'dataString'
if (isset($_POST['dataString'])) {
$str = $_POST['dataString']; // get data
echo "The string: '<i>".$str."</i>' contains ". strlen($str). ' characters and '. str_word_count($str, 0). ' words.';
}
else echo 'There is no data!';
Your data argument is incorrect.
var dataString = name;
$.ajax({
type: "POST",
url: "test_get.php",
data: {"dataString" : dataString },
success: function(response) {
alert(response);
}
});
Read the jQuery $.ajax docs for more info.
You probably need to change:
data: dataString,
To
data: "dataString="+dataString,
Because a HTTP POST still runs off of key/value pairs.

Data not passing through AJAX

I am trying to pass a value of a button using some ajax to a separate file.
Here is my code.
$("input#downloadSingle").click(function() {
var myData = $("input#downloadSingle").val();
$.ajax({
type: 'post',
url:'singleDownload.php',
data: myData,
success: function(results) {
alert('works');
}
});
});
However, when I test out the next page by doing a var_dump on $_POST. I don't get any data back. Thoughts?
You're not specifying the name of the $_POST variable you're gonna get on the singleDownload.php file (unless that's part of the button's value), so you should try something like:
$("input#downloadSingle").click(function() {
var myData = "whatever=" + $("input#downloadSingle").val();
$.ajax({
type: 'post',
url:'singleDownload.php',
data: myData,
success: function(results) {
alert('works');
}
});
});
And make sure $_POST in your php file is the same whatever variable

jquery ajax not working with data field

When i submit a jquery ajax request without the data value, it works, when i submit it with the data value, nothing happens. I check if it works using firebug. I think its a simple mistake but i cant seem to figure it out. Please Help.
Here is the Jquery Code
var inputString = $("something").val();
var suggestions = $.ajax({
url: "temp.php",
type: "POST",
data: {valueInput : inputString},
dataType: "html"
});
temp.php just has some simple code since I'm testing:
echo "We got sumn here";
another thing is the suggestions variable is empty, any ideas?
You can try:
data: 'valueInput=' + encodeURIComponent(inputString),
Update
suggestions is being set to the jqXHR object returned from the $.ajax() function. If you want to do work on the server-response then you need to set a success callback somehow. Here are two ways:
var inputString = $("something").val();
$.ajax({
url : "temp.php",
type : "POST",
data : 'valueInput=' + encodeURIComponent(inputString),
dataType : "html",
success : function (serverResponse) {
//you can now do work on the server-response, it's stored in the serverResponse variable
alert(serverResponse);
}
});
OR
var inputString = $("something").val(),
suggestions = $.ajax({
url : "temp.php",
type : "POST",
data : 'valueInput=' + encodeURIComponent(inputString),
dataType : "html"
});
$.when(suggestions).then(function () {
//this is your callback function
});
I suggest the first method, the second is more advanced and is really only helpful if you want to wait for a set of AJAX requests to complete before doing something.
valueInput should be in quotes as it's a name. 'valueInput'
var inputString = $("something").val();
var suggestions = $.ajax({
url: "temp.php",
type: "POST",
data: {'valueInput': inputString},
dataType: "html"
});
You need to pass data in a form of query string. It should be something like a=1&b=2&c=3&d=4&e=5
You can use .serialize() method over jQuery object that has selected form elements or form tag. So, maybe this code shall be helpful.
var suggestions = $.ajax({
url: "temp.php",
type: "POST",
data: $("something").serialize(),
dataType: "html"
});
You can try
data: JSON.stringify({'valueInput': inputString}),
in you data parameter.

Categories