I'm trying to convert an object that I get from PHP into an array in Javascript but I don't know how to solve this, I try some solutions I read before do this question but it doesn't work, I got something like this in PHP
$data = explode(',', $articles);
$length = count($data);
for ($i = 0; $i < $length; $i++) {
$products = explode('-', $data[$i]);
$product_key = $products[0];
$quantity = $products[1];
$get_data_product = mysqli_query($connection, "SELECT * FROM articles WHERE id_article = '".$product_key."' AND id_user = '".$id_user."'") or die (mysqli_error($connection));
$get_data_product = mysqli_fetch_assoc($get_data_product);
$article_name = $get_data_product['name'];
$article_price = $get_data_product['price'];
$info[$i] = array('name' => $article_name, 'quantity' => $quantity, 'price' => $article_price);
}
echo json_encode($info);
And in Javascript
success: function(info) {
var data = JSON.stringify(info);
console.log(data);
}
Console log show this
[{"name":"prueba 2","quantity":"4","price":"100"}]
I tried to read them all with ths code but it is showing data, only when I use console log or alert
$.each(data, function(i) {
$('#content').append('<tr class="text-center">' +
'<td>' + data[i].quantity + '</td>' +
'<td>' + data[i].name + '</td>' +
'</tr>');
});
As prodigitalson notes in the comments - and is effectively the answer - you converted your data into a JSON object in PHP, but then convert it needlessly into a string, so you then can't manipulate it at all.
E.g: JSON.stringify([{test: 1}]) becomes "[{test: 1}]".
Removing that, you will then be able to loop on it in your original way, or you can loop on it using a standard javascript foreach where data is your response in your callback containing [{"name":"prueba 2","quantity":"4","price":"100"}]:
data.forEach(function (e) {
$('#content').append(
'<tr class="text-center">\n' +
'<td>' + e.quantity + '</td>\n' +
'<td>' + e.name + '</td>\n' +
'</tr>\n'
);
});
PHP End Sample Code:
<?php
for ($i = 0; $i < 3; $i++) {
$quantity=rand(5,10);
$price=rand(500,1000);
$info[$i] = array('name' =>'prueba'.$i, 'quantity' =>"$quantity", 'price' => "$price");
}
echo json_encode($info);
?>
JQuery End:
<!DOCTYPE html>
<html>
<head>
<title>Json</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({ type:"POST", url: "array.php", dataType: "json", success: function(result){
console.log(result);
for(i=0; i<result.length;i++)
{
console.log(result[i]);
console.log(result[i].name);
console.log(result[i].quantity);
console.log(result[i].price);
}
}});
});
</script>
</head>
<body>
</body>
</html>
Sample Response in the test:
[{"name":"prueba0","quantity":"8","price":"574"},{"name":"prueba1","quantity":"8","price":"555"},{"name"
:"prueba2","quantity":"7","price":"901"}]
Reference :
http://www.jsoneditoronline.org/?id=5e23cd942a949e86545fa320a65ff0e7
Hope this solves your problem. Thanks.
I think your code is fine, if you do this in javascript code:
success: function(info) {
var data = JSON.stringify(info);
alert(data[0].name);
}
That alert should show the expected value of name property of data object.
your console.log(data); show json arry that is
[{"name":"prueba 2","quantity":"4","price":"100"}]
try this
$dataobj = data1=json_decode(data);
$arry = (array) $dataobj;
try this code
Related
I have a dropdown and when it's changed then I am calling the ajax depending upon the dropdown value. If the dropdown value is 2 then it will call the ajax and display the data.
Now my issue is, 1) I am getting the output but also i am getting undefined.
2) After getting the output I have to display inside if-else condition but it's only displaying undefined.
Controller
public function getRMname(){
$result= $this->Employee_model->getRMname();
if($result)
{
foreach ($result as $key => $value) {
$data[] = array('rmfirstname' =>$value->firstname , 'rmlastname'=>$value->lastname,'rmid'=>$value->id);
}
}
else
{
$data = "false";
}
echo json_encode($data);
}
Script
$(document).on('change', '.pp_Status', function(event) {
var addrm;
if ($(this).val() == '2') {
$.ajax({
type: "POST",
url: baseUrl + "/Employee_control/getRMname",
//data: {},
dataType: 'json',
success: function(response) {
addrm += '<select name="addrm" class="input-wrapper"><option value="" selected disabled>Select</option>';
$.each(response, function(key, data) {
addrm += '<option value="' + data.rmid + '">' + data.rmfirstname + ' ' + data.rmlastname + '</option>';
});
addrm += '</select>';
}
});
} else {
addrm = '';
}
if (somecondition) {
} else {
echo addrm;
//displaying addrm variable here
}
});
use =''; in defing variable
var addrm=''; instead of
var addrm;
beacause Variable means anything that can vary, you should have to first declare empty String and then after String Concatenate with += symbol.
To be on the safe side, define the variable as
var addrm = '';
Take out the else state so it only runs when selected option is 2.
Finally, the block which checks if selected option is 2 gets executed irrespective of the selected option because you aren't targeting properly.
It should be:
if( $(this).find(':selected').val() == '2' ) {}
Because what you have there doesn't check for the selected value, try console logging to check the value returned:
console.log($(this).find(':selected').val());
I have PHP loop. I take the id, lat, lon data from record, passed it to script to do some calculations, then I passed this data to AJAX which will save the results of that calculation in MySQL DB, if it's successful then it will add the line of confirmation text to a results div.
My Code (I did trim it to keep focus on the issue)
<div id="distance_results"></div>
<?php
$result = $mysqli->query("SELECT * FROM test")
while($row = $result->fetch_array()) {
$id = $row['id'];
$city = $row['city'];
$lat = $row['lat'];
$lon = $row['lon'];
$driving_from = "51.528308,-0.3817765";
$driving_to = "$lat,$lon";
?>
<script>
var id = '<?php echo $id ?>';
var city = '<?php echo $city ?>';
var start = '<?php echo $driving_from ?>';
var end = '<?php echo $driving_to ?>';
// code
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
// code
var mi = response.routes[0].legs[0].distance.value;
console.log(id);
console.log(city);
console.log(mi);
//Ajax Begin
$.ajax({
type: 'post',
url: 'test-dc-upd.php',
data: {'updateid': id, 'distance': mi},
success: function() {
html="Distance between London and " + city + " is " + mi;
$("#distance_results").append("<p>"+html+"</p>");
}
});
//Ajax End
} else {}
});
</script>
<?php } ?>
AND CODE FOR "test-dc-upd.php"
$id = $_POST['updateid'];
$distance = $_POST['distance'];
$result = $mysqli->query("UPDATE test SET distance='$distance' WHERE id='$id' LIMIT 1");
So PHP is looping thru MySQL DB, when but when I look at console:
'mi' values are calculated well according to lat / lon;
PROBLEMS:
1) 'id' and 'city' values stay the same (values of last record in the loop);
2) AJAX is updating value of last record in the loop only
So it obvious there is a some issue with the loop.
Any suggestion to what i do wrong?
Change this
$("<p>"+ html +"</p>").append("#distance_results");
To
$("#distance_results").append("<p>"+ html +"</p>");
Your jquery code is wrong. First you have to put selector and in append function the html code.
Nita, change the success function from:
success: function() {
html="Distance between CITYX and " + city + " is " + mi;
$("<p>"+ html +"</p>").append("#distance_results");
}
});
To
success: function() {
html="Distance between CITYX and " + city + " is " + mi;
$("#distance_results").append(<p>"+ html +"</p>);
// this will append the dynamic content to #distance_results
}
});
Explanation:
To put a dynamic content is some html object you have to first prepare
the content than select the html object and put the content into it.
In a loop calling ajax request is not a good practice we can easily pass array of values to javascript using the function implode like this
this implode function is for single dimensional array,
var ar = <?php echo '["' . implode('", "', $ar) . '"]' ?>;
For your question you need to create a multi dimensional array for the result like this ..
<?php
$result = $mysqli->query("SELECT * FROM test");
$arr= array();
while($row = $result->fetch_array()) {
$arr[]=array('id'=>$row['id'],'city'=>$row['city],'lat'=>$row['lat']...etc);
}
?>
afetr that you can pass each item in the array to javascript like this
var idArray= <?php echo '["' . implode(', ', array_column($arr, 'id')); . '"]' ?>;
var cityArray= <?php echo '["' . implode(', ', array_column($arr, 'city')); . '"]' ?>;
you can get each tag as array in javascript after that using a sing ajax request pass all javascript array to php script. and manipulate in the server side .
Your ajax request is like this
$.ajax({
type: 'post',
url: 'test-dc-upd.php',
data: {
'idArray':idArray,
'cityArray':cityArray, //etc you need pass all array like this
},
success: function(data) {
// your success code goes here
}
});
Note that array_column() function only supported by php 5.3 or above
I manage to do it a little different way i was hoping for ( But distance and travel time has been calculate for more then 3000 locations).
So what i did is to make sure mysql (test-dc.php) finds record where distance and travel time has not been calculated, makes calculation, update record with Ajax. Ajax on succesion opens the (test-dc.php) again, And is looping thru all results till there is nothing else to calculate. Had to refesh few times but thats fine, job done.
Adjustment to Mysql query:
$result = $mysqli->query("SELECT * FROM test WHERE distance='' LIMIT 1")
and to AJAX:
success: function() {
html="Distance between London and " + city + " is " + mi;
$("#distance_results").append("<p>"+html+"</p>");
location.href = "test-dc.php"
}
So that did the trick, but i still belive there is a better way of achiving the same result, i will be happy if someone could help me to figure it out.
<script>
$("#submit").click(function () {
var newhour= [];
for (var i = 0; i < arrayNumbers.length; i++) {
newhour.push(arrayNumbers[i].toString().split(','));
console.log("each: " + newhour[i]); // output: each: 07:00,08:30
each: 18:00,19:00
}
console.log("all: " + newhour); //output: all: 07:00,08:30,18:00,19:00
var jsonString = JSON.stringify(newhour);
$.ajax({
type: "POST",
url: "exp.php",
data:{data: jsonString},
cache: false,
success: function(){
alert("OK");
}
});
});
<script>
I want to pass the newhour array values to php and use them to insert into a table.
so php file, exp.php:
$data = explode(",", $_POST['data']);
foreach($data as $d){
echo $d;
$sql = "insert into exp_table (hour) values ('$d')";
mysql_query($sql);
}
However I can not take the values. What is wrong with the code?
Could you please help me?
Thanks in advance.
according to the answers i tried this on php side, but it returns NULL.
$data = json_decode($_POST['data'],true);
//$data = explode(",", $_POST['data']);
echo "data: " .$data;
var_dump($data); // no output
foreach($data as $d){
echo $d; // no output
}
You do not have to stringify an array in the javascript.
.ajax looks after all that.
pass
data: {newhours: newhour},
then you will get $_POST['newhours'] in the PHP code which will be the array you had in javascript.
In Ajax there is not "type" params, use "method".
Beside that everything should works, you might need to decode the json using json_decode($_POST['data']) on in your php file.
Hopes it helps !
Nic
Pass the array without JSON.stringify in ajax data post. And fetch the data in php file using $_POST['data'].
I just have tried below code and it working great.
<?php
if(isset($_POST['data'])){
print_r($_POST);exit;
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
var newhour= [];
arrayNumbers = [['07:00','08:30'],['08:30','18:00','19:00']];
for (var i = 0; i < arrayNumbers.length; i++) {
newhour.push(arrayNumbers[i].toString().split(','));
console.log("each: " + newhour[i]);
// output: each: 07:00,08:30 each: 18:00,19:00
}
console.log("all: " + newhour); //output: all: 07:00,08:30,18:00,19:00
$.ajax({
type: "POST",
url: "abc.php",
data:{data: newhour},
cache: false,
success: function(data){
console.log(data);
}
});
});
</script>
my Php code;
$sql = "SELECT * FROM login_speak";
if ($result = mysqli_query($con, $sql))
{
$resultArray = array();
$tempArray = array();
while($row = $result->fetch_assoc())
{
$tempArray[] = $row;
}
$resultArray = json_encode($tempArray);
echo $resultArray;
}
mysqli_close($con);
?>
my jquery code;
$.getJSON("url.php", function(data){
$("ul").empty();
$.each(data.result, function(){
$("ul").append("<li>Name:"+this['Name']+"</li>");
alert("kj");
});
});
I have done several things ,But nothing works.I php is correct and I have problem in script ,I guess.
Please give me the answer ,What wrong is done.
Thanks
json_encode from php can be accessed easily in a Javascript varible
There are many ways of doing this, however consider the simple way first if it works with the array you are sending.
in your example - assuming jquery:
var valu = [];
$.ajax(url: "url.php",
success: function(data){
valu=data;
});
see: http://www.dyn-web.com/tutorials/php-js/json/array.php
works for numeric and associative arrays.
I think you want change your code to something like this..
$.each(data.result, function(index,value){
$("ul").append("<li>Name:"+value.name+"</li>");
alert("kj");
});
Heres what I would do.
$.ajax({
url: "url.php",
type: "GET",
dataType: 'json'
}).done(function (data) {
$.each(codes, function(key,value){
$("ul").append('<option value="' + key + '">' + key + ' - ' + value + '</option>');
});
}).fail(function (jqXHR, textStatus, error) {
alert("error message");
console.log("error message: " + error);
});
I'm trying to perform some PHP code and then pass it's results to another PHP script through jquery.
One of these results is an array, and I'm passing it to a GET so it gets to the other script. (alot of work, but I can't have page reloads even tho I have to use PHP).
The problem occurs when I'm trying to put the PHP variable through JQuery.
What I have to do this for me is:
var _leafs = <?php echo json_encode($leafs); ?>;
When I run json_encode on $leafs and then print the result (all using PHP), it gives me a json array that has been successfully validated by JSONLint.
When I use the above code and alert() the result it's missing the brackets and quotes.
Even weirder is when I pass it through like so:
$.get('set_fields.php?pt=' + _path + '&lf' + _leafs, function(data) {
The result is this:
" string(4) "
"
Which shows up to be a <br> in my html reader.
Am I missing something when I'm converting it to json?
Additional code:
<?php
// Fetch the XML from the URL
if (!$xml = file_get_contents($_GET['url'])) {
// The XML file could not be reached
echo 'Error loading XML. Please check the URL.';
} else {
// Get the XML file
$dom = new DOMDocument();
$dom->loadXml($xml);
$xpath = new DOMXpath($dom);
$paths = [];
$leafs = [];
foreach ($xpath->evaluate('//*|//#*') as $node) {
$isLeaf = !($xpath->evaluate('count(#*|*) > 0', $node));
$path = '';
foreach ($xpath->evaluate('ancestor::*', $node) as $parent) {
$path .= '/'.$parent->nodeName;
}
$path .= '/'.($node instanceOf DOMAttr ? '#' : '').$node->nodeName;
if ($isLeaf) {
$leafs[$path] = TRUE;
} else {
$paths[$path] = TRUE;
}
}
$paths = array_keys($paths);
$leafs = array_keys($leafs);
echo "Choose a path<br><br>
<form>
<select id='field_dropdown'>";
foreach($paths as $value) {
echo "<option value='".$value."'>".$value."</option>";
}
echo " </select>
<button id='send_path'>Send path</button>
</form>
";
}
?>
<script>
$(document).ready(function() {
$('#send_path').click(function() {
var _path = $("#field_dropdown").val();
// Get the leafs array and send it as a json string to set_fields.php
var _leafs = <?php echo json_encode($leafs); ?>;
$.get('set_fields.php?pt=' + _path + '&lf=' + _leafs, function(data) {
$('#fields').append(data);
}).error(function() {
$('#fields').html('Error calling XML script. Please make sure there is no error in the XML file.');
});
return false;
});
});
</script>
And here the code where I want the json array to end up (and then get turned back into a PHP array).
<?php
// Match all the fields to the values
$path = $_GET['pt'];
$leafs = json_decode($_GET['lf']);
$fieldLeafs = [];
$pathLength = strlen($path) + 1;
foreach ($leafs as $leaf) { if (0 === strpos($leaf, $path.'/')) { $fieldLeafs[] = substr($leaf, $pathLength); } }
var_dump($path."<br>");
var_dump($leafs."<br>");
?>
What if you get the array through jquery instead of echoing it?
<input id="hidden-value" value="<?php echo json_encode($leafs); ?>" />
and then
var _leafs = $('#hidden-value').val();
What about adding an = after the lf query parameter when you build the get URI?
$.get('set_fields.php?pt=' + _path + '&lf=' + _leafs, ...
Just write 'json' in the last parameter of get method:
$.get('set_fields.php?pt=' + _path + '&lf' + _leafs, function(data) {
$('#fields').append(data);
},'json')//<-- this
.error(function() {
$('#fields').html('Error calling XML script. Please make sure there is no error in the XML file.');
});
Did you try this?
var _leafs = [<?php foreach($leafs as $leaf){ echo "'$leaf',"; } ?>]