Sending array from PHP to javascript through ajax - php

I have this php code to return many arrays to javascript through ajax.
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
function get_events_data() {
// load SimpleXML
$nodes = new SimpleXMLElement('my_events.xml', null, true);
$event_id = array();
$channel_id = array();
$channel_name = array();
$channel_onclick = array();
$event_site = array();
$event_url = array();
$start_date = array();
$start_time = array();
$end_date = array();
$end_time = array();
$event_notes = array();
$n = 0;
foreach($nodes as $node)
{
$event_id[$n] = $node['id'];
$channel_id[$n] = $node->channel['id'];
$channel_name[$n] = $node->channel->name;
$channel_onclick[$n] = $node->channel->onclick;
$event_site[$n] = $node->event_site->name;
$event_url[$n] = $node->event_site->url;
$start_date[$n] = $node->start_date;
$start_time[$n] = $node->start_time;
$end_date[$n] = $node->end_date;
$end_time[$n] = $node->end_time;
$event_notes[$n] = $node->notes;
$n++;
}
$return['event_id'] = $event_id;
$return['channel_id'] = $channel_id;
$return['channel_name'] = $channel_name;
$return['channel_onclick'] = $channel_onclick;
$return['event_site'] = $event_site;
$return['event_url'] = $event_url;
$return['start_date'] = $start_date;
$return['start_time'] = $start_time;
$return['end_date'] = $end_date;
$return['end_time'] = $end_time;
$return['event_notes'] = $event_notes;
echo json_encode($return);
}
echo get_events_data();
?>
On the javascript side I have this code to access the arrays.
$.ajax({
url: "get_events_data.php",
type: "POST",
dataType : 'json',
data: { },
cache: false,
async: false,
success: function (rdata) {
var alert_data = 'event_id '+rdata.event_id[0]+'<br/>'+
'channel_id '+rdata.channel_id[0]+'<br/>'+
'channel_name '+rdata.channel_name[0]+'<br/>'+
'channel_onclick '+rdata.channel_onclick[0]+'<br/>'+
'event_site '+rdata.event_site[0]+'<br/>'+
'event_url '+rdata.event_url[0]+'<br/>'+
'start_date '+rdata.start_date[0]+'<br/>'+
'start_time '+rdata.start_time[0]+'<br/>'+
'end_date '+rdata.end_date[0]+'<br/>'+
'end_time '+rdata.end_time[0]+'<br/>'+
'event_notes '+rdata.event_notes[0]+'<br/>';
alert (alert_data);
},
error: function (request, status, error) {
alert ("status "+status+" error "+error+"responseText "+request.responseText);
},
});
When I print out the first element of each array on the javascript side, it shows as "object" doesn't show the value in that array. What is the right way of accessing the array data on the javascript side?

In JavaScript, an associative array is pretty much an object. Your script is working correctly. Do a console.log() with your data and explore how it prints out in the console, then use that to access the data. You could also post up the JSON data in question and probably get more detailed answers.

The answer to this question showed me how to do this. Reading a json encoded array in javascript
The json encoded rdata object returned from the PHP function could be read like this rdata.event_id[i]["0"]. Here is sample code for the objects within rdata.
var event = rdata.event_id[i]["0"]+' '+
rdata.channel_name[i]["0"]+' '+
rdata.channel_onclick[i]["0"]+' '+
rdata.event_site[i]["0"]+' '+
rdata.event_url[i]["0"]+' '+
rdata.event_onclick[i]["0"]+' '+
rdata.start_date[i]["0"]+' '+
rdata.start_time[i]["0"]+' '+
rdata.end_date[i]["0"]+' '+
rdata.end_time[i]["0"]+' '+
rdata.event_notes[i]["0"]+' ';
$('#event_list').append(event);

Use this instead of your 'similar' code:
foreach($nodes as $node)
{
$event_id[] = $node['id'];
$channel_id[] = $node->channel['id'];
$channel_name[] = $node->channel->name;
$channel_onclick[] = $node->channel->onclick;
$event_site[] = $node->event_site->name;
$event_url[] = $node->event_site->url;
$start_date[] = $node->start_date;
$start_time[] = $node->start_time;
$end_date[] = $node->end_date;
$end_time[] = $node->end_time;
$event_notes[] = $node->notes;
}

you need to either echo
echo json_encode($return);
or
echo get_events_data();
better:
echo json_encode($return);
} // end of function
then next line
get_events_data();

Related

Recover php mysql query with ajax/json?

How to recover data from research by json? I would like to recover the separate items as the result show in php page to create new elements, for example recover item.f, item.m to create new elements like item.f < / div> < span > item.m. .. thank you
(error presented at)
Error Can not read property of items " of null
Php page ( does the query )
if ($_GET['action'] == "chatheartbeat") { chatHeartbeat(); }
function chatHeartbeat() {
$sql = "select * from mensagens ";
$query = mysql_query($sql);
$items = '';
$chatBoxes = array();
while ($chat = mysql_fetch_array($query)) {
$items. = << < EOD
{
"s": "0",
"f": "{$chat['de']}",
"m": "{$chat['mensagem']}",
"i": "{$chat['img']}"
},
EOD;
}
}
Index ( calls the pair query present the results - error here - need help here)
$.ajax({
url: "asd.php?action=chatheartbeat",
cache: false,
dataType: "json",
success: function(data) {
$.each(data.items, function(i, item) {
alert(item.f)
});
}
});
As #jeroen says dont manually generate JSON Strings use json_encode() to create a JSONString from a PHP array or an object.
if ($_GET['action'] == "chatheartbeat") {
$sql = "select * from mensagens ";
$query = mysql_query($sql);
$chatBoxes = array();
while ($chat = mysql_fetch_array($query)) {
$t - new stdClass();
$t->s = "0";
$t->f = $chat['de'];
$t->m = $chat['mensagem'];
$t->i = $chat['img'];
$chatBoxes[] = $t;
}
$items = json_encode($chatBoxes);
// now just echo $items to return it to the javascript in the browser
// here or later in the code if there is more to your code than you showed us
echo $items;
}
References:
json_encode()
json_decode()
Thank you all for the help, I managed to solve the problem as follows
Php page ( does the query )
$result = mysql_query("SELECT * FROM mensagens");
while( $array = mysql_fetch_assoc($result)){
$table[]= array("de"=>$array['de'],"mensagem"=>$array['mensagem']); }
echo json_encode($table);
Index
$.ajax({
url: 'asd.php',
dataType: 'json',
success: function(data)
{
for($i=0; $i < data.length; $i++){
$("#chatbox_"+chatboxtitle+" .chatboxcontent").append(
'<div class="message"><span class="from">'+data[$i].de+':
</span><span class=content">'+data[$i].mensagem+'</span></div>');
}}
});

How should I execute my php code using AJAX?

I've written the conditions down in JavaScript and if it's a down arrow then I want to update the database whereas currently it's not falling into the javascript condition and updating the database at server level. Any help will be appreciated.
Code:
<script language="javascript">
$(document).ready(function() {
totalgames=<?= $totalgames ?>;
//scoress = 0;
previous_s=0;
for(xx=totalgames; xx>=1; xx--){
score_ele = 'scores'+xx;
tdid_ele = 'tdid'+xx;
var tdd = document.getElementById(tdid_ele);
var scoress = document.getElementById(score_ele);
if(previous_s == 0){
tdd.innerHTML = "<img src='images/bullet.png'/>";
}else{
if(parseFloat(previous_s) > parseFloat(scoress.value)){
tdd.innerHTML = "<img src='images/arrow_up.png'/>";
}else if(parseFloat(previous_s) < parseFloat(scoress.value)){
tdd.innerHTML = "<img src='images/arrow_down.png'/>";
<?php
//Selecting from table teams
$sql_sel_amnt = "Select * from teams where t_name='".$t_name."'";
$result_sel = $db1->getResult($sql_sel_amnt);
$row_sel = mysql_fetch_assoc($result_sel);
//Selecting from table profitnloss
$sql_pnl = "Select * from profitnloss where t_name='".$t_name."' and username='".$abc."'";
$result_pnl = $db1->getResult($sql_pnl);
$row_pnl = mysql_fetch_assoc($result_pnl);
$transact_money = $row_pnl['pnl_amount'];
$pnl_results = $row_pnl['pnl'];
$profit = 0;
$loss = 0;
$transact_money = explode("|", $transact_money);
$pnl_results = explode("|", $pnl_results);
for($i=0; $i<count($transact_money); $i++){
if($pnl_results[$i]=='P'){
$profit = $profit + $transact_money[$i];
}else{
$loss = $loss + $transact_money[$i];
}//end if
}//end for..
$money_results_total = $profit - $loss;
$pnl_date = date("d-m-Y H:i:s");
$pnl_amount = $row_sel['c_amount'];//total amount lost
$t_amount = $money_results_total + $row_pnl['t_amount'] + $pnl_amount;
$noofplayers = mysql_num_rows($result_sel)-1;//total no of players
$company_share = 17;//charity percentage
$company_share_amnt = $company_share*$pnl_amount/100;
$pnl_amount_remaining = $pnl_amount - $company_share_amnt;
$charity = substr($row_sel['charity'], 0, 2);//charity percentage
$charity_amount = $charity*$pnl_amount_remaining/100;
$sharing_amount = $pnl_amount-$charity_amount-$company_share_amnt;
$pnl_profit = round($sharing_amount/$noofplayers, 2);
echo "noofplayers=> ".$noofplayers.", company_share=> ".$company_share.", company_share_amnt=> ".$company_share_amnt.", charity=> ".$charity."%, charity_amount=> ".$charity_amount.", sharing_amount=> ".$sharing_amount.", pnl_profit=> ".$pnl_profit;
$sql_updt_loss = "UPDATE profitnloss SET game_date = '".$serial_date."', pnl_date = CONCAT(pnl_date, '$pnl_date|'), pnl_amount = CONCAT(pnl_amount, '$pnl_amount|'), pnl = CONCAT(pnl, 'Loss|'), t_amount='".$t_amount."' where username='".$abc."' and t_name='".$t_name."'";
//echo $updt_pnl;
//$result_loss = $db1->getResult($sql_updt_loss);
$sql_updt_profit = "UPDATE profitnloss SET pnl_date = CONCAT(pnl_date, '$pnl_date|'), pnl_amount = CONCAT(pnl_amount, '$pnl_profit|'), pnl = CONCAT(pnl, 'Profit|') where username not like'".$abc."' and t_name='".$t_name."'";
//echo $updt_pnl;
//$result_profit = $db1->getResult($sql_updt_profit);
?>
}else if(parseFloat(previous_s) == parseFloat(scoress.value)){
tdd.innerHTML = "<img src='images/bullet.png'/>";
}//end if
}//end if 0..
previous_s = document.getElementById(score_ele).value;
}//end for
})//emd document ready..
</script>
The way you should execute you PHP-code using ajax is by moving the server side code to a separate file which you call apon in the ajax-request, the url.
One example is using jQuery.
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
This documentation is located here
You send the information needed to execute the PHP-code in the data. These are then accessed by $_POST or $_GET depending on which type you chose.
If you're not intending to use jQuery, you can look here: Getting Started with AJAX - Updating Form via PHP.
Here are some good practices using ajax

Pass an array from PHP (from DB) to JS?

My goal is to get - finally - a 'normal' JS array in my js-file. Maybe json is the way to do it - but the elements in the array should remain in order and its just an array of three arrays: [["1","2","3"]["1","2","3"]["1","2","3"]].
my php-query (it does produce the array above - I mean: it does work):
// this is file 'dbquery.php'
<?php
include_once('../resources/init.php');
$query = mysql_query("SELECT `useranswer`, `solution`, `time` FROM `results`");
$qlen = mysql_query("SELECT COUNT(1) FROM `results`");
$len = mysql_result($qlen, 0);
$user_a = array();
$solu_a = array();
$time_a = array();
while($row = mysql_fetch_assoc($query)){
array_push($user_a, $row['useranswer']);
array_push($solu_a, $row['solution']);
array_push($time_a, $row['time']);
}
$cd_result = array($user_a, $solu_a, $time_a);
$cd_answer = json_encode($cd_result);
echo $cd_answer;
?>
I assume json is not the adequat form here.
Now all I want is an js-array in my js-file like : my_array = [[1,2,3],[1,2,3],[1,2,3]]
But I terribly fail to achieve this.
With $.ajax() I don't know how to get ALL the data at once without 'data: ' each single value. I just want to "catch" my echo from the php - how to do so?
do like this
<?php
include_once('../resources/init.php');
$query = mysql_query("SELECT `useranswer`, `solution`, `time` FROM `results`");
$qlen = mysql_query("SELECT COUNT(1) FROM `results`");
$len = mysql_result($qlen, 0);
$user_a = array();
$solu_a = array();
$time_a = array();
while($row = mysql_fetch_assoc($query)){
array_push($user_a, $row['useranswer']);
array_push($solu_a, $row['solution']);
array_push($time_a, $row['time']);
}
$cd_result = array($user_a, $solu_a, $time_a);
$cd_answer = json_encode($cd_result);
echo json_encode ($cd_answer); // encode in json format
?>
and in ajax:
$.ajax({
type: "GET",
url: "test.php",
dataType: "json",
data : {anything : 1},
success:function(data){
var x = jQuery.parseJSON( data ); // parse the answer
// if you want in an array format then just use eval()
x = eval(x);
alert(x);
}
});
If you just need a PHP variable passed to JS when the page is rendered, then do this in your PHP view layer:
<script type="text/javascript">
var myInt = <?php echo $int ?>;
var myString = '<?php echo $string ?>';
var myArray = <?php echo json_encode($array) ?>;
// All these JS variables can now be used here
</script>
Obviously, you need to ensure that the variables are valid - so in the case of the int, if it is null or undefined, you need to ensure you don't render the assignment - otherwise it will produce a client-side error.

Send array from php to javascript

I'm screen scraping a site with a php script which creates an array in the end that I want to send back to the javascript caller function. In the code below I've tried to print it out with 'print_r', which doesn't give me any results at all (?). If I echo out on of the elements (e.g $addresses[1]) the element is shown.
So, why ain't I getting anything out from the php function, and what is really the best way to send back the array to the calling js function?
Thanks a lot in advance!
js:
$.post(
"./php/foo.php",
{
zipcode: zipcode
},
function(data) {
$('#showData').html(data);
}
);
php:
$tempAddresses = array();
$addresses = array();
$url = 'http://www.foo.com/addresses/result.jspv?pnr=' . $zipcode;
$html = new simple_html_dom();
$html = file_get_html($url);
foreach($html->find('table tr') as $row) {
$cell = $row->find('td', 0);
array_push($tempAddresses, $cell);
}
$tempAddresses = array_unique($tempAddresses);
foreach ($tempAddresses as $address) {
array_push($addresses, $address);
}
print_r($addresses);
You can use JSON to return an array back to the client-side, it can be send by AJAX same what you are doing on your existing code.
Use json_encode() of PHP, this function will make your PHP array into a JSON string and you can use it to send back to your client by using AJAX
In your PHP code(Just for demonstration how it works)
json.php
<?php
$addresses['hello'] = NULL;
$addresses['hello2'] = NULL;
if($_POST['zipcode'] == '123'){ //your POST data is recieved in a common way
//sample array
$addresses['hello'] = 'hi';
$addresses['hello2'] = 'konnichiwa';
}
else{
$addresses['hello'] = 'who are you?';
$addresses['hello2'] = 'dare desu ka';
}
echo json_encode($addresses);
?>
then in your client script(much better you use the Jquery's long AJAX way)
$.ajax({
url:'http://localhost/json.php',
type:'post',
dataType:'json',
data:{
zipcode: '123' //sample data to send to the server
},
//the variable 'data' contains the response that can be manipulated in JS
success:function(data) {
console.log(data); //it would show the JSON array in your console
alert(data.hello); //will alert "hi"
}
});
references
http://api.jquery.com/jQuery.ajax/
http://php.net/manual/en/function.json-encode.php
http://json.org/
js should be
$.ajax({
url:'your url',
type:'post',
dataType:'json',
success:function(data) {
console.log(JSON.stringify(data));
}
});
server
$tempAddresses = array();
$addresses = array();
$url = 'http://www.foo.com/addresses/result.jspv?pnr=' . $zipcode;
$html = new simple_html_dom();
$html = file_get_html($url);
foreach($html->find('table tr') as $row) {
$cell = $row->find('td', 0);
array_push($tempAddresses, $cell);
}
$tempAddresses = array_unique($tempAddresses);
foreach ($tempAddresses as $address) {
$arr_res[] =$address;
}
header('content-type:application/json');
echo json_encode($arr_res);

php to js array convert with jquery's ajax

Im trying to convert 5 PHP arrays to 5 js arrays.
I used to transfer php variables to js variables with json like this:
$return['variable'] = $variable;
echo json_encode($return);
And then fetch it as json object on the js side like this:
success : function(data) {
alert(data.variable);
}
now things are a bit more complicated, i need to transfer these 5 php arrays from a php script to my js script as 5 js arrays:
PHP arrays:
$i = 0;
while ($location = mysql_fetch_array($get_locations)) {
$location_full_name[$i] = $location['loc_full_name'];
$location_main_name[$i] = $location['loc_main_name'];
$location_sub_name[$i] = $location['loc_sub_name'];
$location_anchor_id[$i] = $location['loc_anchor_id'];
$location_type[$i] = $location['loc_type'];
$i++;
}
and fill these corresponding arrays:
var location_full_name = new Array();
var location_main_name = new Array();
var location_sub_name = new Array();
var location_anchor_id = new Array();
var location_type = new Array();
i dont know how to do this. hope i can get some help :)
regards,
alexander
Maybe if you post what returns in "data" so we can help you more (i think). hehe.
I suggest, for your php code, where you set the data into the arrays:
$i = 0;
$rsl = array();
while ($location = mysql_fetch_array($get_locations)) {
$rsl[$i]['full_name'] = $location['loc_full_name'];
$rsl[$i]['main_name'] = $location['loc_main_name'];
$rsl[$i]['sub_name'] = $location['loc_sub_name'];
$rsl[$i]['anchor_id'] = $location['loc_anchor_id'];
$rsl[$i]['type'] = $location['loc_type'];
$i++;
}
echo json_encode($rsl);
So to get this on the javascript
// You could do the same... var location = []...
var location_full_name = new Array();
var location_main_name = new Array();
var location_sub_name = new Array();
var location_anchor_id = new Array();
var location_type = new Array();
...
dataType: "json",
success : function(data) {
$.each(data, function(index, arr){
location_full_name[index] = arr['full_name'];
...
});
}
For each of your arrays, store the value returned from json_encode. And/or make them one array/object and do the same.
You can utilize the PHP array that is actually an ordered map. Below is an example:
PHP:
<?php
$location_full_name = array("Google, Inc.", "Siku-Siku.com");
$location_type = array("Google headquarter", "Virtual address");
$ret = array("full_name" => $location_full_name, "type" => $location_type);
echo json_encode($ret);
?>
JavaScript (jQuery):
<script type="text/javascript">
$(function() {
$.get("test.php", function(data) {
console.log(data.full_name[1]); // Prints "Siku-Siku.com".
}, "json");
});
</script>

Categories