Converting jquery string to php - php

So I have a php which gets set of coordinates from the database , I want it to run through a jquery variable.
This is the PHP -
$sql = "SQL that works";
$vari = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($loc))
{echo "[";
echo "''";
echo $row['cor1'];
echo ",";
echo $row['cor2'];
echo "]";
}
This is the jquery that I want it to pass through in this form -
var markers = [
['', 51.503454,-0.119562],
['', 51.499633,-0.124755]
];

Actually you have to change your php code like below:-
$sql = "SQL that works";
$vari = mysqli_query($con,$sql);
$data = array(); //create an rray variable
while($row = mysqli_fetch_assoc($loc)){ // use assoc for lighter $row array
$data[] = array('',$row['cor1'],$row['cor2']); // create sub-array and assign to final array
}
echo json_encode($data); //return final data to ajax
Note:-Now decode this json in your jQuery via parseJSON() and do further code.

If you don't want to use ajax, you can do something like this.
For the PHP,
...
$vari = mysqli_query($con,$sql);
$coOrds = mysqli_fetch_array($loc);
$coOrds = json_encode($coOrds);
?>
For the JS,
var coOrdsJson = <?php echo $coOrds; ?>;
var coOrds = $.parseJSON(coOrdsJson);
var markersArr = [];
for (var i=0; i < coOrds.length; i++ ) {
markersArr[] = "['', " + coOrds[i].cor1 + ", " + coOrds[i].cor2 + "]";
}
var markers = markersArr.join(',');
markers = "[" + markers + "]";

Related

No Ajax response post value [duplicate]

I'm trying to loop through my database and output all rows with a match to the joined table.
I have the following two tables:
quest_items stores all data related to an item:
join_questitems stores association between player ID and the items that player has:
JS: pass in all the necessary info to query the table...
$.getJSON("phpscripts.php", {
"_player" : Player,
"_playerID" : UserID
},
function(returned_data) {
var item_name = returned_data.item_name;
item_image = returned_data.item_image;
$(".questItems").html(item_name + ", " + item_image);
}
);
PHP:
$statsArray = array();
$qry =
'SELECT qi.*
FROM quest_items qi
LEFT JOIN join_questitems jqi ON (qi.item_id = jqi.item_id)
WHERE jqi.user_id = "' . $playerID . '"';
$result = $mysqli->query($qry) or die(mysqli_error($mysqli));
while ($row = $result->fetch_assoc()) {
$myrow = json_encode($row);
array_push($statsArray, $myrow);
}
$k = 0;
while ($k < count($statsArray)) {
echo $statsArray[$k];
$k++;
}
But if I just do one row, I get output, but only for one row. I need both rows:
while ($row = $result->fetch_assoc()) {
echo json_encode($row);
exit;
}
$(".questItems").html(item_name + ", " + item_image) gives: rice, test/path.png
Why can't I loop through the PHP array full of json_encoded rows and output them? Do I have to set item_name and item_image as arrays and loop through the arrays?
EDIT:
$(".questItems").append(item_name + ", " + item_image) doesn't work either
network output from debugger shows rows are being output, but in the first row, my UTF-8 character, fàn, is being garbled in the client output (as you can see). This is curious, as at the top of my phpscripts.php file, I put mysqli_set_charset($mysqli, "utf8");
You shouldn't encode each row separately. Put all the results in an array, and then call json_encode on that array when you're done:
while ($row = $result->fetch_assoc()) {
$statsArray[] = $row;
}
echo json_encode($statsArray);
Then in Javascript you need to loop over the returned array:
$.getJSON("phpscripts.php", {
"_player" : Player,
"_playerID" : UserID
},
function(returned_data) {
$.each(returned_data, function(i, e) {
var item_name = e.item_name;
var item_image = e.item_image;
$(".questItems").append(item_name + ", " + item_image + "<br/>");
});
};
);
rather than this:
while ($row = $result->fetch_assoc()) {
echo json_encode($row);
exit; //<--- this code breaks the while loop;
}
have this:
$quest_items = array();
while ($row = $result->fetch_assoc()) {
$quest_items[] = $row;
}
echo json_encode($quest_items);
exit;
because exit triggers the script to stop(even inside loops) so you will only get the first row.

Echo all json_encoded rows

I'm trying to loop through my database and output all rows with a match to the joined table.
I have the following two tables:
quest_items stores all data related to an item:
join_questitems stores association between player ID and the items that player has:
JS: pass in all the necessary info to query the table...
$.getJSON("phpscripts.php", {
"_player" : Player,
"_playerID" : UserID
},
function(returned_data) {
var item_name = returned_data.item_name;
item_image = returned_data.item_image;
$(".questItems").html(item_name + ", " + item_image);
}
);
PHP:
$statsArray = array();
$qry =
'SELECT qi.*
FROM quest_items qi
LEFT JOIN join_questitems jqi ON (qi.item_id = jqi.item_id)
WHERE jqi.user_id = "' . $playerID . '"';
$result = $mysqli->query($qry) or die(mysqli_error($mysqli));
while ($row = $result->fetch_assoc()) {
$myrow = json_encode($row);
array_push($statsArray, $myrow);
}
$k = 0;
while ($k < count($statsArray)) {
echo $statsArray[$k];
$k++;
}
But if I just do one row, I get output, but only for one row. I need both rows:
while ($row = $result->fetch_assoc()) {
echo json_encode($row);
exit;
}
$(".questItems").html(item_name + ", " + item_image) gives: rice, test/path.png
Why can't I loop through the PHP array full of json_encoded rows and output them? Do I have to set item_name and item_image as arrays and loop through the arrays?
EDIT:
$(".questItems").append(item_name + ", " + item_image) doesn't work either
network output from debugger shows rows are being output, but in the first row, my UTF-8 character, fàn, is being garbled in the client output (as you can see). This is curious, as at the top of my phpscripts.php file, I put mysqli_set_charset($mysqli, "utf8");
You shouldn't encode each row separately. Put all the results in an array, and then call json_encode on that array when you're done:
while ($row = $result->fetch_assoc()) {
$statsArray[] = $row;
}
echo json_encode($statsArray);
Then in Javascript you need to loop over the returned array:
$.getJSON("phpscripts.php", {
"_player" : Player,
"_playerID" : UserID
},
function(returned_data) {
$.each(returned_data, function(i, e) {
var item_name = e.item_name;
var item_image = e.item_image;
$(".questItems").append(item_name + ", " + item_image + "<br/>");
});
};
);
rather than this:
while ($row = $result->fetch_assoc()) {
echo json_encode($row);
exit; //<--- this code breaks the while loop;
}
have this:
$quest_items = array();
while ($row = $result->fetch_assoc()) {
$quest_items[] = $row;
}
echo json_encode($quest_items);
exit;
because exit triggers the script to stop(even inside loops) so you will only get the first row.

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

Google Maps API 3 - extracting markers from MySQL DB using PHP

<?
$query = mysql_query("SELECT * FROM poi_example");
while ($row = mysql_fetch_array($query)){
$name=$row['name'];
$lat=$row['lat'];
$lon=$row['lon'];
$desc=$row['desc'];
echo ("addMarker($lat, $lon,'<b>$name</b><br/>$desc');\n");
}
?>
this code (echo) shows the table data in HTML source code.. is there another way (which does not shows the data) to extract markers from table?
thank you.
tutorial & demo page
I prefer to render them as a JSON. You can either do that in-page as you have done above.
<?php
// do database connection here
// run query to fetch your results
$rows = array();
while ($row = mysql_fetch_array($query)) {
$rows[] = $row;
}
echo "<script>var items = '".json_encode($rows)."';</script>";
You can iterate over your items array in JavaScript.
for (var i = 0; i < items.length; i++) {
(function(item) {
addMarker(item.lat, item.lon, '<b>' + item.name + '</b><br />' + item.desc);
})(items[i]);
}
I presume your addMarker() function creates a standard Google Map marker.
Alternative, you can have a PHP script that fetches your items from the database as echoes them as a JSON string, and then just call that via AJAX with jQuery.
So your PHP script would simply be:
<?php
header('Content-Type: application/json');
// connect to database
// do query
$rows = array();
while ($row = mysql_fetch_array($res)) {
$rows[] = $row;
}
echo json_encode($rows);
exit;
And then in your JavaScript file:
$.getJSON('script.php', function(items) {
for (var i = 0; i < items.length; i++) {
(function(item) {
addMarker(item.lat, item.lon, '<b>' + item.name + '</b><br />' + item.desc);
})(items[i]);
}
});
Hope this helps.

json_encode in php

i have this script and it works, but not as i expected. I need to assign an array of values with differents names, now all $arr[] are named "valor"
{"valor":"20"},{"valor":"50"}
i need
{"valor1":"20"},{"valor2":"50"}
the script
$query = mysql_query("SELECT valor FROM grafico") or die(mysql_error());
$arr = array();
while($row = mysql_fetch_assoc($query)) {
$arr[] = $row;
}
echo json_encode($arr);
in ajax
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("button").click(function(){
jQuery.ajax({
url: "chart.php",
dataType: "json",
success: function(json){
var msg = "Nome: " + json.valor1+ "\n";
msg += "Sobrenome: " + json.valor2 + "\n";
alert(msg);
}
});
});
});
</script>
the problem is: I need to create a loop that create uniques names, as value1, value2, value3
like
$arr['valor1'] = "Evandro";
i tried a loop- for, but i get an error of memory
thanks
Try this:
$query = mysql_query("SELECT valor FROM grafico") or die(mysql_error());
$arr = array();
$i = 1;
while($row = mysql_fetch_assoc($query)) {
$arr[] = array("valor{$i}" => $row["valor"]);
++$i;
}
echo json_encode($arr);
Should work. Alternatively if you want to make it so it works with current callback change the $arr[] = line to the following:
$arr["valor{$i}"] = $row["valor"];
$index = 1;
while($row = mysql_fetch_assoc($query)) {
$key = 'valor'.index;
$arr[$key] = $row;
$index++;
}
Does that give you a memory error? It shouldn't.

Categories