1

I'm trying to test the successful submission of data from javascript to a php file by having that php file return the results of the javascript post back to javascript. I'm getting a successful response in the ajax post, but the data is an empty string. How do I find out what data was posted? Here's my code:

JAVASCRIPT:

var benefitsArray = ["someData","someOtherData"];

$('#drop-submit').on('click',function(){
if (benefitsArray.length > 0){

    var formData = { "benefits" : benefitsArray };
    debugger;
    $.ajax({
        url : "dd-receiver.php",
        type: "POST",
        data : formData,
        success: function(data, textStatus, jqXHR)
        {
            console.log(data); //result is "";
            debugger;
            //data - response from server
        },
        error: function (jqXHR, textStatus, errorThrown)
        {
            console.log('failure');
        }
    });
}
});

PHP:

<?php 
echo $_POST["benefits"]
?>

UPDATE:

I got a response by, in the php code, doing:

echo json_encode($_POST['benefits']); 

but the problem is that in the javascript, if I log the data, the result is

"["someData","someOtherData"]" (a string)

and not

["someData","someOtherData"] (an array)

how do I get it to return an array and not a string?

5
  • 1
    Does echoing "Hello World!" perform any differently? Commented Jan 7, 2014 at 20:14
  • Does adding return false; at the end of the click function help? Without it, you're probably submitting the form and none of the rest of the function executes. Commented Jan 7, 2014 at 20:16
  • 2
    BTW, echoing an array will just echo the word "Array", not the contents. Commented Jan 7, 2014 at 20:16
  • can you provide the var_dump($_POST); output? Commented Jan 7, 2014 at 20:35
  • 1
    In the Javascript, if you add dataType: "json" as an option to $.ajax, jQuery will parse the JSON automatically and provide data as an object. Commented Jan 7, 2014 at 20:36

1 Answer 1

2

You're not parsing the JSON being sent to you.

You can make jQuery do this for you by adding dataType: 'JSON' to your $.ajax options...

 $.ajax({
   dataType: 'JSON',
   url : "dd-receiver.php",
   type: "POST",
   data : formData,
   success: function(data, textStatus, jqXHR) ...

Or manually with JSON.parse:

   success: function(data, textStatus, jqXHR) {
     benefits = JSON.parse(data);
     ...
   }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.