0

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?

1
  • Use can also pass an array like this var myarray= JSON.stringify(arrayname); then data: {data :myarray} Commented Jun 10, 2015 at 4:31

4 Answers 4

7

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.