0

I'm trying to encode and send JSON array to php page and add it to mysql:

var data = $('form').serialize();
$.ajax({
    type: 'POST',
    url: 'naujas.php',
    dataType: 'json',
    data: ({
        json: JSON.stringify(data)
    }),
    success: function () {
        $('#naujas').load('naujas.php');
    }
});

But I think its not working I'm getting response from php like that: pav=1&ppav=2&kiekis=3&kaina=4d&ppav=5&kiekis=6&kaina=7&ppav=8&kiekis=9&kaina=0

php file

<?php
    $json = json_decode($_POST['json']);
    echo $json;
?>

What I'm doing wrong?

Colin Brock
  • 21,267
  • 9
  • 46
  • 61
  • 1
    .serialize() gives you a query string, .serializeArray() might be closer to what you want – Musa Jul 11 '12 at 19:04

3 Answers3

1

Try like this:

var data = $('form').serializeArray().reduce( function(obj,cur){
    obj[cur.name] = cur.value;
    return obj;
},{});

Explanation:

  • .serializeArray() returns an array, which has following structure:

    [ {name:"inputname1",value:"inputvalue1"},
      {name:"inputname2",value:"inputvalue2"},
      //---------------------------------------
      {name:"inputnamen",value:"inputvaluen"} ]
    
  • .reduce() function converts that array to object:

    { "inputname1":"inputvalue1",
      "inputname2":"inputvalue2",
      //---------------------------------------
      "inputnamen":"inputvaluen" }
    
Engineer
  • 47,849
  • 12
  • 88
  • 91
0

dataType: 'json' already tell jQuery to post the data in a json format.

All you need to do is to post your data, something like this:

data: (data),

The problem comes from converting your object to a string representation (stringify).

  • 2
    `dataType` specifies the *response-body* type,not the *request-body* type ! – Engineer Jul 11 '12 at 19:21
  • If you only just do data: data you might run into a similar issue like I did here: http://stackoverflow.com/questions/11385668/js-ajax-calling-php-and-getting-ajax-call-data – MrB Jul 11 '12 at 19:22
  • @Engineer: Upvoted, you are right and I was off-track anyway with my answer, I misunderstood OP's question. –  Jul 11 '12 at 21:54
0

You might need to use php stripslashes

http://php.net/manual/en/function.stripslashes.php

I think it's something like this

json_decode(stripslashes($_POST['json']));
MrB
  • 1,544
  • 3
  • 18
  • 30