Search code examples
phpjavascriptjqueryjsobject

javascript convert object string to string


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


Solution

  • 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);
    });