1

I have a click event where I compose a json data, then I want to POST it to a PHP file for processing. But something goes wrong. My PHP file is simplified for now looking like this:

<?php
header('Content-Type: application/json');
 var_dump($_POST);
?>

And the code for POST-ing looks like this:

// myarray is: var myarray = new Array(); 
// and it gets populated above this code

var strObj = JSON.stringify(myarray);
alert(strObj); // so far I get the alert containing valid JSON text
$.ajax ({
  type:"POST",
  url:"proces.php",
  contentType: "application/json",
  dataType: "json",
  async: false,
  data: strObj,
  success: function(){ alert("success")},
  error: function(){ alert("error")}
});

So when I click the button, I receive the alert containing the JSON string (looks fine), then I get the alert saying "error", and when I check the console for the response of proces.php all I see is:

array(0) {
}

What am I doing wrong? What can I do to make it right?

6
  • I think u need to change header to : header('Content-type: application/json'); (at line 1 of proces.php) (and return valid JSON response) Commented Jul 11, 2013 at 11:30
  • I added the header to my php file still nothing new. The response is the same. (I updated the php in the question body) Commented Jul 11, 2013 at 11:41
  • echo json_encode($_POST); Commented Jul 11, 2013 at 11:44
  • add console.log(this, arguments); to error callback and check in console what exact error you get; also you have typo in success param name. Commented Jul 11, 2013 at 11:55
  • @Tommi I solved the success param issue. Not the real problem. I entered the code manually here (not copy/paste) so it was just a typo. Commented Jul 11, 2013 at 11:59

2 Answers 2

1

This did the trick for me:

$.ajax ({
  type:"POST",
  url:"proces.php",
  dataType: "json",
  async: false,
  data: {tmp: strObj},
  success: function(){ alert("success")},
  error: function(){ alert("error")}
});
Sign up to request clarification or add additional context in comments.

1 Comment

I can't see how, because it does not work for me. My code that works is posted below this. I made it work somehow :)
1

I got an answer on my own. Seems to do the trick:

$.post("proces.php", {json: JSON.stringify(myarray)}, function(data){alert(data);});

I mean, I do not get the alert(data); (probably because I do not return a JSON back from php file) but in the PHP I can see the json data now.

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.