How to make php array to be a javascript array? [duplicate] - javascript

This question already has answers here:
Convert php array to Javascript
(21 answers)
Closed 4 years ago.
I have file php that send value in array by query to ajax.
$sql = "SELECT * FROM populasi INNER JOIN waktu ON populasi.idWaktu = waktu.id WHERE waktu.jam = $jam";
$result = $con->query($sql);
$points=array();
foreach ($result as $m) {
$points[] = 'new google.maps.LatLng('.$m[x].', '.$m[y].')';
}
print_r($points);
this ajax will receive a value from php file and I want the value to be a javascript array like "var points". Can you help me how to do it ? Thanks
$.ajax({
type: "POST",
url: "proses.php",
data: {
jam: slider.value,
},
success: function(response){
//example array points
var points = [
new google.maps.LatLng(-7.320339, 112.768071),
new google.maps.LatLng(-7.320233, 112.768446),
];
}
});

can you please try below code
The PHP json_encode function translates the data passed to it to a JSON string which can then be output to a JavaScript variable.get response and used to your javascript code
<?php $json_points = json_encode($points); ?>

A good solution for this is to convert data to JSON format in php and pass it to your js code
in your php:
$sql = "SELECT * FROM populasi INNER JOIN waktu ON populasi.idWaktu = waktu.id WHERE waktu.jam = $jam";
$result = $con->query($sql);
$result = json_encode($result);
echo($result);
in js:
$.ajax({
type: "POST",
url: "proses.php",
data: {jam:slider.value,
},
success: function(response){
response=JSON.parse(response);
var points=[];
for(var i=0; i<response.length; i++){
var responsePoint=response[i];
points.push(new google.maps.LatLng(responsePoint.x, responsePoint.y));
}
}
});

Related

How to get values of encoded json using php in ajax response?

echo json_encode(array('out' => $out, 'total' => $total ));
Hi, I am getting a JSON data as below using the above PHP code.
var result = {"out":"[{\"tax\":\"SGST#9%\",\"percent\":7.75},{\"tax\":\"CGST#9%\",\"percent\":7.75},{\"tax\":\"SGST#2.5%\",\"percent\":3.11},{\"tax\":\"CGST#2.5%\",\"percent\":3.11}]","total":210}
I need to get the elements in a separate variable like below
var out = [{"tax":"SGST#9%","percent":7.75},{"tax":"CGST#9%","percent":7.75},{"tax":"SGST#2.5%","percent":3.11},{"tax":"CGST#2.5%","percent":3.11}];
var total = 210;
I tried so far with the below codes.
result = JSON.stringify(result);
result = result.replace(/\\/g, "");
var obj3 = JSON.parse(result);
alert(obj3[0]);
But i am not getting any output.
The basic problem is that $out is JSON to start with (so it ends up being double encoded), but it doesn't make sense for it to be JSON in the context.
You could just convert it to a PHP data structure before converting the wider array to JSON:
$out = json_decode($out, true);
$json = json_encode(array('out' => $out, 'total' => $total ));
echo "var result = $json;";
If you don't want to touch the PHP, you can work around that in JavaScript:
$out = json_decode($out, true);
$json = json_encode(array('out' => $out, 'total' => $total ));
echo "var result = $json;";
?>
var out_json = result.out;
var out = JSON.parse(out_json);
In your Ajax setup, add JSON
dataType: 'JSON',
Then in your success function,
success: function(result) {
console.log(result.tax);//gives you the value for the tax key provided it's defined in the php response array
},

convert js array to php array and check its content

I want to sent a JS array to remote php server and convert it to a php array.
To check if php array is equal to js array I'm trying to get its members inside result div, but without success.
var rlist = ["title1", "title2", "title3"];
var b = JSON.stringify(rlist);
$.ajax({
url: 'reorder.php',
type: 'post',
data: {'b': b},
success: function(data) {
$("#result").html(data);
}
});
reorder.php
$rlist = json_decode( $_POST['b'], true );
echo $rlist;
try to put this code in the reorder.php
$rlist = json_decode( $_POST['b'], true );
foreach ($rlist as $value) {
echo "<div>" . $value . "</div>";
}
You can use json_decode as jQuery ajax submits it's arrays as json.
// Use as object
$json = json_decode($_POST['postdata']);
// Use as
echo $json->seomthign
$json = $_POST['postdata'];
// Output array
echo "<pre>";
var_dump(json_decode($json));
echo "</pre>";

How to retrieve two results from SQL Database

I am using PHP server with SQL Database using CPanel.
I am retrieving values (numbers) from the database using SQL queries and pass them to a separate javascript file.
In order to achieve that, I first created a query on a separate PHP file which gets the information:
File Name: SQLamountofusers.php
<?php
$query = sprintf("SELECT COUNT( * ) as c
FROM `applications`
JOIN `users` ON ( users.id = applications.id_m )
WHERE `cdate` > CURRENT_DATE -30");
$result = mysql_query($query);
$res = mysql_fetch_assoc($result);
echo json_encode($res[c]);
mysql_free_result($result);
?>
The echoed result is then passed to a JS file using AJAX:
File Name: canvas.js
$(document).ready( function() {
$(usersreport).click(function() {
$.ajax({
type: 'POST',
url: 'js/SQLamountofusers.php',
data: 'id=usersreport',
dataType: 'json',
cache: false,
success: function(result) {
var num = Number(result);
{ label: "Active", y: num},
{ label: "Inactive", y: 0 },
});
});
Now this is what I want to achieve but don't know how:
I want to pass to the canvas.js file two values, one is the active users (which requires one query from the DB, which is already written above) and the other is the inactive users (which requires another query) - So how can I get two results into the JS file?
Should I create another separate PHP file with the other query or is there another way to achieve it?
Try adjusting your query to something like:
<?php
$query = sprintf("SELECT
COUNT(DISTINCT IF(cdate > CURRENT_DATE - 30, users.id, NULL)) AS c,
COUNT(DISTINCT IF(cdate <= CURRENT_DATE - 30, users.id, NULL)) AS d
FROM applications
JOIN users ON users.id = applications.id_m");
$result = mysql_query($query);
$res = mysql_fetch_assoc($query);
echo json_encode($res);
mysql_free_result($result);
?>
Then you can adjust your canvas.js to pull the result as
$(document).ready( function() {
$(usersreport).click(function() {
$.ajax({
type: 'POST',
url: 'js/SQLamountofusers.php',
data: 'id=usersreport',
dataType: 'json',
cache: false,
success: function(result) {
var num = Number(result.c);
var num2 = Number(result.d);
{ label: "Active", y: num},
{ label: "Inactive", y: num2 },
});
});
Disclaimer: I have not tested this code, just offering this as a potential solution you may try.
File Name: SQLamountofusers.php
<?php
$query = "SELECT COUNT( * ) as c
FROM `applications`
JOIN `users` ON ( users.id = applications.id_m )
WHERE `cdate` > CURRENT_DATE -30";
$result = mysql_query($query);
$res = mysql_fetch_assoc($result);
$data = array('active' => $res['c']);
$query2 = "SELECT ...";
$result2 = mysql_query($query2);
$res2 = mysql_fetch_assoc($result2);
$data['inactive'] = $res2['c']);
echo json_encode($data);
?>
File Name: canvas.js
$(document).ready( function() {
$(usersreport).click(function() {
$.ajax({
type: 'POST',
url: 'js/SQLamountofusers.php',
data: 'id=usersreport',
dataType: 'json',
cache: false,
success: function(result) {
{ label: "Active", y: result.active},
{ label: "Inactive", y: result.inactive},
});
});
Just replace second sql query with the one you need.
EDIT: Basically you can pass through json arrays and objects. So you can easily pass as many numbers as you want. Prepare php array with values you need, then json_encode() it and you will get an object or array with values on js side.
If you encode php array without keys like $arr = array(1,2,3); you will get array on js side. You can reference it as a[0], a[1] etc.
If you encode associative php array, i.e. with keys like $arr = array('k1'=>1, 'k2'=>2); you will get an object on js side. And reference it as o.k1, o.k2 etc.
Try:
$query = "SELECT COUNT( * ) as c
FROM applications
JOIN users ON ( users.id = applications.id_m )
WHERE cdate > CURRENT_DATE -30";
Without sprintf();

Ajax read PHP generated json

So I want to send a json to an ajax call but I don't know how to read the json when is sent. And also my json looks strange because of the backslashes...
This is my ajax:
function find(){
var type = $('#object_type').val();
$.ajax({
type : 'POST',
url : 'get_user.php',
data : {
'type' : type
},
dataType : 'json',
error : function(response){
alert('SOMETHING WENT WRONG');
},
success : function(response){
This is what I get as a response:
"[{\"name\":\"Test\",\"link\":\"test.php\"},{\"name\":\"Test2\",\"link\":\"test2
.php\"}]"
}
});
}
This is my PHP function:
$type = $_POST['type'];
$user_array;
$user = mysqli_query($conn, "SELECT name,link FROM user WHERE `type` LIKE '%".$type."%'") or die();
while ($row = mysqli_fetch_array($user, MYSQLI_ASSOC)) {
$row_array['name'] = $row['name'];
$row_array['link'] = $row['link'];
array_push($user_array, $row_array);
}
mysqli_close($conn);
$result = json_encode($user_array, 128);
echo json_encode($result);
First change that you should make :
You don't need to encode two times
$result = json_encode($user_array, 128);
echo json_encode($result);
should be
$result = json_encode($user_array, 128);
echo $result;
Now the response should look like
[{"name":"Test","link":"test.php"},{"name":"Test2","link":"test2
.php"}]
which is a valid Javascript Array and can be accessed using following code :
var len = response.length;
for(i=0;i<len;i++){
console.log(response[i].name);
console.log(response[i].link);
}
As provided in techierishi's answer. Do not encode your response twice. Just do
echo $result;
The JSON should be valid and parsed, why?
json_encode is used on a valid PHP array returned from a MySQLi query.
dataType is used, explicitly forcing jQuery to JSON.parse the response and no errors where raised during that process.
The JSON that is returned has the following structure
ROOT
ARRAY
ARRAY OBJECT
OBJECT PROPERTY
To address something like that:
root[array index].property
Will give you the array's value, which is an object. That object has multiple properties.
[] means array
{} means object
So [{name:"value 1"},{name:"value 2"}] is actually
ARRAY
[0].name = value 1
[1].name = value 2
So retrieving information like name from your JSON will be:
response[0].name; // = test

json_encode with multidimensional array returning string "array" instead of data

I am passing a multidimensional array back to a .php file using json, jquery, and ajax. My goal is essentially to fill a drop down box (id=project) with multiple entries. Here's some code snippets:
$("#turninId").change(function() {
var user_id = $("#turninId").val();
$.ajax ( {
url:"send_input.php",
type: "POST",
dataType: "json",
data:{id_selection: user_id},
success:function(response) {
for (var i=0; i<response.proj.length; i++) {
$("#exp").html(response.proj[i]);
$("#project").html(response.proj[i]); } });
});
In send_input.php (backend), I query a db, and send the information to an array. Then I use json_encode.
$query="SELECT project FROM main";
$results = $db->query($query);
while ($row_id = $results->fetchArray()) {
$proj_option[] = "<option value=\"".$row_id['project']."\">".$row_id['project']."</option>\n";
$pselected=$row_id['project'];
}
$output = array( "proj" => "$proj_option");
echo json_encode($output);
My problem is that this is RETURNING THE STRING "Array".
For example, if I do: response.proj[0], I get "A" returned.
What gives? I've seen a few people with questions about this error, but no definite solution. Any help?
This is because you are casting $proj_option to a string by enclosing it in quotes. Just remove the quotes and you will get the array.

Categories

Resources