Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get "data" from JQuery Ajax requests [closed]

this is the code that I have on index.html:

<html>
    <head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width">
        <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
        <script>
            $.ajax({
                type: "POST",
                url: 'test.php',
                data: "check",
                success: function(data){
                    alert(data);
                }
            });
        </script>
    </head>
    <body>
        <div></div>
    </body>
</html>

How do I program test.php to get the "data" that is sent in the AJAX API?

like image 441
Daniyaal Khan Avatar asked Dec 30 '14 06:12

Daniyaal Khan


1 Answers

You are asking a very basic question here. You should first go through some Ajax tutorials. Just to help you a little (assuming you are aware of GET and POST methods of sending data), 'data' in data: "check" is different than 'data' in function (data) are different. For clarity, you should name them different as here:

$.ajax({
     type: "POST",
     url: 'test.php',
     data: "check",
     success: function(response){
         alert(response);
     }
});

This makes it clear that one is data that you are sending to the test.php file in POST parameters and other is the response you are getting from the test.php file after it is run. In fact, the data parameter that you POST to test.php has to be a hash like here (I am assuming the key as "type" here:

$.ajax({
     type: "POST",
     url: 'test.php',
     data: {"type":"check"},
     success: function(response){
         alert(response);
     }
});

There can obviously be more key-val pairs in data.

So, assuming your test.php file is something like this:

if(isset($_POST['type'])){
  //Do something
  echo "The type you posted is ".$_POST['type'];
}

In this case your alert should read: "The type you posted is check". This will change based on what value you send for 'type' key in AJAX call.

like image 186
nitigyan Avatar answered Oct 06 '22 20:10

nitigyan