I got the following problem. I want to display a multi array via ajax.
Javascript:
function getContent(HSID,HSname){
$.ajax({
url: 'ajax/script.gethandlungslogContent.php',
type: "POST",
data: { HSID : HSID },
dataType : "json",
success: function(data) {
document.getElementById('wartungslogHead').innerHTML = HSname;
document.getElementById('wartungslogContent').innerHTML = data.hl_aenderung;
document.getElementById('wartungslogID').value = data.HSID;
//document.getElementById('wartungslogID').value = data.KentID;
document.getElementById('buttonEdit').style.display = 'inline';
document.getElementById('buttonDelete').style.display = 'inline';
}
});
}
PHP Script:
<?php
include_once('../classes/class.mysql.php');
if (isset($_POST['HSID'])){$HSID = $_POST['HSID'];};
$HSID = 2;
$mydb3 = new DB_MySQL('localhost','','','');
$query3 = "SELECT * FROM hosting_handlungslog WHERE HSID = '$HSID'";
$mydb3->query($query3);
while ($row3 = $mydb3->fetchRow()){
echo json_encode($row3);
}
?>
The return of the php script looks like this:
{"HLID":"1","HSID":"2","hl_datum":"2014-01-19","hl_info":"n","hl_aenderung":"Windows-UpdatesJava Update"}
{"HLID":"2","HSID":"2","hl_datum":"2014-02-02","hl_info":"n","hl_aenderung":"Windows-UpdatesTomcat-UpdateApache-Update"}
{"HLID":"3","HSID":"2","hl_datum":"2014-03-03","hl_info":"n","hl_aenderung":"Windows-UpdatesTomcat-UpdateApache-Update"}
{"HLID":"4","HSID":"2","hl_datum":"2014-04-13","hl_info":"y","hl_aenderung":"Windows-UpdatesTomcat-Update auf 6.0.39Apache Update 2.4.8 (OpenSSL auf 1.0.1g)"}
{"HLID":"5","HSID":"2","hl_datum":"2014-04-14","hl_info":"n","hl_aenderung":"Zertifikatsaustausch wegen Heartbleed Bug"}
{"HLID":"6","HSID":"2","hl_datum":"2014-04-27","hl_info":"y","hl_aenderung":"Java Update auf 7.0.58"}
{"HLID":"7","HSID":"2","hl_datum":"2014-06-08","hl_info":"y","hl_aenderung":"Windows-UpdatesTomcat-Update auf 6.0.41Apache Update auf 2.4.9 (OpenSSL auf 1.0.1h)Java Update auf 7.0.60"}
{"HLID":"8","HSID":"2","hl_datum":"2014-07-21","hl_info":"y","hl_aenderung":"Apache Update auf 2.4.10Java Update auf 7.0.62"}
What to do here? Thanks in advance!
You must save it to another Array and show after gets all data from mysql.
<?php
include_once('../classes/class.mysql.php');
if (isset($_POST['HSID'])){$HSID = $_POST['HSID'];};
$HSID = 2;
$myjsonarray = null;
$mydb3 = new DB_MySQL('localhost','','','');
$query3 = "SELECT * FROM hosting_handlungslog WHERE HSID = '$HSID'";
$mydb3->query($query3);
while ($row3 = $mydb3->fetchRow()){
$myjsonarray[] = $row3;
}
echo json_encode($myjsonarray);
?>
And now you get this
[{"HLID":"1","HSID":"2","hl_datum":"2014-01-19","hl_info":"n","hl_aenderung":"Windows-UpdatesJava Update"},{"HLID":"2","HSID":"2","hl_datum":"2014-02-02","hl_info":"n","hl_aenderung":"Windows-UpdatesTomcat-UpdateApache-Update"},{"HLID":"3","HSID":"2","hl_datum":"2014-03-03","hl_info":"n","hl_aenderung":"Windows-UpdatesTomcat-UpdateApache-Update"},...]
Example show in php...
<?php
echo $myjsonarray[0]["HLID"];
echo $myjsonarray[1]["HLID"];
?>
In jquery you may use "for"
for(i=0;i<data.lenght;i++){
mydata = data[i];
alert(mydata["HSname"]);
}
Change your PHP to :
$tempArray = array();
while ($row3 = $mydb3->fetchRow()){
tempArray[] = $row3;
}
echo json_encode($tempArray);
Then in javascript:
success: function(data) {
$.each(data, function(index, item){
// Now loop through e.g.
$('body').append('<div class="wartungsLogID">' + item.HSID + '</div>');
});
}
In your javascript, in the success callback, you need to parse the json (var data).
If you have a table element, you can fill it with your data.
First you need a table and cycle:
var t = document.getElementById(mytableId);
for (var i = 1; i < data.length; i++)
...
inside the loop you need to create a row for every object inside your json:
var tr = document.createElement('tr');
var td = document.createElement('td');
td.innerHTML = data[i].hl_aenderung;
tr.appendChild(td);
t.appendChild(tr);
and repeat this for every field (every object's propery (hl_datum,hl_info,etc.)).
Within the Ajax Success callback you must loop through the array to display each object individually.
Below is an example, including some best practice techniques:
success: function(data) {
var textToDisplay = '';
$.each(data, function(i, item){
textToDisplay += '<li data-id="'+item.HLID+'">'+item.hl_aenderung+'</li>'
});
$('ul').append(textToDisplay);
}
Here's a working fiddle which you can expand on.
Related
I tried to call / search data by ID , from the server using ajax in cordova , but when I click to display the data " undefined" , what's wrong ???
This my html
<input type="text" id="result" value=""/>
<button>get</button>
<div id="result2"></div>
function get (){
var qrcode = document.getElementById ("result").value;
var dataString="qrcode="+qrcode;
$.ajax({
type: "GET",
url: "http://localhost/book/find.php",
crossDomain: true,
cache: false,
data: dataString,
success: function(result){
var result=$.parseJSON(result);
$.each(result, function(i, element){
var id_code=element.id_code;
var qrcode=element.qrcode;
var judul=element.judul;
var hasil2 =
"QR Code: " + qrcode + "<br>" +
"Judul: " + Judul;
document.getElementById("result2").innerHTML = hasil2;
});
}
});
}
This my script on server
include "db.php";
$qrcode= $_GET['qrcode'];
$array = array();
$result=mysql_query("select * from book WHERE qrcode LIKE '%{$qrcode}%'");
while ($row = mysql_fetch_array($result)) { //fetch the result from query into an array
{
$array[] =$row['qrcode'];
$array[] =$row['judul'];
$array[] =$row['jilid'];
}
echo json_encode($array);
}
try to change your parameter in calling ajax
var dataString = {qrcode : qrcode };
Change your php code as below
include "db.php";
$qrcode= $_GET['qrcode'];
$array = array();
$result=mysql_query("select * from book WHERE qrcode LIKE '%{$qrcode}%'");
while ($row = mysql_fetch_array($result)) { //fetch the result from query into an array
{
$array[] =['qrcode'=>$row['qrcode'],'judul'=>$row['judul'],'id_code'=>$row['jilid']];
}
echo json_encode($array);
}
RESOLVED the problem is. I try to replace with this script and the result was the same as I expected.
while ($row = mysql_fetch_object($result)){
$array[]=$row++;
}
echo json_encode($array);
I am trying to run a SELECT query in PHP and then multiple rows are selected, but I need to fetch them into an array and then use: echo json_encode($array). After That I need to get this array into AJAX.
Here is the PHP code:
$val = $_POST['data1'];
$search = "SELECT * FROM employee WHERE emp_name = :val OR salary = :val OR date_employed = :val";
$insertStmt = $conn->prepare($search);
$insertStmt->bindValue(":val", $val);
$insertStmt->execute();
$insertStmt->fetchAll();
//echo "success";
//$lastid = $conn->lastInsertId();
$i = 0;
foreach($insertStmt as $row)
{
$arr[$i] = $row;
$i++;
}
echo json_encode($arr);
The problem is that I can't get all the lines of this array into AJAX so I can append them into some table. Here is the script:
var txt = $("#txtSearch").val();
$.ajax({
url: 'search.php', // Sending variable emp, pos, and sal, into this url
type: 'POST', // I will get variable and use them inside my PHP code using $_POST['emp']
data: {
data1: txt
}, //Now we can use $_POST[data1];
dataType: "json", // text or html or json or script
success: function(arr) {
for() {
// Here I don't know how to get the rows and display them in a table
}
},
error:function(arr) {
alert("data not added");
}
});
You need to loop over your "arr" data in the success callback. Something along the lines of:
var txt = $("#txtSearch").val();
$.ajax
({
url: 'search.php', //Sending variable emp, pos, and sal, into this url
type: 'POST', //I will get variable and use them inside my PHP code using $_POST['emp']
data: {data1: txt},//Now we can use $_POST[data1];
dataType: "json", //text or html or json or script
success:function(arr)
{
var my_table = "";
$.each( arr, function( key, row ) {
my_table += "<tr>";
my_table += "<td>"+row['employee_first_name']+"</td>";
my_table += "<td>"+row['employee_last_name']+"</td>";
my_table += "</tr>";
});
my_table = "<table>" + my_table + "</table>";
$(document).append(my_table);
},
error:function(arr)
{
alert("data not added");
}
});
You could just return
json_encode($insertStmt->fetchAll());
Also, be sure to retrieve only characters in UTF-8 or JSON_encode will "crash".
Your success function should be like this :
success:function(arr)
{
$.each(arr,function (i,item) {
alert(item.YOUR_KEY);
});
}
Consider the following PHP Block. I want to output "name" to div #1 and "slog" to div #2
<?php
require_once 'db_conx.php';
$Result = mysql_query("SELECT * FROM profiles ORDER BY lastupdated desc limit 1") or die (mysql_error());
while($row = mysql_fetch_array($Result)){
$result = array();
$result['name'] = $row['name'];
$result['slog'] = $row['slog'];
echo json_encode($result);
}
mysql_close($con);
?>
Here's the ajax that just outputs json itself.
var get_fb = (function() {
var counter = 0;
var $buzfeed = $('#BuzFeed');
return function(){
$.ajax({
type: "POST",
url: "../php/TopBusinesses_Algoriththm.php"
}).done(function(feedback) {
counter += 1;
var $buzfeedresults = $("<div id='BuzFeedResult" + counter + "'></div>").addClass('flat-menu-button');
$buzfeedresults.text(feedback);
$buzfeed.append($buzfeedresults);
var $buzfeedDivs = $buzfeed.children('div');
if ($buzfeedDivs.length > 10) { $buzfeedDivs.last().remove(); }
setTimeout(get_fb, 1000);
})
};
})();
get_fb();
You can update the html/content of a DOM element with the following:
document.getElementById(name).innerHTML = "text";
So in this instance:
document.getElementById('#1').innerHTML = $yourNameContent;
document.getElementById('#2').innerHTML = $yourSlogContent;
First: move var counter = 0; outside from get_fb() function;
Second: Do not call get_fb(); explicitly, because (function(){...})(); already calls method after initialization.
Third: Why use POST method if there is not data to submit!
So, do this and have a try:
var counter = 0;
var $buzfeed = $('#BuzFeed');
var get_fb = (function() {
$.ajax({
type: "GET",
url: "../php/TopBusinesses_Algoriththm.php"
}).done(function(feedback) {
counter += 1;
var $buzfeedresults = $("<div id='BuzFeedResult" + counter + "'></div>").addClass('flat-menu-button');
$buzfeedresults.text(feedback);
$buzfeed.append($buzfeedresults);
var $buzfeedDivs = $buzfeed.children('div');
if ($buzfeedDivs.length > 10) { $buzfeedDivs.last().remove(); }
setTimeout(get_fb, 1000);
})
})();
I'm trying to pass image coordinates via json to a php file that should update the database.
I have this in jquery:
var coords=[];
var coord = $(this).position();
var item = { coordTop: coord.top, coordLeft: coord.left };
coords.push(item);
var order = { coords: coords };
$.ajax({
type: "POST",
data : +$.toJSON(order),
url: "updatecoords.php",
success: function(response){
$("#respond").html('<div class="success">X and Y Coordinates
Saved</div>').hide().fadeIn(1000);
setTimeout(function(){
$('#respond').fadeOut(1000);
}, 2000);
}
});
This is what updatecoords.php looks like:
<?php
$db = Loader::db();
$data = json_decode($_POST['data']);
foreach($data->coords as $item) {
$coord_X = preg_replace('/[^\d\s]/', '', $item->coordTop);
$coord_Y = preg_replace('/[^\d\s]/', '', $item->coordLeft);
$x_coord = mysql_real_escape_string($coord_X);
$y_coord = mysql_real_escape_string($coord_Y);
$db->Execute("UPDATE coords SET x_pos = '$x_coord', y_pos = '$y_coord'");
}
?>
The success message shows from the javascript however nothing gets updated in the database?
Any thoughts?
You have a + before $.toJSON. Meaning that the json string it returns will be converted to an integer - probably 0 or NaN.
Alex is right, but you can also take the quotes out from the preg_replace pattern. PHP naturally uses /.../ slashes to "quote" a regular expression.
try this
UPDATE coords SET x_pos = '".$x_coord."', y_pos = '".$y_coord."'
and look here how to use toJSON
EDIT :
try this
$.ajax({
type: "POST",
data : { coordTop: coord.top, coordLeft: coord.left ,coords: coords },
and in second code do this
$data = json_decode($_POST['data']);
$coordTop = mysql_real_escape_string($_POST['coordTop']);
$coordLeft = mysql_real_escape_string($_POST['coordLeft']);
$coords = mysql_real_escape_string($_POST['coords']);
foreach(.........
.....
.....
and then use those variables $coordTop , $coordLeft , $coords
Thanks for the help but this seemed to do the trick....
In javascript:
$.post('updatecoords.php', 'data='+$.toJSON(order), function(response){ alert (response + mydata);
In Updatecoords.php:
$data = json_decode(stripcslashes($_POST['data']));
I'm grabbing some database entries, creating a 2D array and then passing them to js with AJAX. But when I loop through the array in javascript, it's an "undefined" mess. The console log for dbArray works fine, so I know the PHP/AJAX is working. Not sure what I am doing wrong with the loop...
PHP ('load-words.php):
$query = mysql_query("
SELECT * FROM words
ORDER BY RAND()
LIMIT 50
") or die(mysql_error());
$dbArray = array();
while ($row = mysql_fetch_assoc($query)) {
$word_phrase = stripslashes($row['word_phrase']);
$description = stripslashes($row['description']);
// construct a 2D array containing each word and description
$dbArray[] = array($word_phrase,$description);
};
echo json_encode($dbArray);
Javascript:
$.ajax({
url: 'func/load-words.php',
success: function(dbArray) {
console.log(dbArray);
var items = "<ul>";
for (var i in dbArray) {
items += "<li><a href='#'><b>" + dbArray[i][0] + ' : ' + dbArray[i][1] + "</a></li>";
}
items += "</ul>";
div = $('#dbArray');
div.html(items);
}
});
I guess this is failing because jQuery is interpreting the AJAX response as a string, since your PHP is not outputting a JSON header and your AJAX is not stipulating JSON. This is easily tested:
$.ajax({
url: 'func/load-words.php',
success: function(dbArray) { alert(typeof dbArray); /* "string"? */ }
});
Try
$.ajax({
url: 'func/load-words.php',
dataType: 'json', //<-- now we explicitly expect JSON
success: function(dbArray) { alert(typeof dbArray); /* "object"? */ }
});