AJAX jQuery PHP Return Value - php

I am new to AJAX and am kind of confused by what PHP passes back to the jQuery.
So you have an AJAX function like this:
$.ajax({ url: '/my/site',
data: {action: 'test'},
type: 'post',
success: function(output) {
alert(output);
}
});
(I took this from ajax another StackOverflow page.)
But on various other resources they will have the success section look like this:
success: function(data) {functionfoocommandshere}
I am just confused as to what dictates the naming of this variable? If the PHP ultimately echoes an array:
echo $myVar;
How can I get this from the AJAX?

An Ajax-Requests fetches a whole site. So you'll not get any data in variables, but the whole site in the data-parameter. All echos you made together will be in this parameter. If you want to retrieve an array, you should transform it to json before.
echo json_encode($myArray);
Then you can receive it via Ajax in this way
$.ajax({ url: '/my/site',
data: {action: 'test'},
dataType: 'json',
type: 'post',
success: function(output) {
alert(output);
}
});

In you PHP file, use json_encode to turn the array into a more convenient format for use in Javascript. So you would have something like:
echo json_encode($myArray);
Then, in your JavaScript, the data variable of the success method will hold the JSON. Use jQuery's parseJSON to convert this to a JavaScript object, which will then be very easy to manipulate. I don't know what you array contains, but you might do something like this:
$.ajax({ url: '/my/site',
data: {action: 'test'},
type: 'post',
success: function(data) {
var obj = jQuery.parseJSON(data);
alert(obj.name[0] === "John");
}
});
Again, the data variable here will contain anything your PHP outputs, but JSON is a common and convenient way to transfer data back to your JavaScript.

<script type="text/javascript">
$.ajax({
url: '/my/site',
data: {action: 'test'},
type: 'post',
success: function(output) {
alert(output);
}
});
</script>
<?php
$action = $_POST['action'];
echo $action;?>
Any output that is printed/echoed will be returned to the success function. This is handy when you want to fill an html container with something that you need to run in real time.
Once you get the hang of this, another option is to use JSON to return variables with values.

The data that's returned from the PHP AJAX function, can be retrieved from the success block. Here's the manual
$.ajax({ url: '/my/site',
data: {action: 'test'},
type: 'post',
dataType: 'json',
success: function(output) {
//output is the data returned from PHP AJAX function in JSON format
alert(output);
}
});

Related

How to pass an array of string using ajax?

I'm using this ajax to pass an array of strings to another page.
This is the array on nomes.php
[ 'Home','A empresa','funcionarios','Quem Somos?','Historia','Inicio',]
This is the code, the alert doesn't work - can anyone help?
$.ajax({
type: 'post',
url: 'nomes.php',
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
},
dataType: "json",
success: function(data){
v=data;
alert(v);
}
});
You need to encode the PHP-array to a JSON-array.
<?php
echo (json_encode($myPhpArray));
?>
You can serialize the array into JSON using stringify to pass them through. Add this to your Ajax call:
data: JSON.stringify(arr);
Replace arr with your JavaScript array. This needs a plugin though. Have a look at this answer for more info.
Alternatively, if your array is in PHP, not in JavaScript you can echo it out directly like this:
data: <?php echo json_encode($arr) ?>,
If you're trying to pass the json to the server, you can do it like :
var strArray = ['str1', 'str2', 'str3'];
$.ajax({
type: 'post',
url: 'nomes.php',
data: {strarray: strArray},
dataType: "json",
success: function(data){
v=data;
alert(v);
}
});
If you're trying to receive it, you need to set the header on php side :
header('content-type: application/json');
echo json_encode(array('str1', 'str2', 'str3'));

Using AJAX to pass variable to PHP and retrieve those using AJAX again

I want to pass values to a PHP script so i am using AJAX to pass those, and in the same function I am using another AJAX to retrieve those values.
The problem is that the second AJAX is not retrieving any value from the PHP file. Why is this? How can I store the variable passed on to the PHP script so that the second AJAX can retrieve it?
My code is as follows:
AJAX CODE:
$(document).ready(function() {
$("#raaagh").click(function(){
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
data: ({name: 145}),
success: function(data){
console.log(data);
}
});
$.ajax({
url:'ajax.php',
data:"",
dataType:'json',
success:function(data1){
var y1=data1;
console.log(data1);
}
});
});
});
PHP CODE:
<?php
$userAnswer = $_POST['name'];
echo json_encode($userAnswer);
?>
Use dataType:"json" for json data
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
dataType:'json', // add json datatype to get json
data: ({name: 145}),
success: function(data){
console.log(data);
}
});
Read Docs http://api.jquery.com/jQuery.ajax/
Also in PHP
<?php
$userAnswer = $_POST['name'];
$sql="SELECT * FROM <tablename> where color='".$userAnswer."'" ;
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
// for first row only and suppose table having data
echo json_encode($row); // pass array in json_encode
?>
No need to use second ajax function, you can get it back on success inside a function, another issue here is you don't know when the first ajax call finished, then, even if you use SESSION you may not get it within second AJAX call.
SO, I recommend using one AJAX call and get the value with success.
example: in first ajax call
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
data: ({name: 145}),
success: function(data){
console.log(data);
alert(data);
//or if the data is JSON
var jdata = jQuery.parseJSON(data);
}
});
$(document).ready(function() {
$("#raaagh").click(function() {
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
data: ({name: 145}),
success: function(data) {
console.log(data);
$.ajax({
url:'ajax.php',
data: data,
dataType:'json',
success:function(data1) {
var y1=data1;
console.log(data1);
}
});
}
});
});
});
Use like this, first make a ajax call to get data, then your php function will return u the result which u wil get in data and pass that data to the new ajax call
In your PhP file there's going to be a variable called $_REQUEST and it contains an array with all the data send from Javascript to PhP using AJAX.
Try this: var_dump($_REQUEST); and check if you're receiving the values.
you have to pass values with the single quotes
$(document).ready(function() {
$("#raaagh").click(function(){
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
data: ({name: '145'}), //variables should be pass like this
success: function(data){
console.log(data);
}
});
$.ajax({
url:'ajax.php',
data:"",
dataType:'json',
success:function(data1){
var y1=data1;
console.log(data1);
}
});
});
});
try it it may work.......

How to parse json data received from a jQuery ajax call in php

I'm calling a php script (getNum.php) via ajax after creating an object and using jquery.json to turn
it to json. Now i want to handle the object on the php side.
print_r($_POST['data']) doesn't work nor anything else i've tried.
This is my code:
// create object
var bing= new Object();
bing.id = 99;
bing.nameList = getBingList();
//create pdf
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "getNum.php",
dataType: "html",
data: $.toJSON(bing),
success: function(data){
alert(data);
window.location = "generateBing.php?num="+data
}
});
If you're using print_r($_POST['data']) to show the content, you'll need to send it as "data" as well.
$.ajax({
type: "POST",
url: "getNum.php",
data: {data: $.toJSON(bing)},
success: function(data){
alert(data);
window.location = "generateBing.php?num="+data
}
});
Otherwise you have to do print_r($_POST)
Since you are posting a JSON object directly, there is no argument name for $_POST. You'll need to read the raw contents of the POST request. Try this:
$data = json_decode(file_get_contents('php://input'));
print_r($data);

pass php array to jquery

Can someone please give me a simple example how should jquery $.ajax syntax look like in order to pass array from php to jquery.
On server side I have:
$a=array(1,2,3,4,5);
echo json_encode($a);
So, I'd like get this to js and have:
js_array=[1,2,3,4,5];
I'd really appreciate any help, cause I've been trying for some time now and no luck.
Thank you!
$.ajax({
method: 'GET', // or POST
url: 'yourfile.php',
dataType: 'json',
data: {}, // put data to be sent via GET/POST into this object if necessary
success: function(response) {
// response is your array
}
});
you can either use:
$.ajax({
url: 'url',
dataType: 'json',
success: function(data){
//do something with data
}
});
or:
$.getJSON('url', function(data) {
do something with data
})

Can a Jquery Ajax Call Accept an Object on Succes from PHP?

I'm writing a simple ajax function and looking to populate two text input fields with the 'success' results. I'm wondering what my php syntax has to be to return an object.
Here is my Javascript function
function editModule(a){
data = {moduleNum:a}
$.ajax({
type: 'POST',
data: data,
url: 'includes/ajaxCalls.php',
success: function(data) {
alert(data['title']); // <-- This is where I'm not sure what to return from php
}
});
}
Here is my php doc (so far, this is where I need to know how to return an object)...
<?php
$data = array('title'=>'this');
echo json_encode($data);
When I run the function I just get the alert "undefined".
Suggestions?
Thanks,
-J
Try this. You can specify that you're expecting a JSON object and then you can interpret data accordingly.
function editModule(a){
data = {moduleNum:a}
$.ajax({
type: 'POST',
data: data,
dataType: 'json',
url: 'includes/ajaxCalls.php',
success: function(data) {
alert(data.title);
}
});
}
I have returned JSON data from the server via a jQuery Ajax call, not in PHP but it should be the same. As long as you set the content-type of your response to application/json jQuery should consider the responseText as a JSON string. Alternatively you can also set dataType: "JSON" in your Ajax call which tells jQuery that you expect JSON.
Your php page returns: {"title":"this"} in this case.
So you can reference the result with:
alert(data.title);
You may need to specify the data type:
function editModule(a){
data = {moduleNum:a}
$.ajax({
type: 'POST',
data: data,
url: 'includes/ajaxCalls.php',
dataType: 'json',
success: function(data) {
alert(data['title']); // <-- This is where I'm not sure what to return from php
}
});
}

Categories