I use jquery and ajax to retrieve a dynamically made array made in php, like so:
$json = array();
while ($row = $stmt->fetch_assoc()) {
$json['item_'.$row['id']] = $row['name'];
}
header('Content-type: application/json; charset=utf-8');
echo json_encode($json);
exit;
If I test the php file in browser, it outputs:
{"item_3":"Simon","item_1":"Miriam","item_2":"Shareen"}
So far so good. But how do I use that array in jquery?
I have this jquery ajax:
$.getJSON( "json.php", function(data) {
console.log(data);
});
And testing that page in browser, it put this in console:
Object {item_3: "Simon", item_1: "Miriam", item_2: "Shareen"}
And that's ok right? Or should item_x also be in quotes?
Now, how do I USE that array in jquery?
If I try console.log(data[0]) it puts undefined
As i mentioned in comments, php associative arrays become javascript objects, which cant be accessed numericaly.
A solution would be to send an array of objects instead:
while ($row = $stmt->fetch_assoc()) {
$json[]= ['key'=>'item_'.$row['id'] , 'value' => $row['name']];
}
the in js:
data[0].key;
data[0].value;
EDIT obviously key is a misleading name in this example, better to call it something else:
$json[]= ['id'=>'item_'.$row['id'] , 'value' => $row['name']];
//js
data[0].id;
Try to use $.each() to iterate through that object,
$.each(data,function(key,val){
console.log(key,val);
});
DEMO
If you want to access it without iterating it then simply use bracket notation
data['item_3'] //Simon
Or directly access it like,
data.item_3 //Simon
Then convert it like an array as per your wish like this,
var obj = {"item_3":"Simon","item_1":"Miriam","item_2":"Shareen"};
var convertedArray = $.map(obj,function(val,key){
var obj = {}; obj[val] = key;
return obj;
});
DEMO
Related
I have a PHP array like this.
Array
(
[0] => hal([[br,1],[cl,4]])
[1] => alk([[nc(1),1,2],[nc(1),3]])
)
How to pass to JavaScript like below.
var hal=[["br",1],[cl,4]];
var alk=[[nc(1),1,2],[nc(1),3]];
I write some code
<script>
var data = <?=json_encode($input);?>; //$input is name of the php array
var hal=[data[0].substring(5,data[0].lastIndexOf(']'))];
var alk=[data[1].substring(5,data[1].lastIndexOf(']'))];
document.write(hal[0]);
</script>
The output is [br,1],[cl,1] and my expected output is like the one below.Any ideas? Thank you.
document.write(hal[0]); => ["br",1]
document.write(hal[0][0]); => ["br"]
If you want multiple variables, you'll want to loop through the array; you can grab the names using a regular expression. If you're trying to turn this into valid data you can parse, like a JSON string, you're going to have to do an awful lot of work; likely wherever you're getting this string from would be a better place to look to. Have them pass you a valid JSON string instead.
<script>
<?php foreach($input as $v) {
preg_match("/(\w+)\((.*)\)/", $v, $matches);
$var = $matches[1];
$val = str_replace("'", "\\'", $matches[2]);
echo "var $var = '$val';\n";
} ?>
</script>
There's a package called Transform PHP Vars to JavaScript by Jeffrey Way that you can use to transfer your variable easily to your Javascript.
First, create an implementation of the Laracasts\Utilities\JavaScript\ViewBinder interface. This class is in charge of inserting the given JavaScript into your view/page.
<?php
class MyAppViewBinder implements Laracasts\Utilities\JavaScript\ViewBinder {
// $js will contain your JS-formatted variable initializations
public function bind($js)
{
// Do what you need to do to add this JavaScript to
// the appropriate place in your app.
}
}
Next, put it all together:
$binder = new MyAppViewBinder;
$javascript = new PHPToJavaScriptTransformer($binder, 'window'); // change window to your desired namespace
$javascript->put(['foo' => 'bar']);
Now, you can access window.foo from your JavaScript.
I found an answer for my problem.Here i pass value from php as string.Then that string convert it to an object.
<?php
$input="hal([[br,1],[cl,4]])";
preg_match('#^([^[]+)?([^)]+)#i',$input, $hal); //get string as '[[br,1],[cl,4]]'
?>
<script>
var hal1 = <?=json_encode($hal[2]);?>; //'[[br,1,2],[cl,1,2]]' pass to javaScript
function toJSObject(str){
str = str.replace(/([a-zA-Z]+)/g, '"$1"');
return (JSON.parse(str))
}
var hal = toJSObject(hal1); // pass to JS object [['br',1,2],['cl',1,2]]
document.write(hal);
</script>
And also get this as right.
document.write(hal[0]); => ["br",1]
document.write(hal[0][0]); => ["br"]
I send Ajax call to AjaxHandler.php page, the AjaxHandler page call other function in Functions.php (other page).
On success i need to return object from AjaxHandler.php, the object need to have 2 params.
Here is the ajax call:
var month_number = document.getElementById("Month").innerHTML;
var year_number = document.getElementById("Year").innerHTML;
$.get("AjaxHandler.php", { "year": year_number, "month": month_number }, function (encodedata) {
var data = JSON.parse(encodedata);
$("#LinesPlace").html(data);
});
Here is the AjaxHandler.php code the need to handle that:
if(isset($_GET['year'],$_GET['month']))
{
$year = $_GET['year'];
$month = $_GET['month'];
$a = getExpenses($year, $month);
echo $a->pharama;
echo $a->pharamb;
$b = object_to_array($a);
echo $b;
return json_encode($b);
}
Now when i put that url:
http://xxxxxxxxx.com/AjaxHandler.php?year=2015&month=09
Its show me the echo of pharama and pharamb but when i try to convert the object to array and then decode it its just not working, i tryed alot but nothing.
Here is the object_to_array function:
//convert php object to array
function object_to_array($data){
if(is_array($data) || is_object($data))
{
$result = array();
foreach($data as $key => $value) {
$result[$key] = $this->object_to_array($value);
}
return $result;
}
return $data;
}
*I taked that function from this site from other question..
Please advice =]
Regards,
Rafael.
If you need to decode the JSON as an array or object, json_decode has a parameter specifically for that: http://php.net/json_decode
mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )
...
assoc
When TRUE, returned objects will be converted into associative arrays.
For example:
$json_as_object = json_decode($json, false);
$json_as_array = json_decode($json, true);
Attempting to manually convert an object into an array should be unnecessary.
You need to encode it very specifically with JSON_UNESCAPED_UNICODE like this:
$jsonObj = json_encode ( string $json, JSON_UNESCAPED_UNICODE);
I have this code in a standard function for this sort of thing
http://php.net/manual/en/function.json-last-error.php
PS. I think you are over checking it in your object to array function. I would probably choose something like: if(is_array($param)){ .. }
Rafael I cant comment need 50 rep or something:D You say: What you mean unnecessary? you mean i can return the object php as is?
Half of what if am saying: you know the things you put into the function obj_to_array() rigth? That what goes in and it ain't an object so why check it? Who will send it? Do you foresee a $_POST incomming all wrapped up as a nice object and ready to go? Like normally the form does a $_POST / $_GET and provides arrays by default as far as I know? And if you produce an obj elsewhere in your code why put use it as input for this function? Don't you know what you are doing somewhere else in your code? Sure you do and as long as you are concise and precise it will never suddenly be a object returned form $_POST or any function normally outputting arrays or integers etc. Check your output as you created it in the first place? Check your web inputs very well (1 time! and for js injections), then only check your types for validating ambiguous output / inputs of your own like an output that can produce an array or a true / false return value. Checking this output for a value of 1 for a TRUE value of the boolean can result in disappointment because:
if the value of $a is 1 in if($a) do something; then a 1 can be the TRUE value returned as the result of the function that produced the thing that we are checking or the result of count($a). If we then assume the array is length 1 because of a misinterpretation of the value of $a then this can give unintended results? You want to be sure that it is the array in $_array($a) that's doing the talking and not the array for example? Thats all to it I think? Or am I rambling (again)?
I'm creating a json in javascript in that way
jsonArr.push({
position: 'WN',
wind: windWN,
wave: waveWN,
sea: seaWN
});
var myJsonString = JSON.stringify(jsonArr);
I'm sending it via an AJAX method with jsonData: jsonData:Ext.encode(myJsonString)
My json array looks like that when I send it :
In PHP side, I'm getting the Json and decoding it that way :
$rawpostdata = file_get_contents("php://input");
$rawpostdata2 = json_decode($rawpostdata, true);
I tried print_r( $rawpostdata2[1]); and got '{', as the second character of the "string", and I can't understand why.
In the other side, I tried print_r($rawpostdata), cut/past the result in a $string and retest my json_decode like that :
$rawpostdata = file_get_contents("php://input");
// print_r($rawpostdata);
$string = '[{"position":"N","wind":"2","wave":"65","sea":"65"},{"position":"E","wind":"3","wave":"5","sea":"6"},{"position":"S","wind":"56","wave":"4","sea":"8"},{"position":"W","wind":"1","wave":"56","sea":"84"},{"position":"NE","wind":"5","wave":"6","sea":"65"},{"position":"ES","wind":"6","wave":"45","sea":"6"},{"position":"SW","wind":"69","wave":"8","sea":"4"},{"position":"WN","wind":"7","wave":"8","sea":"56"}]';
$rawpostdata2 = json_decode($string,true);
print_r ($rawpostdata2[1]);
It gives me the correct result !
Array (
[position] => E
[wind] => 3
[wave] => 5
[sea] => 6 )
Do you have some explanations?
EDIT : I make it working by making another json_decode
$rawpostdata = file_get_contents("php://input");
$rawpostdata2 = json_decode($rawpostdata,true);
$rawpostdata3 = json_decode($rawpostdata2,true);
But I don't really understand...
First, you create json string:
var myJsonString = JSON.stringify(jsonArr);
Then you encode the resulting string into json again:
Ext.encode(myJsonString)
Thus, you have to json_decode() twice in PHP.
Try using $_POST instead of file_get_contets() which gives you a string.
you need to do a type cast on the result of json_decode like this:
<?php
$rawpostdata = file_get_contents("php://input");
$rawpostdata2 = (array) json_decode($rawpostdata,true);
?>
I hope this works for you.. Cheers..!!
I generate a json object inside my php file using json_encode but when I parse it in Javascript I get error unknow token which is because when I print the returned string it is actually html code not a json string.
let's consider the simplest case:
php:
$testjson = '{"result":true,"count":1}';
echo $testjson;
js:
$.get("serverside.php", function(data, status) {
JSON.parse(data); // I get error here
});
how should I use that JSON object from php in javascript?
It probably best you create your json array a bit more dynamically in php :
$testjson = array();
$testjson['result'] = true;
$testjson['count'] = 1;
echo json_encode($testjson);
What Tanantos said is you best bet. I personally would've write it like:
$testjson = array(
"result" => true,
"count" => 1
);
echo json_encode($testjson);
PHP :
$testjson = array(
"result" => true,
"count" => 1
);
echo json_encode($testjson);
js :
$.get('serverside.php', function(json){
console.log(json);
}, 'json');
jquery-1.10.2.min
I've had a good search and am stumped. It may be a simple answer, but after 80 hours of work so far this week, I just can't see it...
In my app I pass some variables to a Web Service, which passes back a single structure containing key/value pairs.
$.ajax({
type: "POST",
url: "it_submitcall.php",
data: {callService: "getcall", callid: $("#callNumber").val()},
dataType: "HTML",
success: function(data){
//do stuff here
},
error: function(data){
// unable to communicate with web service stuff here
}
});
The response I get back is
Array
(
[CALLID] => 44497
[CALLERNAME] => Chris
[TEAMID] => 1175
)
How do I access the elements above in javascript? Any pointers would be greatly appreciated...
Many thanks.
On the PHP side use json_encode to turn the Array into JSON e.g:
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
Then on the JavaScript side use JSON.parse() to get a JavaScript object back - in your case:
success: function(data){
var obj = JSON.parse(data);
},
As #phenomnomnominal notes, you can use json_encode() on a PHP object to turn it to JSON (and, notably, json_decode() to turn it from JSON to a PHP object)
Once you've got that down, nicely, PHP and JS "hash"-like objects act a lot alike (in PHP, we call these associative arrays and in JavaScript, object literals).
In php, you access an array $your_var like this:
$value = $your_var[ 'key' ];
You can also use variables:
$key = 'key';
$value = $your_var[ $key ];
In JavaScript, it's very similar:
var value = your_var[ 'key' ];
Alternatively:
var key = 'key';
var value = your_var[ key ];
And there's one more syntax that's helpful and more efficient when you don't need variable access to a key:
var value = your_var.key