javascript convert object string to string - php

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

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

Related

js json.stringify to PHP json_decode

I am new to JSON.
In JS, I create an array of values like so:
var arrFields = $("td>.frmInput").map(function(){
return {
id: this.id,
value: $(this).val()
};
}).get();
I then AJAX them to the server like so:
$.ajax({
type: "POST",
url: "ajax/ax_all_ajax_fns.php",
data: "Fields=" +JSON.stringify(arrFields),
success: function(recd) {
alert(recd);
}
});
Note that there is a mixture of strings, plus the JSON.stringified (?) array. (There are additional string values sent, so data must remain as string.)
On the PHP side, I need to turn the received Fields string into an associative array.
Doing this:
$jsonAsStr_Fields = $_POST['Fields'];
die($jsonAsStr_Fields);
Returns this text string in the alert():
[{"id":"rateDriver","value":"Jacques Villeneuve"},{"id":"rateCar","value":"Chev"}]
Doing this:
$arrFields = json_decode($jsonAsStr_Fields, TRUE);
$driver = $arrFields['rateDriver'];
$car = $arrFields['rateCar'];
$tire = $arrFields['rateTire'];
die('Driver: [' .$driver. '] Car: [' .$car. '] Tire: [' .$tire. ']');
Returns this:
Driver: [ ] Car: [ ] Tire: [ ]
How can I turn the $jsonAsStr_Fields string into an assoc array, and thereby output the correct values to my alert?
Do this instead for your creation of values:
var arrFields = {};
$("td>.frmInput").each(function(){
arrFields[this.id] = $(this).val();
});
This will create an object, when JSON-stringified, that looks like this:
{"rateDriver":"Jacques Villeneuve", "rateCar":"Chev"}
Which seems to be the format you want to use in your PHP code.
You have an array of associative arrays and your arrays don't have the specified props, rateDriver for example is the value of the first array's element's id:
$driver = $arrFields[0]['id'];
$car = $arrFields[1]['id'];
For seeing the array's contents you use the famous var_dump function.
From the Author:
For those who haven't fully understood what solved this problem.
The underlying problem was that the stringified JSON was being modified en route (immed after hit Submit button en route to the PHP side) by the AJAX. All quote marks were being escaped, which made it impossible for that string to work with json_encode.
This was discovered by grabbing the value of the received data once it hit the PHP side:
$jsonAsStr_Fields = $_POST['Fields'];
die($jsonAsStr_Fields);
And alerting the received data in the AJAX success function:
success: function(recd) {
alert(recd);
}
Both of the above were described in the OP.
However, because I assumed this was an unrelated problem, I "fixed" the string displayed in the alert() box when I posted the question. Lesson to be learned: don't help - just post what you actually see.
It really displayed like this:
{\"id\":\"rateDriver\",\"value\":\"Jacques Villeneuve\"}
but I wrote that it displayed like this:
{"id":"rateDriver","value":"Jacques Villeneuve"}
Of course, the json_decode() PHP function had no idea what to do with the backslashes, so the string did not convert.
Solution was to use str_replace() on the received JSON string over on the PHP side, to resolve the problem, like this:
str_replace("\\", "", $_POST['Fields']);

Echo/return an array in php

Im trying to query a database from a php file then return the results (userLOC of each row) to the calling Jquery function.
Calling Jquery:
$.post(url, data, function (data)
{
alert(data);
})
relavent PHP:
$sql = "Select * from location";
$result = mysql_query($sql);
$stack = array();
while($row = mysql_fetch_array($result))
{
array_push($stack, $row["userLOC"]);
}
return $stack;
The problem is that I cant return it correctly, if I "echo $stack" it does not work it says Im trying to convert the array to string. If I "echo $stack[0]" it will give me the first result in the array correctly so I know the values are being stored correctly (as are $stack[1], etc.) but this only sends the one value back. And if I "return $stack" as pictured nothing is alerted because nothing is echoed. How would I go about getting the whole array back so that I could iterate through and use them on the jquery side?
In PHP
$foo = array();
echo $foo;
will produce the literal string Array as output.
You need to convert your array into a string. Since you're dealing with a Javascript target, use JSON as the perfect means of doing so:
$foo = array('a', 'b', 'c', 'd', 'e');
echo json_encode($foo);
Then in your JS code:
$.get(...., function (data) {
alert(data[1]); // spits out 'b'
});
Just remember to tell jquery that you're expecting JSON output.
You need to wrap (serialize) the data in a way that can be transported to the client via HTTP and used to get the original data.
Usual container formats are XML and JSON. JSON is well suited for usage in JavaScript, so use the PHP function json_encode() and echo the result.
Youll want to use JSON!
Client-side:
jQuery.post(url, data, function( data ) {
//Data is already converted from JSON
}, "json");
Server-side:
return json_encode($stack);
Explanation
Hope this helps!
echo json_encode($stack); can help you
at jquery side use jQuery.parseJSON()
You need to convert the array to a JSON object like this : return json_encode($stack);
Just convert your array it to a JSON object and return it back to your JavaScript:
return json_encode($stack);
As others have said, you may wish to wrap the output using something like json:
echo json_encode($stack);
However, if you aren't looking for an output with the complexity of JSON formatting, you could just use implode() to output a comma separated list:
echo implode(',',$stack);

unable to unpack php array with $.post()

I have an array stored in php: $cv1 = array('a','b');
As you can see in the code below, I am trying to get the respective data from the array then delegate it to two separate functions.
But the data returned from the php callback function is: 'Array' instead of 'a','b';
and result[0] gets 'A' result[1] gets 'r' etc.
Thanks for help!
js:
$('a').on('click',function(){
var cv = $(this).data('cv');
var url= '_php/myphp.php';
$.post(url,{contentVar:cv},function(data) {
result=data;
return result;
}).done(function() {
alert(result[0]);
$('#myDiv').html(result[1]);
});
});
php:
$cv1 = array("a","b");
$contentVar = $_POST['contentVar'];
if($contentVar == "cv1")
{
echo json_encode($cv1);
}
It's common in PHP for you to get "Array" instead of an actual array when it accidentally gets cast to a string. That's not what you're doing here though; we can test:
> $cv1 = array("a","b");
array(2) {
[0] =>
string(1) "a"
[1] =>
string(1) "b"
}
> json_encode($cv1);
string(9) "["a","b"]"
$cv1 gets encoded correctly.
You must be treating it like a string somewhere else:
> (string)array("a","b")
! Array to string conversion
string(5) "Array"
Also, why do you have two success callbacks in $.post? The 3rd argument is a success callback, which works the same as .done. Use one or the other (I recommend done) but not both.
You may also consider passing json as the last argument (dataType) so that jQuery knows what to expect and will properly decode the result.
Try to do something like this:
$.post(url,{contentVar:cv}
function(response)
{
alert(response[0]);
},'json'
);
You need to convert the json string format to a javascript object/array.
var result = $.parseJSON(data);
see this question jQuery ajax request with json response, how to? for more detail.
But there is something strange that, if is returning 'Array', the php is not converting the array to json, what happens if the ($contentVar == "cv1") return false? If you will return an array to javascript you need to convert to a string (and the json format is perfect for this).

jqplot not evaluating string

I am using jqplot and have constructed an array with the following PHP code
if($fiveRes){
$lastNum = mysql_num_rows($fiveRes);
$testarray = array();
while($row = mysql_fetch_array($fiveRes, MYSQL_ASSOC)) {
$testarray[] = array($row['GameDate'], floatval($row['WKP']));
}
echo json_encode($testarray);
}
This code outputs the correct code that I need to insert into the jqplot function. Here is the array generated by the code above:
[["2011-12-24",0],["2011-12-19",14],["2011-12-08",22],["2011-12-04",14],["2011-11-27",12]]
So currently i'm printing this array to the screen, and then using jQuery .text() to capture the string and place it inside a variable. I can echo out the var that I assigned the array string to and it works correctly, however when I pass it into the jqplot function it does nothing.
var p1array = $('.col.first .parray').text();
alert(p1array); //Alerts the correct array formatted like above.
var plot1 = $.jqplot('jqplot0', [p1array], {
title:'Last 5 Fantasy Points',
axes:{
xaxis:{
renderer:$.jqplot.DateAxisRenderer,
tickOptions:{
formatString:'%b %#d'
}
},
yaxis:{
tickOptions:{
formatString:''
}
}
},
highlighter: {
show: true,
sizeAdjust: 7.5
},
cursor: {
show: false
}
});
To make it even more complicated, if I copy the string that the PHP generates and I hardcode it into a variable in JS it works. Any ideas why the jqplot plugin won't evaluate the string I get from using $(this).text();.
Here is the jQplot example i'm modeling after: http://www.jqplot.com/tests/cursor-highlighter.php
Using this method helped me solve this problem. Instead of using jQuery to access the printed variable I inserted a little bit of javascript at the bottom of my PHP page to capture the local variable in PHP and then used that to pass into the jQplot function.
Pass a PHP string to a JavaScript variable (and escape newlines)
Use [p1array] directly with out braces and try... it should work just like p1array

Pass string to json with jquery and loop the elements

Hello there I have a really complex php script that produces a javascript file in jquery
There is a string that is stored in an input type text and I want to converted into json.
The input type text has undedined number of elements.
So I initisialize the string in the input box
<input type="text" id="selectbuttons" value="{}">
After some actions the string in the input box is something like that:
{"button":"bt1","style":"style1"},{"button":"bt2","style":"style2"}
etc...
Then this is my script , i use the function addScriptto to add it to the document's header, also I am using the core of jquery jquery-1.6.2.min.js to make the json object
$document->addScriptto('
$.noConflict();
jQuery(document).ready(function($) {
var loaded=$("#selectButtons").val();
var obj = jQuery.parseJSON(loaded);
}); //end of dom ready
');
But I can't make it work, when the string is not empty
Is there something wrong with my json syntax? Also, I would be later able to loop all the elements and retrieve the data? Thanks in advance
Your JSON string should be in an array format like below
[{"button":"bt1","style":"style1"},{"button":"bt2","style":"style2"}]
And then you can use the $.each to loop through the JOSN values as below:
$.each(yourJSONstring,function(i,values) {
//yourJSONstring holds the JSON array
// i is just the loop index. it will increment by 1 in every loop
alert(values.button) //will alert bt1 in the 1st loop, bt2 in 2nd
alert(values.style) //will alert style1 in 1st loop, style2 in 2nd
//You can have values here of the keys in JSON using the dot notation as above and do your operations.
})
maybe just put [ ... ] around the JSON so it is understood as an array, something like:
var obj = jQuery.parseJSON( '[' + loaded + ']' );
Yes, your JSON syntax is wrong. You should have it like:
[{"button":"bt1","style":"style1"},{"button":"bt2","style":"style2"}]
and then you will have array of your objects.

Categories