3

I cannot convert JS object to exact string, my code:

jsonObj['payment_value']=100.10;
jsonObj['payment_date']="2012-06-15";
jsonObjStr = JSON.stringify(jsonObj);
alert(jsonObjStr);
$.post("test", jsonObjStr.toString(), function(output){
    alert(output);
});

first alert displays:

{"payment_date":"2012-06-15","payment_value":100.1}

and in function test (i'm using codeigniter framework) it should print "payment_date" and "payment_value", code like this:

echo $this->input->post("payment_value");
echo $this->input->post("payment_date");

which is equvalent in "clear" php to:

echo $_POST["payment_value"];
echo $_POST["payment_date"];

but second alert displays clear string.

If I put

{"payment_date":"2012-06-15","payment_value":100.1}

instead of jsonObjStr.toString() it works fine

Does anyone knows how to fix it WITHOUT using json_decode? I need to have posted values in this format, not in other array

So i need to convert jsonObjStr exact to string (something inversely to function eval())

Thank in advice

1
  • 1
    I'm not sure I understand what you're trying to do. What is your intended output? Commented Jun 15, 2012 at 9:57

1 Answer 1

4

According to $.post docs, second argument should be map or query string:

map example:

{
   "payment_date":"2012-06-15",
   "payment_value":100.1
}

query string example:

'payment_date=2012-06-15&payment_value=100.1​​​'

When you use JSON.stringify, then you get:

'{"payment_date":"2012-06-15","payment_value":100.1}'

which is invalid query string. So the solution is: do not stringify anything, pass the object itself as 2nd argument:

jsonObj['payment_value']=100.10;
jsonObj['payment_date']="2012-06-15";
$.post("test", jsonObj, function(output){
   alert(output);
});
Sign up to request clarification or add additional context in comments.

1 Comment

i can't believe that it is so simple... Obviously it works fine! Thank you!

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.