39

So here's my issue, I am using AJAX (jQuery) to post a form to process.php but the page actually needs to echo out a response such as apple or plum. I'm not sure how to take the response from process.php and have it stored as a variable...

Here's the code I have so far:

<script type="text/javascript">
        function returnwasset(){
            alert('return sent');
            $.ajax({
                type: "POST",
                url: "process.php",
                data: somedata;
                success function(){
                    //echo what the server sent back...
                }
            });
        }
    </script>

Also will I need to echo the response in process.php in json? or will plain text be fine?

Sorry if this sounds like a stupid question, this is my first time doing something as such in Ajax.

PS: How do I name the POST request in the above code?

user115422
  • 4,662
  • 10
  • 26
  • 38

5 Answers5

49

<?php echo 'apple'; ?> is pretty much literally all you need on the server.

as for the JS side, the output of the server-side script is passed as a parameter to the success handler function, so you'd have

success: function(data) {
   alert(data); // apple
}
Marc B
  • 356,200
  • 43
  • 426
  • 500
  • `success function` is missing a `:` after success. you can trivially check for syntax errors by opening your browser's JS/debug console. – Marc B Feb 17 '13 at 06:14
  • thanks! I'm going to mark this as the answer, I appreciate it a lot (sorry about my obvious mistakes, I'm new to AJAX) umm also, where do I name the post request so the server will recognize it as `$_POST['blah']` ? – user115422 Feb 17 '13 at 06:15
  • 2
    @MarcB : can I get variables values,which I have in process.php?? – Emma Dec 06 '13 at 05:03
  • I'm surprised how difficult it was to find out that the "return" simply needs to be an echo. The first time I tried to do Ajax I had the hardest time figuring this out; but it's so simple. Many tutorials skip past this vital info because, presumably, they think it's so obvious they don't need to say it. – Stephen R Nov 16 '16 at 17:55
  • use `echo json_encode('apple');` instead of `echo 'apple';` – Sandhu Jan 07 '17 at 11:50
  • What if the php code needs to do some job as well? Like editing a database. – Ferazhu Jan 20 '22 at 02:09
  • does this works also in case of `error:` with a `http_response_code(400)` cause my `echo` is not being read on my `js` file when it returns. – S. W. G. Mar 22 '23 at 17:16
35

The good practice is to use like this:

$.ajax({
    type: "POST",
    url: "/ajax/request.html",
    data: {action: 'test'},
    dataType:'JSON', 
    success: function(response){
        console.log(response.blablabla);
        // put on console what server sent back...
    }
});

and the php part is:

<?php
    if(isset($_POST['action']) && !empty($_POST['action'])) {
        echo json_encode(array("blablabla"=>$variable));
    }
?>
Patt Mehta
  • 4,110
  • 1
  • 23
  • 47
Alex
  • 461
  • 5
  • 6
  • 6
    I would agree most with this answer. You can also include multiple variables in the response, such as `array("blablabla"=>$variable, "success"=>true, "user_message"="hello")` then simply use them in the JavaScript e.g. `response.success`. – SharpC Mar 02 '16 at 16:19
16
<script type="text/javascript">
        function returnwasset(){
            alert('return sent');
            $.ajax({
                type: "POST",
                url: "process.php",
                data: somedata;
                dataType:'text'; //or HTML, JSON, etc.
                success: function(response){
                    alert(response);
                    //echo what the server sent back...
                }
            });
        }
    </script>
laalto
  • 150,114
  • 66
  • 286
  • 303
Ethan
  • 2,754
  • 1
  • 21
  • 34
  • thanks for the answer, I've given it an upvote, now I just need to decide who to mark as answer :) – user115422 Feb 17 '13 at 06:16
  • 4
    "With great power comes great responsibility." -Ben Parker – Ethan Feb 17 '13 at 06:17
  • sorry ethan, but since mark answered it first, I think he deserves me marking it as answer, plus he guided me through afterwards. I've still given you an upvote :) thanks anyways! – user115422 Feb 17 '13 at 06:19
12

in your PHP file, when you echo your data use json_encode (http://php.net/manual/en/function.json-encode.php)

e.g.

<?php
//plum or data...
$output = array("data","plum");

echo json_encode($output);

?>

in your javascript code, when your ajax completes the json encoded response data can be turned into an js array like this:

 $.ajax({
                type: "POST",
                url: "process.php",
                data: somedata;
                success function(json_data){
                    var data_array = $.parseJSON(json_data);

                    //access your data like this:
                    var plum_or_whatever = data_array['output'];.
                    //continue from here...
                }
            });
Tucker
  • 7,017
  • 9
  • 37
  • 55
1
var data="your data";//ex data="id="+id;
      $.ajax({
       method : "POST",
       url : "file name",  //url: "demo.php"
       data : "data",
       success : function(result){
               //set result to div or target 
              //ex $("#divid).html(result)
        }
   });
Theo Itzaris
  • 4,321
  • 3
  • 37
  • 68