I want to display my JSON array which i got from the PHP server as list in HTML. The code I used loops through the array, but when i replace the array with the variable it does not work.
$(document).ready(function(){
$(document).bind('deviceready', function(){
//Phonegap ready
onDeviceReady();
});
var ownproducts = $('#ownproducts');
$.ajax({
url: 'MYURL',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
var products = '<br>'+item.item;
var ul = $('<ul>').appendTo('body');
var json = { items: ['Banana','Cherry','Apple','Strawberry','Pear','Pineapple'] };
$(json.items).each(function(index, item) {
ul.append($(document.createElement('li')).text(item));
});
ownproducts.append(products);
});
},
error: function(){
ownproducts.text('Error Message');
}
});
});
So i get a JSON file containing data from my database, item.item contains an array but when i replace this:
var json = { items: ['Banana','Cherry','Apple','Strawberry','Pear','Pineapple'] };
for:
var json = { items: item.item };
or:
var json = { items: products };
it does not work (not displaying anything javascript related).
EDIT:
I try to get some items from my database through PHP
<?php
header('Content-type: application/json');
require 'config.php';
$con = mysqli_connect($url,$username,$password,$database);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$userid = $_GET['userID'];
mysqli_select_db($con, $database);
$sql = "SELECT shoppingListID AS id, shoppingListUserID AS userid, shoppingCheckBox AS checkbox, shoppingItem AS item, shoppingDate AS date
FROM shoppinglist
WHERE shoppingListUserID='$userid'
ORDER BY shoppingDate DESC";
$result = mysqli_query($con,$sql) or die ("Query error: " . mysqli_error());
$records = array();
while($row = mysqli_fetch_assoc($result)) {
$records[] = $row;
}
mysqli_close($con);
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
?>
the ShoppingItem field contains an array like ["Tomatos","Apples","Mangos","Bananas"] the SQL returns multiple shoppinglists from a single user, I want to display the shoppinglists on cards with the items of each list in an html list.
Anyone any suggestions? I appreciate the help.
Let me suppose that your JSON endpoint does in fact return the right data -- in this case visiting what you"ve labeled MYURL generates (I believe!) the text:
jsoncallback({"items":["Banana","Cherry","Apple","Strawberry","Pear","Pineapple"]})
Then we can move on to your logic, which consists in this callback function:
function (data, status) {
$.each(data, function (i, item) {
var products = "<br>" + item.item;
var ul = $("<ul>").appendTo("body");
var json = {
items: ["Banana", "Cherry", "Apple", "Strawberry", "Pear", "Pineapple"]
};
$(json.items).each(function (index, item) {
ul.append($(document.createElement("li")).text(item));
});
ownproducts.append(products);
});
}
What is the problem here? There are a lot. The first is that you should probably not be iterating over data, since that is not your array. Instead you should be iterating over data.items.
The second is that you should probably just be creating the HTML rather than creating a ton of DOM stuff. You can use vanilla JS's Array.prototype.map or Array.prototype.join functions rather than delegating this to JQuery: it is a part of the JS spec that this is sufficient:
function (data, status) {
var html = '<ul><li>' + data.items.join('</li><li>') + '</li></ul>';
$(html).appendTo('body');
}
Related
I'm working with Ajax for the first time and I'm trying to translate an ajax request from javascript to jquery and can't figure out how to do it.
Here is my javascript code:
function aaa(track_id) {
var req = new XMLHttpRequest();
req.open("get", "list.php?tr=" + track_id, true);
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
req.onreadystatechange = bbb;
req.send();
}
function bbb(e) {
if(e.target.readyState == 4 && e.target.status == 200) {
antwort = e.target.responseXML;
document.getElementById("title").firstChild.nodeValue = antwort.getElementsByTagName("ti")[0].firstChild.nodeValue;
document.getElementById("artist").firstChild.nodeValue = antwort.getElementsByTagName("art")[0].firstChild.nodeValue;
}
};
And here is the list.php:
<?php
header("Content-Type: text/xml; charset=utf-8");
$con = mysqli_connect("", "root", "", "music");
$res = mysqli_query($con, "SELECT * FROM tracks WHERE track_id = " . $_GET["tr"]);
$dset = mysqli_fetch_assoc($res);
echo "<?xml version='1.0' encoding='utf-8'?>";
echo "<data>";
echo " <tr>" . $dset["track_id"] . "</tr>";
echo " <ti>" . $dset["title"] . "</ti>";
echo " <art>" . $dset["artist"] . "</art>";
echo "</data>";
?>
Can anyone help me? Thanks in advance!
Whilst the other answers will "do the job", there are some refinements you can make.
jQuery has a specific get method which simplifies things, and in addition, you can put the data into an object passed to the get or ajax call instead of appending it to the url as in other answers:
function aaa(track_id) {
$.get( 'list.php',
{ tr: track_id },
function(data) {
var $antwort = $(data.responseXML);
$("#title").text($antwort.find("ti").text());
$("#artist").text($antwort.find("art").text());
}
);
}
Another improvement is to structure it as a Promise:
function aaa(track_id) {
$.get( 'list.php',
{ tr: track_id }
).done( function(data) {
var $antwort = $(data.responseXML);
$("#title").text($antwort.find("ti").text());
$("#artist").text($antwort.find("art").text());
});
}
The advantage of this is that you can chain error handling onto this relatively easily.
Turning to list.php, there are a few problems with it.
It would probably be better returning JSON instead of XML, as that would reduce the complexity of the success code, but obviously you can't do things like that if other applications expect an XML API.
<?php
// protect against MySQL injection by using parameters...
$query = '
SELECT track_id AS tr, title as ti, artist as art
FROM tracks
WHERE track_id=?';
$mysqli = new mysqli("", "root", "", "music");
// this needs more error checking...
$stmt = $mysqli->prepare( $query);
$stmt->bind_param( 's', $_GET['tr']);
$stmt->execute();
$result = $stmt->get_result();
$dset = $result->fetch_assoc();
// simpler to return JSON
header('Content-Type: application/json');
echo json_encode( $dset);
?>
jQuery.ajax() method is used to perform an AJAX (asynchronous HTTP) request.
function aaa(track_id) {
$.ajax({
url: "list.php?tr=" + track_id,
dataType: "json",
success: function (result) {
bbb(result);
}
});
}
function bbb(e) {
antwort = e;
document.getElementById("title").firstChild.nodeValue = antwort.getElementsByTagName("ti")[0].firstChild.nodeValue;
document.getElementById("artist").firstChild.nodeValue = antwort.getElementsByTagName("art")[0].firstChild.nodeValue;
};
The equivalent of making an AJAX in jQuery is $.ajax(). You can also put the XML in the response in to a jQuery object and traverse that to find the values you require. Given the logic you've shown, you could implement it like this:
function aaa(track_id) {
$.ajax({
url: 'list.php',
data: { tr: track_id },
success: function(data) {
var $antwort = $(data.responseXML);
$("#title").text($antwort.find("ti").text());
$("#artist").text($antwort.find("art").text());
}
});
}
This is assuming that the firstChild of the targeted elements is a textNode.
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.
I have a filter for some devices in a webpage, made of checkbox. Whenever one of the checkbox is clicked, i call a function which add to an object the value of the checkboxes checked. I want to send this object to a php file, via ajax, and use it to perform some MySQL query, then return the results from the php and display them on the page. The problem is, i'm missing something, since i kept getting a parseerror in my js.
Here's my code:
device-filter.js
$(document).ready(function(){
$(".ez-checkbox").click(function() {
console.log("ok");
var re = {Brand: "", Cost: "", OS: ""};
$("#Brand :checkbox:checked").each(function(){
re.Brand += $(this).val()+" & ";
});
$("#Cost :checkbox:checked").each(function(){
re.Cost += $(this).val()+" & ";
});
$("#OS :checkbox:checked").each(function(){
re.OS += $(this).val()+" & ";
});
if(re.lenght==0){
}
else{
$.ajax({
method: "POST",
dataType: "json", //type of data
crossDomain: true,
data: re,
url:"./php/filtered-device-query.php",
success: function(response) {
//display the filtered devices
},
error: function(request,error)
{
console.log(request+":"+error);
}
});
}
});
});
filtere-device-query.php
<?php
//connection to db
$mysqli = new mysqli("localhost", "root", "", "my_db");
if (mysqli_connect_errno()) { //verify connection
echo "Error to connect to DBMS: ".mysqli_connect_error(); //notify error
exit(); //do nothing else
}
else {
//echo "Successful connection"; // connection ok
$devices =json_decode($_POST['re']);
echo var_dump($devices)."<br>";
$myArray = array();//create an array
$brand = rtrim($devices["Brand"], " &");
$cost = rtrim($devices["Cost"], " &");
$os = rtrim($devices["OS"], " &");
$query = " SELECT * FROM `devices` WHERE `Brand` = '$brand' AND 'Cost' = '$cost' AND 'OS' = '$os' ";
$result = $mysqli->query($query);
//if there are data available
if($result->num_rows >0)
{
while($row = $result->fetch_array(MYSQL_ASSOC)) {
$myArray[] = $row;
}
echo json_encode($myArray);
}
//free result
$result->close();
//close connection
$mysqli->close();
}
?>
Thanks in advance for any help!
You have some typos, first in the jQuery:
if(re.lenght==0){
should be:
if(re.length==0){// note the correct spelling of length
Then in your PHP you're using quotes on column names in the query. Those should be removed or better yet, back ticked:
$query = " SELECT * FROM `devices` WHERE `Brand` = '$brand' AND `Cost` = '$cost' AND `OS` = '$os' ";
More importantly...
An object, as you've described it, has no length. It will come back as undefined. In order to find the length you have to count the keys:
if(Object.keys(re).length == 0){...
The object re, as you've declared it, already has 3 keys, a length of 3. Checking for length of 0 is a waste of time.
Little Bobby says your script is at risk for SQL Injection Attacks. Learn about prepared statements for MySQLi. Even escaping the string is not safe!
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);
I want to get all posts id from current page after 15 second interval to make server side php query. Php query will find match in Sql with id and if any data find for a particular id's, it will be .append it.
So in my current page have many div with their own dynamic post id like:
<div class="case" data-post-id="111"></div>
<div class="case" data-post-id="222"></div>
<div class="case" data-post-id="333"></div>
<div class="case" data-post-id="anything else dynamic no"></div>
And I want, my javascript will get and sent this ids to a php query for find any match in Sql.
Here my array only got 1st post id. Problem is either my javascript array or php array
My update script: (here var CID cannot get ids, only get first id)
//make array to get id
var CID = []; //get dynamic id
$('div[data-post-id]').each(function (i) {
CID[i] = $(this).data('post-id');
});
function addrep(type, msg) {
CID.forEach(function (id) {
$("#newreply" + id).append("");
});
}
var tutid = '<?php echo $tutid; ?>';
function waitForRep() {
$.ajax({
type: "GET",
url: "/server.php",
cache: false,
data: {
tutid: tutid,
// this way array containing all ID's can be sent:
cid: CID
},
timeout: 15000,
success: function (data) {
addrep("postreply", data);
setTimeout(
waitForRep,
15000);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
setTimeout(
waitForRep,
15000);
}
});
}
server.php
if($_REQUEST['tutid'] && $_REQUEST['cid']){
//make array to cid to get id
foreach($_REQUEST['cid'] as $key => $value){
$res = mysqli_query($dbh,"SELECT * FROM test WHERE id =".$value." AND page_id=".$_REQUEST['tutid']." ORDER BY id DESC LIMIT 1") or die(mysqli_error($dbh));
$rows = mysqli_fetch_assoc($res);
$row[] = array_map('utf8_encode', $rows); //line 80
$data = array();
$data['id'] = $rows['id'];
//etc all
//do something
if (!empty($data)) {
echo json_encode($data);
flush();
exit(0);
}
} }
Change small code and check it
//make array to get id
var CID = []; //get dynamic id
$('div[data-post-id]').each(function (i) {
CID[CID.length] = $(this).data('post-id');
});