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?

1
  • 1
    .serialize() gives you a query string, .serializeArray() might be closer to what you want Commented Jul 11, 2012 at 19:04

3 Answers 3

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" }
    
Sign up to request clarification or add additional context in comments.

4 Comments

Your edited code gives me only last form fields values not all array.
@OsvaldaKazlaučiūnaitė So you have multiple forms? Do I understand right?
well, form is one, but I can add additional rows set to it
@OsvaldaKazlaučiūnaitė Make sure, that when you add/remove/modify new input elements, those elements are inside of the form tag.
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).

3 Comments

dataType specifies the response-body type,not the request-body type !
If you only just do data: data you might run into a similar issue like I did here: stackoverflow.com/questions/11385668/…
@Engineer: Upvoted, you are right and I was off-track anyway with my answer, I misunderstood OP's question.
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']));

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.