send and decode JSON array

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?

Upvotes: 0

Views: 335

Answers (3)

Engineer
Engineer

Reputation: 48803

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" }
    

Upvotes: 1

MrB
MrB

Reputation: 1594

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']));

Upvotes: 0

user1454661
user1454661

Reputation:

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).

Upvotes: 0

Related Questions