passing coordinates from mysql to js via php - javascript

So, i've a working js script that calls a php script that executes a mysql query.
The bad part is when i try to pass the coordinates back to the js script because they are unformatted.
Example:
the array i would like to have is {xx.xxxxxxx, yy.yyyyyyy...}
instead i get {xx.xxxxxxxyy.yyyyyyy and so on}.
here is the php query code UPDATED:
<?php
include('config.php'); //richiama lo script per la connessione al database
$org_name=$_POST['valor']; //riceve il nome dell'organizzazione terroristica desiderata
$return = array();
$query=mysql_query("SELECT longitude, latitude FROM gtdb WHERE `gname` LIKE '$org_name%' and longitude!=''"); //esegue una query al database
while($row=mysql_fetch_assoc($query)&&$row2=mysql_fetch_assoc($query)){
$return[] = array($row['longitude'], $row2['latitude']);
}
header('Content-type: application/json');
echo json_encode($return);
?>
here is the javascript code that triggers the query, when it gets back the datas from the query calls the dataadder function (see the next section of js code):
var Datas = [new google.maps.LatLng(32.7603282, 46.343451)];
$(document).ready(function() {
$('#gnome').change(function() {
var inpval=$(this).val();
$.ajax({
url: 'php/query.php',
type: 'post',
data: {valor : inpval},
success: function(data) {
while(Datas.length > 0) {
Datas.pop();
}
alert(data);
Datas = dataadder(data);
initialize(); //reinitialize gmap with the new datas
alert(Datas);
}
});
});
});
dataadder code
function dataadder(array){
var arr2 = [];
var i=0;
var j=1;
while(j<=array.length){
arr2.push("new google.maps.LatLng("+array[i]+")");
i+=2;
j+=2;
}
alert(arr2);
return(arr2);
}
Any help?

You should probably try with json_encode, something like this :
$query=mysql_query("SELECT longitude, latitude FROM gtdb WHERE `gname` LIKE '$org_name%' and longitude!=''"); //esegue una query al database
$return = array();
while($row=mysql_fetch_assoc($query)){
$return[] = array($row['longitude'], $row['latitude']);
//or $return[] = ''. $row['longitude'] . '.' . $row['latitude'];
//if you want one 'xxx.yyy' string per row of the output
}
echo json_encode($return);
this will output something like [['xxx','yyyy'], ['xxx','yyyy']]. you then need to call that php with $.getJSON(...) instead of $.ajax(). also you'll have to adapt dataadder accordingly.
and as said in comments, add application/json as your content-type

Related

Convert a Ajax Json String to a JS Object for my Ajax Get Script

I ideally want the Ajax result to be converted from Jsonstring to OBJ Thank You in advance.
I know the AJAX GET script is working becuase when I alert the Ajax Post result I see the Contents in json string format as below.
alert(JSON.stringify(data));
[{"id":"1","username":"jiten","name":"Jitensingh\t","email":"jiten93mail”},{“id":"2","username":"kuldeep","name":"Kuldeep","email":"kuldeemail”}]
I want the AJAX GET result data converted to look like this in OBJ format like below.
{id:31,name:"Mary",username:"R8344",email:"wemail}];
PHP/SQL CODE with the Json encoded Array
<?php
include "../mytest/config.php";
$return_arr = array();
$sql = "SELECT * FROM users ORDER BY NAME";
$result = $conn->query($sql);
//Check database connection first
if ($conn->query($sql) === FALSE) {
echo 'database connection failed';
die();
} else {
while($row = $result->fetch_array()) {
$id = $row['id'];
$username = $row['username'];
$name = $row['name'];
$email = $row['email'];
$return_arr[] = array(
"id" => $id,
"username" => $username,
"name" => $name,
"email" => $email);
}
// Encoding array in JSON format
echo json_encode($return_arr);
}
?>
php echo _encode array above returns below Json string format
[{"id":"1","username":"jiten","name":"Jitensingh\t","email":"jiten93mail”},{“id":"2","username":"kuldeep","name":"Kuldeep","email":"kuldeemail”}]
I am looking for something like below.( top half of the script)
<script>
$(document).ready(function(){
$.ajax({
url: 'ajaxfile.php',
type: 'get',
dataType: 'JSON',
success: function(result){
var data =(JSONstring convert to OBJ(result);
//-----The top half of script -------------
$.each(data, function( i, person ) {
if(i == 0) {
$('.card').find('.person_id').text(person.id);
$('.card').find('.person_name').text(person.name);
$('.card').find('.person_username').text(person.username);
$('.card').find('.person_email').text(person.email);
} else {
var personDetailCloned = $('.card').first().clone();
personDetailCloned.find('.person_id').text(person.id);
personDetailCloned.find('.person_name').text(person.name);
personDetailCloned.find('.person_username').text(person.username);
personDetailCloned.find('.person_email').text(person.email);
$('.card-container').append(personDetailCloned);
}
});
});
</script>
I will need help with the closing tags as above is just an example
The solution is:
success: function(result){
data =(result);
There was no need o convert the data to OBJ or anything ( blush). Then the code on the 2nd half of the Ajax script will receive the data and populate. Thanks to all contributors.

PHP MySQL JS AJAX - Loop issue

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.

Accessing PHP JSON response using Javascript

Is this valid approach: I want to keep api key from being accessible via source code so I have been trying to keep it hidden with PHP and use Javascript to display data. (I prefer to use js syntax to display data) I've been able to display data successfully but when I look at the source code I can see the JSON response. Can anyone tell me if this is a valid approach and why not good idea to have json shown in source?
<?php
$apikey = "xxxx";
$data = file_get_contents('http://url?apikey=' . $apikey);
$json = json_decode($data,true);
?>
I then access the response like so:
<script type="text/javascript">
var data = <?php echo json_encode($json) ?>;
$('.in-theaters-soon').append('<p>' + data.movies[0].title + '</p>');
</script>
You can directly echo the values from PHP since you already have the response in $json. For example:
<div class="in-theaters-soon">
<p><?php echo $json['movies'][0]['title']; ?></p>
</div>
Always make some validation of the printed data.
<?php
$apikey = "xxxx";
$data = file_get_contents('http://url?apikey=' . $apikey);
if (is_array($data) && ! empty($data)) {
/**
* Do something.
/**/
}
You could do something like this if you have the php in a separate file.
Your php file.
<?php
// create a token check to make sure it is being called.
$apikey = "xxxx";
$data = file_get_contents('http://url?apikey=' . $apikey);
echo json_encode($data);
?>
Then query your php file something like this sending a token or something similar.
$.ajax({
url: url,
type: 'POST',
data: {token:token},
success: function(data){
var response = $.parseJSON(data);
for(var x = 0; x < response.length; x++){
$('.in-theaters-soon').append('<p>' + response[x].title + '</p>');
}
},
cache: false,
contentType: false,
processData: false
});
Hope this helps.

Array json between ajax and php

I'm developing a simple guestbook and I want to update the table with all messages without refreshing the page because if someone it's writing a comment and the page refreshes the comment will be lost.
So I began writing some code with ajax to update the table but I don't know how to send an array (with comment, username, date ecc) from php to ajax.
In the database I have a column named "wrote" and it can be 0 (unread) or 1 (read). 1 it's when the messages it's already on the table.
This is what I've done since now, maybe it's wrong
getGuest.php
<?php
include("Database.php");
$Database = new Database( "localhost", "root", "1234");
$Database->connectToServer();
$Database->connectToDatabase("test");
$result = $Database->unreadMessages();
$rows=mysql_fetch_array($result);
echo json_encode($rows);
?>
Script.js
window.onload = function(){
interval = window.setInterval('updateGuest()',5000);
}
function updateGuest() {
$.ajax({
url: 'getGuest.php',
method: 'get',
success: on_getGuest_success,
error: on_error
});
}
function on_getGuest_success(data) {
for(var i=0; i<data.length;i++) {
// HERE I WANT TO ADD A ROW WITH ALL MESSAGE UNREAD BUT I DONT KNOW WHAT I HAVE TO DO
}
}
function on_error() {
//do something
}
Make sure the JSON contains an array
Add headers
use getJSON
Like this:
PHP
$data = array();
while ($row = mysql_fetch_assoc($result)) {
$data[] = $row;
}
header("content-type: application/json");
echo json_encode($data);
JS:
$(function() { // when page has loaded
var tId = setInterval(function() { // save the tId to allow to clearTimeout if needed
$.getJSON("getGuest.php",function(data) { // call the server using jQuery's JSON access
$('.guestbook').empty(); // empty the container
var rows = []; // create an array to hold the rows
$.each(data,function(_,item) { // loop over the returned data adding rows to array
rows.push('<tr><td class="name" width="10%">' + item.name + '</td></tr>');
});
$('.guestbook').html(rows.join()); // insert the array as a string
});
},5000); // every 5 secs
});
I would personally only return what was new since last time

How to Pass Two Values From PHP to Ajax

Can you please let me know how I can pass Two Values from PHP file into a jQuery Ajax script. What I have is a Ajax call as:
<script>
$(function() {
var req = $.ajax({
url: 'captcha.php',
});
req.done(function(data){
alert(data);
})
});
</script>
and my PHP (captcha.php) is like:
<?php
$number1 = rand(1,9);
$number2 = rand(1,9);
$sum = $number1 + $number2;
echo $number1;
?>
as you can see currently I am able to pass the value of the $number1 but I need to have both values($number1 and $number2). Can you please let me know how to achieve this?
Thanks
Instead of sending (invalid) HTML to the client, use a structured data format, such as JSON.
<?php
header("Content-Type: application/json");
$data = Array($number1, $number2);
print json_encode($data);
exit;
In the JavaScript, jQuery will now populate data with an array.
Why don't you make an array containing variables to return and json_encode it to parse it in JS?
echo json_encode(array($number1, $number2));
Make an array out of your values:
$array = array($number1, $number2);
Then parse it to json
$json = json_encode($array);
Then echo out the $json and you have multiple variables in your js!
<script>
$(function() {
var req = $.ajax({
url: 'captcha.php',
});
req.done(function(data){
data = data.split(",");
//Number 1
alert(data[0]);
//Number 2
alert(data[1]);
})
});
</script>
<?php
$number1 = rand(1,9);
$number2 = rand(1,9);
$sum = $number1 + $number2;
echo $number1 .",". $number2;
?>
All this does is tells the php script to echo Number1,Number2 and then the javascript splits this string into an array from the ,
First Way
You can concatenate the two values seperating them by a special character like '_' like this
PHP
echo $number1 . '_' . $number2;
And then do like this in javascript
data = data.split('_'); // get an array with the two values
Second way
You can encode as JSON in php and do a json ajax request
PHP
$result = array($number1, $number2);
echo json_encode($result);
Javascript
$.getJSON('captcha.php',function(data){
console.log(data); //
});

Categories

Resources