convert js array to php array and check its content - javascript

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>";

Related

" " instead of [ ] in JSON

I used a php variable into Javascript like this-
var Coordinates = <?php echo json_encode($coords); ?>;
And now I want to stringify it so I used
var JSON_Coordinates = JSON.stringify(Coordinates);
the result is
["-98.47442960102632,38.51861967935271","-98.46128420909388,38.17510666712973","-97.91584295178713,38.17274814619617", -"97.91882439611877,38.51683243137235", "-98.47442960102632,38.51861967935271"]
But I want It to be like this-
[[-98.47442960102632,38.51861967935271],[-98.46128420909388,38.17510666712973],[-97.91584295178713,38.17274814619617], [-97.91882439611877,38.51683243137235], [-98.47442960102632,38.51861967935271]]
So how to replace " " with [ ]?
You could fix it on the server side:
$coords = array(
'-98.47442960102632,38.51861967935271',
'-98.46128420909388,38.17510666712973',
'-97.91584295178713,38.17274814619617',
'-97.91882439611877,38.51683243137235',
'-98.47442960102632,38.51861967935271'
);
$coords = array_map(function($coord) {
list($lat, $lon) = explode(",", $coord);
return array((float) $lat, (float) $lon);
}, $coords);
echo json_encode($coords);
Output (pretty printed):
[
[-98.474429601026, 38.518619679353],
[-98.461284209094, 38.17510666713],
[-97.915842951787, 38.172748146196],
[-97.918824396119, 38.516832431372],
[-98.474429601026, 38.518619679353]
]
Before converting to json in php, you could convert each coords string to an array in a loop, then ensure values are not strings but numeric using JSON_NUMERIC_CHECK
<?php
foreach ($coords as &$value) {
$value = explode(',', $value); // prevent to array like ["23","45"]
}
unset($value); // avoid reuse of &reference variable by mistake
echo json_encode($coords, JSON_NUMERIC_CHECK);
?>

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

seperate each array value from array passed by ajax -- php

I passed an array using Ajax and i echoed it in php , it works good. But i don't know how to separate its value and find its length.
Here is the code:
var myCheckboxes = new Array();
$(".book_type:checked").each(function() {
myCheckboxes.push($(this).val());
});
$.post("s.php?c="+category+"&k="+myCheckboxes,{data : "some data"}, function(response){
$("#show_result").html(response);
And the php is:
$a=$_GET['k'];
echo $a;
it displays the values of all checkbox like this
all,0,1,2,3,4
How can i find $a length as array?. if i use sizeof($a) it shows as 1.
Also how to separate those values into each single value.
Any suggestion
try like this
$a=$_GET['k'];
$value= explode(",",$a);
echo sizeof($value); //output 6
echo $value[0]; //all
echo $value[1]; //0
echo $value[2]; //1
echo $value[3]; //2
echo $value[4]; //3
echo $value[5]; //4
Try using:
$a=$_GET['k'];
$a=explode(',', $a);
echo count($a);
Pass the value as an array
$.post("s.php", {
data: "some data",
c: category,
k: myCheckboxes
}, function (response) {
$("#show_result").html(response);
})
then
$a=$_GET['k'];
where $a will be an array, so count($a) should give you the length
You should call JSON.stringify in your javascript:
// ⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓
... category+"&k=" + JSON.stringify(myCheckboxes) ...
or, alternatively, use jQuery ajax syntax sugar in your post request:
$.post("s.php", { k: myCheckboxes, ... });
This will provide a json as string passed to controller. From within your controller you should json_decode the received parameters:
$a = $_GET['k'];
print_r(json_decode($a));
Hope this helps.

How can get values from php array using jquery or javascript?

I trying to get data from php array and put in java-script variable. Follwoing are the php arrays.
Array Name
Array
(
[0] => username
[1] => byusers
)
Array Value
Array
(
[0] => user
[1] => 1
)
What I have Try tried
Get php array value in javascript variable
var DATATABLE_SEARCH_NAMES = new Array( "<?php echo (is_array($DATATABLE_SEARCH_DATA_NAMES)) ? $DATATABLE_SEARCH_DATA_NAMES['names'] : 0;?>");
var DATATABLE_SEARCH_VALUES = new Array( "<?php echo (is_array($DATATABLE_SEARCH_DATA_VALUE)) ? $DATATABLE_SEARCH_DATA_VALUE['values'] : 0;?>");
This should do what you ask, it is just a case of converting the PHP arrays to a form that javascript can understand. You can use json_encode() to do that.
$DATATABLE_SEARCH_DATA_NAMES = array('username','byusers');
$DATATABLE_SEARCH_DATA_VALUE = array('user', 1);
$js1 = json_encode($DATATABLE_SEARCH_DATA_NAMES);
$js2 = json_encode($DATATABLE_SEARCH_DATA_VALUE);
//echo $js1.PHP_EOL;
//echo $js2.PHP_EOL;
echo "<script>\n";
echo 'var names = ' . $js1 . ";\n";
echo 'var values = ' . $js2 . ";\n";
echo "</script>\n";
say, you have a PHP array as this:
$arr = array("key1"=>"foo","key2"=>"bar");
the easiest way to put it to javascript is this:
var arr = <?php echo json_encode($arr); ?>;
ending with a JSON object.

php decode json array

I have a php page that receives a json object from javascript page, but i was not able to decode the json in php. How to decode the json and store in php such that $arr[0]=[1,2,34,5,2]; $arr[1]=[2,1,34,5,2]; $arr[2]=[8,1,34,5,2]; in php ?
after removing "myString = JSON.stringify(myObject);"
echo $value; outputs "Array"
echo $value[0]; outputs nothing
echo $value->{"key"}; outputs nothing either
how can i actually get the array contents?
javascript:
var mon=[1,2,34,5,2];
var tue=[2,1,34,5,2];
var wed=[8,1,34,5,2];
var myObject = {'key' :'value','key2':'value','key3':'value'};
myObject.key = mon;
myObject.key2 = tue;
myObject.key3 = wed;
myString = JSON.stringify(myObject); //this line removed
var jsonString = JSON.stringify(myObject);
$.ajax({
type: "POST",
url: "n3.php",
data: {data : jsonString},
cache: false,
success: function(aaa){
alert("OK");
$("#pageContent").html(aaa);
}
});
php:
<?php
$value = json_decode($_POST['data']);
echo $value; //this echos the whole json object
echo $value->{"key"}; //this outputs nothing
?>
You are JSON encoding your data twice on the Javascript side. When you call json_encode in PHP once, you get a JSON encoded object back. That's why echo $value outputs the whole string. If it was a PHP array at this point it would output "Array" or an error in case it was an object, it would not output the whole content.
Either json_decode it again, or don't double encode it in Javascript.

Categories

Resources