简单的jQuery + PHP无法正常工作

I have the following code in my javascript:

$.ajax({
    url : 'update_data.php',
    type : 'POST',
    data : 'asdfasd', //d,
    success : function(response){
        console.log(response);
    },
    error: function(jqXHR, textStatus, errorThrown){
        console.log('jqXHR.responseText:  ' + jqXHR.responseText);
        console.log('jqXHR.responseXML :  ' + jqXHR.responseXML);
        console.log('textStatus:   ' +  textStatus);
        console.log('errorThrown:   ' + errorThrown);
    },
    dataType : 'text'
});

Here is my 'update_data.php' :

<?php
    echo json_encode($_POST);
    if (isset($_POST['data'])){
        echo "here!";
    } else {
        echo "failed jquery";
    }
?>

When I run the Ajax method, I get the following response in my console:

[]failed jquery

meaning update_data.php didn't get any POST request. '[]' is from json_econd($_POST), and 'failed jquery' is from the if/else.

What am I doing wrong?

you need to pass data as below

 data : {'data':'asdfasd'},

if want to pass multiple parameters then

data : {'data':'asdfasd','param1':'value','param2':'value'},

or submit data of form

data : $( "formselector" ).serialize(),

data parameter in ajax

Type: PlainObject or String or Array 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).

Read more about jquery ajax parameters HERE

your sentence echo json_encode($_POST); is just response return back to your AJAX request. so the code under it do not work. Try comment this sentence and run again. I think you can see "here!" in console.

You have doing two mistakes:

1: In jquery you must send data like : data : {'data':'asdfasd'}

2: In the 'update_data.php' : json_encode in the last of script

Whenever you use ajax the always pass the data as a key value pair inside curly braces as:

data = {'data':'asdfasd'}
  • If you use this type of data passing then it will always work.
  • Another thing is if you want to submit a full form data then try sending serialized data of form as:

data = $('#form_id').serialize();

This will provide you all form data on your php page in $_GET -r $_POST whichever you have used as a method for ajax.