2

i want to pass a post json value to another page. however when i add a json datatype on my post ajax parameter, the javascript code is not functioning. however if i remove the json parameter its working. im just new to jquery. thanks in advance for your help.

<script type="text/javascript">
$('#login_form').submit(function(evt) {
    evt.preventDefault();
    var url = $(this).attr('action');
    var postData = $(this).serialize();

    $.post(url, postData, function(o) {
        alert(o);
    }, "json");

});
</script>
  • 1
    It sounds like the returned data is not correctly formatted JSON, and the parser is throwing an error. Check the console for request errors. – Rory McCrossan Aug 05 '14 at 08:44
  • See your response, it must be json-encoded. Or show your server script. – dafive Aug 05 '14 at 08:45
  • hi Rory im just new web dev. can you tell how can i check my console for request errors. –  Aug 05 '14 at 08:59
  • 1
    @urbz — No. That's if you are posting JSON which the OP most definitely is not (because `serialize` doesn't return JSON). – Quentin Aug 05 '14 at 08:59
  • @frenzii — Open the console (how you do this depends on your browser, ask Google for details). Read it. – Quentin Aug 05 '14 at 09:00
  • 1
    If telling jQuery to parse some data as JSON doesn't work, then the problem is almost certainly that the server is not outputting JSON. Either (1) Change the server side code you haven't shared with us to output JSON or (2) Stop trying to parse not-JSON as JSON. – Quentin Aug 05 '14 at 09:01
  • "i want to pass a post json value" — Don't confuse what you are sending with what you are receiving. The data you are sending is not encoded as JSON. The change you are making which stops it working is telling jQuery how to parse the *response*. – Quentin Aug 05 '14 at 09:02

1 Answers1

-2

Since you have put "json" in your $.post, your url should return json data. If it is not returning a json then your function will not fire.

Since your JavaScript is functioning without json datatype, you may not returning a json as a response.

Check this JSFiddle, since it returns a JSON, you can see the alert.

Saranga
  • 3,178
  • 1
  • 18
  • 26