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.
Related
I know that using php inside js is a bad practice, but unfortunately for now my skill is not enough to come up with something else.
$(document).ready(function() {
$("#type").change(function() {
var val = $(this).val();
valSize = "<?php $sql = "SELECT model FROM cars WHERE brand = 'val'";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result)){
echo '<option>'.$row['model'].'</option>';
}
?>";
$("#size").html(valSize);
});
});
Is there any way how I could add val variable inside php code?
Your best bet would be to use a JavaScript AJAX call to send a request to another php file on your server.
First, create a separate PHP file on your server, I'll label it query.php (ONLY for the purposes of this explanation, I'd recommend choosing something more meaningful to your application).
<?php
if ($_POST['brand']) {
// Be sure to set up your SQL $conn variable here
$conn = ...;
$sql = "SELECT model FROM cars WHERE brand = '" . $_POST['brand'] . "'";
$result = mysqli_query($conn, $sql);
$data = []; // Save the data into an arbitrary array.
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
echo json_encode($data); // This will encode the data into a variable that JavaScript can decode.
}
Then in your JavaScript, perform the AJAX request:
$(document).ready(function() {
$("#type").change(function() {
var val = $(this).val();
$.post('query.php', {'brand' : val}, function(data){
var jsonData = JSON.parse(data); // turn the data string into JSON
var newHtml = ""; // Initialize the var outside of the .each function
$.each(jsonData, function(item) {
newHtml += "<option>" + item['model'] + "</option>";
})
$("#size").html(newHtml);
});
});
});
You can't execute the php code once the page has loaded. You're going to have to make a ajax call to a php file, that queries the data you need and echos that back to the original file. I would also recommend encoding it using echo json_encode($queryResults); Then you can JSON.parse($data);the return data in the success function of the ajax call.
I have this section of code that is suppose to get the Values of the input fields and then add them to the database. The collection of the values works correctly and the insert into the database works correctly, I am having issue with the data posting. I have narrowed it down to the data: and $__POST area and im not sure what I have done wrong.
JS Script
$("#save_groups").click( function() {
var ids = [];
$.each($('input'), function() {
var id = $(this).attr('value');
//Put ID in array.
ids.push(id);
console.log('IDs'+ids);
});
$.ajax({
type: "POST",
url: "inc/insert.php",
data: {grouparray: ids },
success: function() {
$("#saved").fadeOut('slow');
console.log('Success on ' + ids);
}
});
});
PHP Section
<?php
include ('connect.php');
$grouparray = $_POST['grouparray'];
$user_ID = '9';
$sql = "INSERT INTO wp_fb_manager (user_id, group_id) VALUES ($user_ID, $grouparray)";
$result=mysql_query($sql);
if ($result === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysql_error();
}
?>
You cannot send an array trough an ajax call.
First, use something like:
var idString = JSON.stringify(ids);
And use it: data: {grouparray: idString },
On the PHP side:
$array = json_decode($_POST['grouparray']);
print_r($array);
Say I have 10 items in my db that I am trying to shuffle, how could I alter my current code so that every time it pulls a name out of the db that it shows up one at a time, rather than all at once?
$con = mysqli_connect("XXX", "XXX", "XXX", "XXX");
$query = mysqli_query($con, "SELECT * FROM users WHERE `group` = 3");
echo 'Normal results: <br>';
$array = array();
while ($row = mysqli_fetch_assoc($query)) {
$array[] = $row;
echo $row['firstname'] . ' ' . $row['lastname'] . '<br>';
}
?>
<form method="post">
<input type="submit" value="Shuffle" name="shuffle">
</form>
<?php
if (isset($_POST['shuffle'])) {
shuffle($array);
echo 'Shuffled results: <br>';
foreach ($array as $result) {
$shuffle_firstname = $result['firstname'];
$shuffle_lastname = $result['lastname'];
?>
<div id="shuffle_results">
<?php echo $shuffle_firstname . ' ' . $shuffle_lastname . '<br>';?>
</div>
<?php }
}
//What I added in and this is the spot I added it as well
$get_shuffle = array($array);
$shuffle_one = array_pop($get_shuffle);
print_r($get_shuffle);
?>
I want them all to stay put once they have shown.. I just want all of them to come out one at a time. Say, there is 10 pieces of paper in a bag and you are drawing one at a time and then put the pieces of paper on a table to show what was drawn, that is what I want.
As a follow up to my comment suggesting you use JavaScript instead of PHP for the animation, here is a basic way to do it. (This code assumes you have jQuery on the page).
Note: I haven't tested this code and there is likely a bug or two, but I hope you get the general idea.
Your HTML
<div id="shuffle_results"></div>
<form onsubmit="getData()">
<input type="submit" value="Shuffle" name="shuffle">
</form>
Your PHP
$con = mysqli_connect("localhost", "root", "", "db");
$query = mysqli_query($con, "SELECT * FROM users WHERE `group` = 3");
$array = array();
while ($row = mysqli_fetch_assoc($query)) {
array_push($array, $row);
}
header('Content-Type: application/json');
echo json_encode($array);
Your JavaScript
function getData() {
$.ajax({
url: 'url to PHP script',
dataType: 'json',
success: function(data) {
for(var i = 0, l = data.length; i < l; ++i) {
window.setTimeout(addResult, 2000, data[i].firstname, data[i].lastname);
}
},
error: function(jqXHR, textStatus, error) {
alert('Connection to script failed.\n\n' + textStatus + '\n\n' + error);
}
});
}
function addResult(firstname, lastname) {
$('#shuffle_results').append("<p>" + firstname + " " + lastname + "</p>");
}
The basic idea here is that you shouldn't use PHP to do DOM manipulation. PHP can load data into your webpage (and that data can be DOM elements, JSON data as I have shown, or other types of data), but once there JavaScript should be used to interact with it. Recall, PHP runs on your server, while JavaScript (traditionally) runs in the client's web browser.
I am looking to display data by running some query via php script and then using ajax to show it on an html page.
I have a php script that echos the data from a sql query in json format. The output looks like this:
{"Username":"Server","RICS":12739,"Exclusive_RICS":0}{"Username":"eikon1","RICS":4,"Exclusive_RICS":0}{"Username":"balbla","RICS":552,"Exclusive_RICS":0}{"Username":"somename","RICS":221,"Exclusive_RICS":201}
I would like to display this data using an $.ajax call.
I did some research and came up with this:
$(document).ready(function(){
$.ajax({
url : 'query.php',
type : 'POST',
data : {
//'numberOfWords' : 10
},
dataType:'json',
success : function(data) {
window.alert(data.Username)
},
error : function(request,error)
{
alert("Request: "+JSON.stringify(request));
}
});
});
However, it's not working properly. I just get this alert:
I am new to js/ajax/php so excuse me if I missed something simple.
Any help is appreciated. Thanks!
EDIT:
php code:
$sql = 'select * from table';
$retval = sqlsrv_query($conn,$sql);
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while( $row = sqlsrv_fetch_array( $retval, SQLSRV_FETCH_ASSOC) ) {
echo json_encode($row);
}
sqlsrv_free_stmt($retval);
//echo "Fetched data successfully\n";
sqlsrv_close($conn);
EDIT 2:
Managed to get the output of php in correct JSON format through this. Now just need to display this using ajax.
while( $row = sqlsrv_fetch_array( $retval, SQLSRV_FETCH_ASSOC) ) {
$rows[] = $row;
}
echo json_encode($rows);
Looping through your SQL result set and echoing each row separately produces an invalid JSON format. Instead you should json_decode the entire SQL result set.
Here's how you can update your PHP code so that it outputs the correct format:
php code:
$sql = 'select * from table';
$retval = sqlsrv_query($conn,$sql);
if(! $retval ) {
die('Could not get data: ' . mysql_error());
}
echo json_encode( sqlsrv_fetch_array( $retval, SQLSRV_FETCH_ASSOC) );
sqlsrv_free_stmt($retval);
//echo "Fetched data successfully\n";
sqlsrv_close($conn);
There may be one more step necessary in your AJAX success callback. You'll have to JSON.stringify the result because PHP will send it back as plain text:
success : function(data) {
var result = JSON.stringify( data );
window.alert(result.Username)
},
Thanks for the help everyone. I was eventually able to figure out the issue.
First of all, as pointed by users, my json format was not right. I
fixed that with the solution in my edit.
Secondly, I had to reference my php directly with the exact address. I think it has to do with running queries from same server. Not sure perfectly.
Thirdly, i tried a plain ajax call and even that was failing. It turns out my browser (chrome) needed a clean up. I cleared my cookies and it started to work fine. Why it was acting weird? I have no idea!
Finally, now I needed to display the data in a table format and
update the table frequently. I am still working with that but this is
what I got going for me right now:
$(document).ready(function() {
(function poll() {
$.ajax({
url : 'http://localhost/scripts/query.php',
type : 'POST',
data : {},
dataType:'json',
success : function(response) {
var json_obj = $.parseJSON(JSON.stringify(response));
var output="";
for (var i in json_obj)
{
output+="<tr>";
output+="<td>" + json_obj[i].time.date + "</td>" + "<td>" + json_obj[i].username + "</td>" + "<td>" + json_obj[i].rics + "</td>" + "<td>" + json_obj[i].exclusive_rics +"</td>";
output+="</tr>";
}
$('#table_content').html(output);
},
error : function(request,error)
{
alert("Request: "+JSON.stringify(request));
} ,
dataType: "json",
complete: setTimeout(function() {poll()}, 5000),
timeout: 2000
})
})();
});
I really don't understand why this was so hard to do. I am sure this is a common scenario and I really wish there was a more straightforward way of doing this. Hopefully, my final code will avoid others from wasting so much of their time. Good luck!
So I have a database pass a whole bunch of data using PHP back to jQuery through JSON.. I'm trying to access individual columns from the returned data but no luck..
My PHP:
header('Content-Type: application/json');
require 'database.php';
mysql_query('SET CHARACTER SET utf8');
$myjsons = array();
$qry = 'SELECT * FROM quotes ORDER BY id';
$result = mysql_query($qry);
while($row = mysql_fetch_assoc($result)){
$myjsons[] = json_encode(array($row));
}
echo $_GET['callback'] . '(' . json_encode($myjsons) . ')';
Here's my JS:
function getAll(){
jQuery.ajax({
url:'example.com/js/getAll.php',
async: true,
dataType: 'jsonp',
success:function(data){
$('.quoteList').append(data[0]);
}
});
}
Currently that appends the following to the element:
[{"id":"1","text":"The most wasted of all days is one without laughter.","author":"E.E. Cummings","status":"1"}]
So for example.. if I wanted the jQuery to go through data[0] to data[92] (the last one) and append the author of each to .quoteList, how could I do that? I've tried data[0][1] and data[0][author]
You can use $.each() to loop through the data and append the author:
$.each(data, function(i) {
$('.quoteList').append(data[i]['author']);
});
The PHP might be defective because json_encode is called twice, and this is unusual. As written this would be flattening the rows into JSON strings, but mere strings nonetheless, which then get JSON encoded again into an array of strings. This is probably not what you intended, as it would be making it possible to print the received data but not access the components of rows which will be decoded to strings and not objects.
Compare https://stackoverflow.com/a/6809069/103081 -- here the PHP echoes back a callback with a single JSON object inside parenthesis ().
I suspect the fix looks like https://stackoverflow.com/a/15511447/103081
and can be adapted as follows:
header('Content-Type: application/json');
require 'database.php';
mysql_query('SET CHARACTER SET utf8');
$myjsons = array();
$qry = 'SELECT * FROM quotes ORDER BY id';
$result = mysql_query($qry);
while($row = mysql_fetch_assoc($result)){
$myjsons[] = $row;
}
echo $_GET['callback'] . '(' . json_encode($myjsons) . ')';
Once you have this, you should be getting back proper JSON for your array of objects and be able to use #Felix's code on the client side.
you need to use loop on your data, try this
success:function(data){
for (var i in data) {
$('.quoteList').append(data[i]);
}
}
This should work:
(upd. all code:)
function getAll(){
jQuery.ajax({
url:'example.com/js/getAll.php',
async: true,
dataType: 'jsonp',
contentType: "application/json",
success:function(data){
var str = "";
$(data).each(function(index, item){
str += item.author + " ";
});
$('.quoteList').append(str);
}
});
}
Your problem is here:
while($row = mysql_fetch_assoc($result)){
$myjsons[] = json_encode(array($row));
}
echo $_GET['callback'] . '(' . json_encode($myjsons) . ')';
you need something like this:
while($row = mysql_fetch_assoc($result)){
$myjsons[] = $row;
}
$myjsons['callback'] = $_GET['callback'];
echo json_encode($myjsons);