Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AJAX jQuery PHP Return Value

Tags:

jquery

ajax

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?

like image 798
eatonphil Avatar asked Nov 13 '12 18:11

eatonphil


People also ask

How can I get specific data from AJAX response?

You can't as it's asynchronous. If you want to do anything with it, you need to do it in a callback. How? Because it's asynchronous, javascript will fire off the ajax request, then immediately move on to execute the next bit of code, and will probably do so before the ajax response has been received.

How PHP can be used in AJAX application?

Create an XMLHttpRequest object. Create the function to be executed when the server response is ready. Send the request off to a PHP file (gethint. php) on the server.

Can we use jQuery in PHP?

All you need to do to use jQuery with PHP is to include the jQuery javascript file in your HTML document in the head tag.


1 Answers

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);
          }
 });
like image 185
Gnietschow Avatar answered Oct 18 '22 21:10

Gnietschow