split JSON data from PHP to three arrays in JavaScript - javascript

I am passing values from PHP Script to JS using JSON encode.
$arr=array('X'=>$X,'Y'=>$Y,'par'=>$par);
echo json_encode($arr);
Which produces
{"X": ["-0.9537121038646844","-0.9537121038646844","-0.9537121038646844","0.9537121038646843",""],
"Y": ["-0.9537121038646844","-0.7799936811949519","-0.5533396521383813","-0.37962122946864896",null],
"par": ["0.009811016749950838","0.005007306592216437","5.058030686503405E-4","9.451402320405391E-4",null]}
In the javascript, I used the following command
{
$.post("plot.php",param,function(data){dataType:"json";console.log(data);Var X1=data.X;});
}
But I am not able to obtain the values of X alone. I tried few suggestions from similar threads, but none of them did the trick.I need the three arrays, X,Y and Par to be used in JS.

Try this:
$.post("plot.php", param, function(data) {
console.log(data);
var X1 = data.X;
},
"json"
);
You can also use $.ajax (which is the function $.post internally calls):
{
$.ajax({
type: "POST",
url: "plot.php",
dataType: "json",
data: param,
success: function(data) {
console.log(data);
var X1=data.X;
}
});
}

If you are using php you have to specify at the last parameter of post fn that is json type:
$.post("plot.php",param, function(data){
console.log(data);
var X1=data.X;
},'json');

Related

Set javascript variables from ajax request to mysql database

I am trying to make an ajax request to a mysql database and need to loop through the results and either set them as javascript variables or use them in functions within the loop.
mysql query where id is not unique and will return an array of results:
$id =$_REQUEST['id'];
$sth = $conn->prepare("SELECT * FROM quote where id = :id");
$sth->bindParam(':id', $id);
$sth->execute();
$result = $sth->fetchAll();
echo json_encode($result);
Ajax request using post and log results:
$.ajax({
type: "POST",
data: "id="+id,
url: "get-quote-data.php",
cache: false,
success: function (result) {
console.log(result);
}
});
logs 2 objects in an array as there are currently 2 results:
[{"id":"6776t2dhc3aq","0":"6776t2dhc3aq","Wid":"6776t2dhc3aqnew0.5981985541579144","1":"6776t2dhc3aqnew0.5981985541579144","room":"Plot 1 Bedroom","2":"Plot 1 Bedroom","style":"S150","3":"S150","type":"upvc","4":"upvc","colour":"0","5":"0","RAL":"","6":"","cill":"2","7":"2","width":"1023.0000","8":"1023.0000","height":"1585.0000","9":"1585.0000","fitting":"1","10":"1","comments":"","11":"","spacercol":"1","12":"1","glassstyle":"0","13":"0","handles":"0","14":"0","hinges":"0","15":"0","trickle":"0","16":"0","sash":"0","17":"0","fanlight":"0","18":"0","total":"0.0000","19":"0.0000","g1":"6","20":"6","g2":"6","21":"6","g3":"0","22":"0","g4":"0","23":"0","g5":"0","24":"0","g6":"0","25":"0","g7":"0","26":"0","g8":"0","27":"0","m1":"1023.0000","28":"1023.0000","m2":"1023.0000","29":"1023.0000","m3":"0.0000","30":"0.0000","m4":"0.0000","31":"0.0000","m5":"0.0000","32":"0.0000","m6":"0.0000","33":"0.0000","m7":"0.0000","34":"0.0000","m8":"0.0000","35":"0.0000","t1":"777.5000","36":"777.5000","t2":"777.5000","37":"777.5000","t3":"0.0000","38":"0.0000","t4":"0.0000","39":"0.0000","t5":"0.0000","40":"0.0000","t6":"0.0000","41":"0.0000","t7":"0.0000","42":"0.0000","t8":"0.0000","43":"0.0000","ICwinBor":"0","44":"0","LOF":"0","45":"0","LOH":"0","46":"0","intFinish":"0","47":"0","fEx":"0","48":"0","fExt":"0","49":"0","fExl":"0","50":"0","fExr":"0","51":"0","cler":"0","52":"0","fMul":"0","53":"0","commission":"666.999666","54":"666.999666","survey":"666.999666","55":"666.999666","NumItem":"1","56":"1","slideType":"","57":"","horns":"0","58":"0","vsLS":"0","59":"0","vsArched":"0","60":"0","vsFixed":"0","61":"0","vsSecure":"0","62":"0","vsPolished":"0","63":"0","vsJointed":"0","64":"0","vsBay":"0","65":"0","UPVCfStyle":"1","66":"1","UPVCbStyle":"1","67":"1","ALUfStyle":"1","68":"1","ALUbStyle":"1","69":"1","drain":"1","70":"1","ventPos":"1","71":"1","ALUProfile":"Alitherm 600","72":"Alitherm 600"},
{"id":"6776t2dhc3aq","0":"6776t2dhc3aq","Wid":"6776t2dhc3aqnew0.8957906831392683","1":"6776t2dhc3aqnew0.8957906831392683","room":"Plot 2 Bedroom","2":"Plot 2 Bedroom","style":"S150","3":"S150","type":"upvc","4":"upvc","colour":"0","5":"0","RAL":"","6":"","cill":"2","7":"2","width":"1023.0000","8":"1023.0000","height":"1585.0000","9":"1585.0000","fitting":"1","10":"1","comments":"","11":"","spacercol":"1","12":"1","glassstyle":"0","13":"0","handles":"0","14":"0","hinges":"0","15":"0","trickle":"0","16":"0","sash":"0","17":"0","fanlight":"0","18":"0","total":"0.0000","19":"0.0000","g1":"6","20":"6","g2":"6","21":"6","g3":"0","22":"0","g4":"0","23":"0","g5":"0","24":"0","g6":"0","25":"0","g7":"0","26":"0","g8":"0","27":"0","m1":"1023.0000","28":"1023.0000","m2":"1023.0000","29":"1023.0000","m3":"0.0000","30":"0.0000","m4":"0.0000","31":"0.0000","m5":"0.0000","32":"0.0000","m6":"0.0000","33":"0.0000","m7":"0.0000","34":"0.0000","m8":"0.0000","35":"0.0000","t1":"777.5000","36":"777.5000","t2":"777.5000","37":"777.5000","t3":"0.0000","38":"0.0000","t4":"0.0000","39":"0.0000","t5":"0.0000","40":"0.0000","t6":"0.0000","41":"0.0000","t7":"0.0000","42":"0.0000","t8":"0.0000","43":"0.0000","ICwinBor":"0","44":"0","LOF":"0","45":"0","LOH":"0","46":"0","intFinish":"0","47":"0","fEx":"0","48":"0","fExt":"0","49":"0","fExl":"0","50":"0","fExr":"0","51":"0","cler":"0","52":"0","fMul":"0","53":"0","commission":"666.999666","54":"666.999666","survey":"666.999666","55":"666.999666","NumItem":"1","56":"1","slideType":"","57":"","horns":"0","58":"0","vsLS":"0","59":"0","vsArched":"0","60":"0","vsFixed":"0","61":"0","vsSecure":"0","62":"0","vsPolished":"0","63":"0","vsJointed":"0","64":"0","vsBay":"0","65":"0","UPVCfStyle":"1","66":"1","UPVCbStyle":"1","67":"1","ALUfStyle":"1","68":"1","ALUbStyle":"1","69":"1","drain":"1","70":"1","ventPos":"1","71":"1","ALUProfile":"Alitherm 600","72":"Alitherm 600"}]
Within my success function I need to be able to loop through all of the results in each object and use them as I require.
I have tried many of the answers posted on here with no luck, such as:
for (var j = 0; j < result.length; j++){
var windowid = result[j].Wid);
console.log(windowid );
}
logs undefined.
I have also tried many for in and foreach loop examples with no luck.
Thanks in advance for any help.
Parse the result as JSON before the for loop.
Add line result = JSON.parse(result) . As content-type header is not set to application/json your result will be a string which should be parsed as json.
First, you're returning in JSON format, so set that in the ajax request...
$.ajax({
type: "POST",
data: "id="+id,
url: "get-quote-data.php",
dataType: 'json',
cache: false,
success: function (result) {
console.log(result);
}
});
Inside the success function, you can use $.each function to loop through your response...
$.each(result,function(id,value) {
value['id']...
value['Wid']...
etc...
});
So, putting all together...
$.ajax({
type: "POST",
data: "id="+id,
url: "get-quote-data.php",
dataType: 'json',
cache: false,
success: function (result) {
$.each(result,function(id,value) {
var windowid = value['Wid'];
console.log(windowid);
});
}
});
I hope it helps

Convert json object to string

I have the following controller:
public function getPrice()
{
$id = $this->input->post('q');
$data['price'] = $this->emodel->get_peUniformPrice($id);
echo json_encode($data);
}
which outputs this:
"{\"price\":[{\"Price\":\"250\"}]}"
How can I make it like 250? My jQuery:
function showPrice(size) {
$.ajax({
type: "POST",
url: "<?php echo site_url('enrollment/getPrice/');?>",
data: {
q: size
},
success: function(data) {
$("#txtpeUniform").val(data);
},
});
}
I can see that you are using jQuery.. if you want to turn the json object into a javascript object you could do something like
var convertedObject = $.parseJSON($data);
alert(convertedObject.Price);
what this effectively does is converts your Json string into a javascript object which you can reference the properties out of and the get the value from these properties.. let me give you another example
var jsonString = {'Firstname':'Thiren','Lastname':'Govender'};
var jObject = $.parseJSON(jsonString);
console.log(jObject.Firstname) // this will output Thiren.
console.log(jObject.Lastname) // this will output Govender.
modify your code
function showPrice(size) {
$.ajax({
type: "POST",
url: "<?php echo site_url('enrollment/getPrice/');?>",
data: {
q: size
},
success: function(data) {
console.log(data); // make sure this is returning something..
$("#txtpeUniform").val(data);
},
});
}
I hope this helps you..
Regards
The $.ajax method will automatically deserialise the string to an object for you, so you simply need to access the required property. Assuming that you only ever want to retrieve the first price returned in the price array, you can access it directly by index. Try this:
success: function(data) {
$("#txtpeUniform").val(data.price[0].Price); // = 250
},

Passing php string as json to be received by jquery

I am trying to echo a string which is structured like json, but the jquery ajax post is not able to parse it properly. What I want to know is if this string will be treated like json in the jquery json parse just like when we echo a json_encode.
echo '{"mobno":'.$mobno.',"charge":'.$charge.',"capacity":'.$capacity.'}';
ajax code:
jQuery.ajax({
type: "POST",
url: "file.php",
data: { type: $(this).val(), amount: $("#amount").val()},
cache: false,
success: function(response){
var Vals = JSON.parse(response);
if(!Vals){
alert("Error1");
}else{
var capacity = parseInt(Vals.capacity);
if(capacity>0){
alert("worked1");
}else{
alert("worked2");
}
}
}
});
I don't get a single alert out of the 3.
As per your edit and comment, your json string is correct. You just have to change your AJAX request.
Add this setting dataType: "json" in your AJAX request if you're expecting a json object as response from server.
So your AJAX request should be like this:
jQuery.ajax({
type: "POST",
url: "file.php",
data: { type: $(this).val(), amount: $("#amount").val()},
cache: false,
dataType: "json",
success: function(response){
// you can access json properties like this:
// response.mobno
// response.charge
// response.capacity
var capacity = response.capacity;
if(capacity > 0){
alert("worked1");
}else{
alert("worked2");
}
}
});
Just so JavaScript can differ string and properties of json, please use double quote for starting and ending the string and for json properties use single quote or vice-versa. Try that out and let me know if you could not figure that out.
As other answers suggest you need to fix the quotes of the JSON the web service is sending back in the response.
Regarding you question, everything sent back in the response is actually a string. You need to decide what to do with it once it arrives.
One of the ways to allow both client side and server side programs understand what was sent is setting the right content type header.
For JSON the best way is to set the content type header to "application/json".
If you're using php you can do this:
$data = /** whatever you're serializing **/;
header('Content-Type: application/json');
echo json_encode($data);
On the client side jquery ajax you can do this:
$.ajax({
dataType: "json",
url: url,
data: data,
success: function(data, textStatus, jqXHR){}
});
In this example the "data" parameter passed to the "success" callback function is already a js object (after JSON.parse). This is due to the use of the "dataType" parameter in the ajax declaration.
Optionally, you can do this manually and write a simple $.post which receives a string and do the JSON.parse yourself.
Maybe you should do the manual parsing yourself at first, and use the console.log(data) before and after the parsing so you'd know you're doing it correctly. Then, move on to the automatic way with "dataType" set to "json".
Please see #Rajdeep Paul's JSON string correction. Then, have your response JSON object remapped to an array.
JSON string
echo "{\"mobno\":\"".$mobno."\",\"charge\":\"".$charge."\",\"capacity\":\"".$capacity."\"}";
Ajax
$.ajax({
type: "POST",
url: "file.php",
data: { type: $(this).val(), amount: $("#amount").val()},
cache: false,
success: function(response){
// map JSON object to one-dimensional array
var Vals = $.map( JSON.parse(response), function(el) { return el });
if(!Vals){
alert("Error1");
}else{
var count = parseInt(Vals.length);
if(count>0){
alert("worked1");
}else{
alert("worked2");
}
}
}
});
Reference: Converting JSON Object into Javascript array

How to pass json data from one javascript to another

Guys here the first script is designed to take static .json files to display certain content and animate them. The code snippet is
var self = this;
$.getJSON('data/post_'+ index +'.json', function(d){
self.postCache[index] = d;
callback(d)
but I want to modify it to so it could take data from database. I got the data in the same format as it was in static json files and my question is how can I pass that data to this script so that it work as it should.
I am sending request using ajax
$(function ()
{
$.ajax({
url: 'api.php',
data: "<?php echo $data?>",
dataType: 'json',
success: function(data)
{
//I really dont know what to write here :(
}
});
});
and the api.php file is getting data from database and I an encoding the data to json using json_encode
var self = this;
$.post('api.php',
{"post_id": index},
success: function(d)
{
self.postCache[index] = d;
callback(d);
});
see http://api.jquery.com/jquery.post/
In api.php do a SQL query where the post_id = $_POST['post_id'] then echo json_encode($database_row);
$.getJSON just calls $.ajax with some predefined values automatically set for you. This means, since you said the data is the same, that you can do exactly the same as you were doing previously.
Keep a reference to this
Make your async call
in the success function, save your reference and execute your callback
var self = this;
$.ajax({
url: 'api.php',
data: "<?php echo $data?>",
dataType: 'json',
success: function(data)
{
self.postCache[index] = data;
callback(data);
}
});

Issue in getting a property in a JSON file using jQuery GET

I ma using jQuery get to retrieve a simple property on a JSON file.
With the following script I get undefined.
What am I doing wrong here?
<script>
$(document).ready(function() {
var urlOriginal = 'http://xxx.com/xxx/xxx/xxx/resources.js';
var urlResource = 'proxy_dr3.php?proxy_url=' + encodeURIComponent(urlOriginal);
$.get(urlResource, function(data) {
console.log(data); // I can see all the content from the JSON FILE
console.log(data.urlPage); // undefined - PROBLEM HERE
var urlHTML = data.urlPage;
/*$.get(urlHTML, function(data) {
$('#result').html(data);
});*/
});
});
</script>
content for resource.js is json
{
"urlPage": "http://xxx.com/xxx/xxx/xxx/article_517d960f0cf2fe38916a2f9d.html"
}
The result type in Network is text/html. After loading resource.js
$.get won't guess it's JSON as the mime type your server gives is wrong.
You could parse the provided value (which is probably a string) using JSON.parse but you should use $.getJSON, so that the callback receives a parsed value.
$.getJSON(urlResource, function(data) {
console.log(data);
console.log(data.urlPage);
});
you can use any one method which is best suitable for your app.
$.ajax({
type: "GET",
data: "ur data",
url: "ur url",
contentType: "application/json; charset=utf-8",
success: function(data) {
}
});
or you can use $.getJSON function

Categories