Double quote in php json encode - php

The JSON out of my file is:
[{"name":"ltrs","data":["25","80","110","113","139","1025","1026","1027","1028","1029"]},{"name":"total","data":["3","723","19","48","3","6","14","17","15","6"]}]
I require:
[{"name":"ltrs","data":["25","80","110","113","139","1025","1026","1027","1028","1029"]},{"name":"total","data":[3,723,19,48,3,6,14,17,15,6}]
JSON required for plotting bar chart in highchart.js.
When I run php query from mysql for json encode it gives the output with double quote.

I guess you want to do this if name = total
Here is the code try it:
var a = [{"name":"ltrs","data":["25","80","110","113","139","1025","1026","1027","1028","1029"]},{"name":"total","data":["3","723","19","48","3","6","14","17","15","6"]}];
$.each(a, function(k,v){
if(v.name == 'total'){
$.each(v.data, function(k1,v1){
v.data[k1] = v1*1;;
});
}
});
console.log(a);

Related

CakePHP: Escape single quotes within an implode function delimited with commas

I have a routine in my controller that retrieves the values from a single database column and builds a quoted array out of them:
$suppliers=$this->Model->find('list',array('fields'=>array('Model.supplier', 'Model.supplier')));
$strSuppliers="'".implode("','", $suppliers)."'";
$this->set('suppliers', $strSuppliers);
$strSuppliers is then fed to a jQuery script that creates an auto-complete dropdown list in the "suppliers" field in my Edit view:
<script>
$(function() {
var availableTags = [<?php echo $suppliers ?>];
$( "#MsrSupplier" ).autocomplete({
source: availableTags
});
});
</script>
The output of the variable is something like 'Tom', 'Dick', 'Harry', etc.
This works fine, unless any of the retrieved values contain single quotes. 'Tom's', 'Dick', 'Harry' breaks the array, and I'm having difficulty understanding how to escape the single quotes so that my dropdown will continue to function when they're present. I've tried changing the delimiter and swapping single quotes for double quotes, like so:
$strSuppliers='"'.implode("','", $suppliers).'"';
But that didn't work. What else might I try here?
Check out json_encode() for PHP to output a JSON string, and then look at JSON.parse() for use in your jQuery.
Instead of using implode() to generate your string, use json_encode() and then have JSON.parse() decode that for use in whatever application you need.
Edit: Added some code for clarity:
$strSuppliers = json_encode($suppliers);
and then in your jQuery:
var jsonStr = '<?php echo $suppliers; ?>';
var availableTags = JSON.parse(jsonStr);
EDIT 2: As ndm pointed out in the comments, you can do this more cleanly by directly assigning the Javascript variable to the output of json_encode():
var availableTags = <?php echo $suppliers; ?>;

How to access entry in the javascript object array

I assigned a JSON result from php to a javascript variable.
The result returned looks like below but it gives me undefined undefined
[{"a":"2","u":"jamesoduro","l":"Oduro","f":"James"},{"a":"5","u":"deary.grace","l":"Grace","f":"Dear"}]
I simple know this look like a javascript array with two objects.
I am trying to access the data inside the objects but to no avail.
Below is script:
PHP
<?php
//fetch online users
$array = array();
$sql = "SELECT id as a,username as u, lastname as l,firstname as f FROM users WHERE active =1 limit 2";
$q = mysqli_query($dbc_conn,$sql);
while($row = mysqli_fetch_assoc($q)){
$array[] = $row;
}
$json = json_encode($array);
echo $json;
?>
JQUERY
$(document).ready(function(){
//checking online users
setTimeout(function(){
$.ajax({
url:"testing.php",
type:"post",
success:function(response){
var array = response;
console.log(array[0].f +" "+ array[0].l);
}
});
},200);
});
Please what could be the problem?? Thank you
$.ajax({
url:"testing.php",
type:"post",
success:function(response){
var array = JSON.parse(response);
console.log(array[0].f +" "+ array[0].l);
}
});
You get a string from php , need turn the string into a json object .
You have to learn to debug your code to find what is going wrong I guess .
Try deserializing the response:
var array = JSON.parse(response);
EXPLANATION
The response you get from the ajax call is of type string, so you have to convert it to an object. That's what JSON.parse() method do: it parses the JSON string and creates the object that this string represent, following specific rules (The parsed string must be in a valid JSON format).
Keep your server side PHP script code neat and clean
Start PHP block from first character of first line.
Do not close php block if there is no output in HTML format.
Use ob_clean() function before echo output in is your are in developer mode and display error is enabled.
for example
ob_clean();
echo json_encode($array);
In client side, if you are getting JSON response in ajax, pass dataType:'json' in ajax option
$.ajax({
url:"testing.php",
type:"post",
dataType:"json",
success:function(response){
console.log(response[0].f +" "+ response[0].l);
}
});

Need help returning a json string after a successful jquery $.post()

I am posting to a php page that is returning the following json encoded string
{"msg":"Hi {{full_name}}, <br \/>\r\n<br \/>\r\n It was nice meeting you."}
I had added that json object in the <script> </script>
However when run the $.post() and try to output data.msg it says undefined.
Here is the full code
$.post("mass_messaging.php",{template_id: template_id})
.done(function(data){
console.log(data.msg)
//Outputs undefined???
});
Below is a snippet of my html code
<script>
addMustachePlaceHolder();
{"msg":"Hi {{full_name}}, <br \/>\r\n<br \/>\r\n It was nice meeting you."}
</script>
Any help would be really appreciated.
You probably need to parse the json as it is a string and you need an object. jQuery can do that automatically if you set the data type:
$.post("mass_messaging.php", {template_id: template_id}, function(){}, "json")
^^^^^^ here
Apart from that it is not entirely clear what you are returning. You should only return one valid json string from your php script and nothing else; no script tags, javascript, etc.
I found the answer. I was using json_encode() which was returning a json string.
So i just used data = JSON.parse(data);
and it worked!
Below is what I did
$.post("mass_messaging.php",{template_id: template_id})
.done(function(data){
data = JSON.parse(data);
console.log(data.msg);
});
var obj = jQuery.parseJSON( data );
console.log(obj.msg);

How to replace strings in a Javascript array

I am trying to pass the values of a Javascript array to a PHP URL through Ajax. Here is script array
<script>"Talent_Percentile.php?"+globalArray"</script>
Where globalArray is my Javascript array. When I alert this, I get
Talent_Percentile.php?eqt_param1=4.00,eqt_param2=4.00,eqt_param3=4.00
I know about string replace but I don't know how to use it on an array. I need an output like
Talent_Percentile.php?eqt_param1=4.00&eqt_param2=4.00&eqt_param3=4.00
Can someone help me?
I'd recommend encoding your array to JSON:
<script>
var url = "Talent_Percentile.php?" + JSON.stringify(globalArray);
</script>
On the server side, use json_decode to decode the data.
var mystring = globalArray.join("&");
var url = "Talent_Percentile.php?" + mystring;
Generally, to apply a function to all elements of an array you should use map:
globalArray = globalArray.map(function(v) {
return v.replace("old", "new");
});

Parsing PHP/JSON data in Javascript

I'm trying to communicate AJAX, JSON to PHP and then PHP returns some data and I'm trying to parse it with Javascrpt.
From the php, server I return,
echo json_encode($data);
// it outputs ["123","something","and more something"]
and then in client-side,
success : function(data){
//I want the data as following
// data[0] = 123
// data[1] = something
// data[3] = and more something
}
But, it gives as;
data[0] = [
data[1] = "
data[2] = 1
It is reading each character but I want strings from the array, not individual characters. What is happening here? Thanks in advance, I am new to Javascript and JSON, AJAX.
JSON.parse(data) should do the trick.
Set the dataType property of the ajax call to json. Then jQuery will automatically convert your response to object representation.
$.ajax({
url : ...,
data : ...,
dataType : "json",
success : function(json) {
console.log(json);
}
});
Another option is to set headers in PHP so that JQuery understand that you send a JSON object.
header("Content-Type: application/json");
echo json_encode($data);
Check this one... Should Work
success : function(data){
var result = data;
result=result.replace("[","");
result=result.replace("]","");
var arr = new Array();
arr=result.split(",")
alert(arr[0]); //123
alert(arr[1]); //something
alert(arr[2]); //......
}
You did not shown function in which you parse data. But you shoud use
JSON.parse
and if broser does not support JSON then use json polyfill from https://github.com/douglascrockford/JSON-js
dataArray = JSON.parse(dataFomXHR);
I'm not sure if this is what you want but why don't you want php to return it in this format:
{'item1':'123','item2':'something','item3':'and more something'}
Well to achieve this, you'll need to make sure the array you json_encode() is associative.
It should be in the form below
array("item1"=>123,"item2"=>"something","item3"=>"more something");
You could even go ahead to do a stripslashes() in the event that some of the values in the array could be URLs
You could then do a JSON.parse() on the JSON string and access the values
Hop this helps!

Categories