How to display array of json data properly in html? - php

My Ajax
$("form").on("submit", function () {
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "ajax2.php", //Relative or absolute path to response.php file
data: data,
success: function (data) {
$("#main_content").slideUp("normal",function(){
$(".the-return").html("<br />JSON: " + data);
//how to alter this part to display data for each record in one div?
});
}
});
return false;
});
My query
$statement = $pdo->prepare("SELECT * FROM posts WHERE subid IN (:key2) AND Poscode=:postcode2");
$statement->execute(array(':key2' => $key2,':postcode2'=>$postcode));
// $row = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = array();
while( $row = $statement->fetch()) {
array_push($json, array($row['Name'], $row['PostUUID']));
}
header('Content-Type: application/json');
echo json_encode($json);
The result displayed currently in this form:
JSON: jack,55421894ab602,test,55439324cc43d
But I want to display like:
Name:jack,
Id:55421894ab602
.....and some other info-
Name:test
Id:55439324cc43d
.....and some other info-
This part:
$(".the-return").html("<br />JSON: " + data);
I tried: data[0];
But when I do this, only the first record displayed obviously.
What I'm trying is :
data[0] itself is an array. How to display that array together with other records fetched in nice html?
edited: WIth these edited code, i can only retrieve the last result, it's not looping through the array.
ajax
success: function (data) {
$("#main_content").slideUp("normal",function(){
//$(".the-return").html("<br />JSON: " + j_data);
for (i = 0; i < data.length; i++) {
$(".the-return").html("<div>Name:" + data[i].name + "<br/>Id:" + data[i].id);
}
console.log(data); // this shows nothing in console,I wonder why?
//alert(j_data);
});
}
php
$json = array();
while( $row = $statement->fetch()) {
//array_push($json, array($row['Name'], $row['PostUUID']));
array_push($json, array("name" => $row['Name'], "id" => $row['PostUUID']));
}
header('Content-Type: application/json');
echo json_encode($json);

First, to get the names of the fields in your template, you need store them in your array:
array_push($json, array("name" => $row['Name'], "id" => $row['PostUUID']));
Result after json_encode -> {"name":"TheName","id":"TheID"}
Next, in your js code, if the json that it receives is valid, you can do a loop:
success: function (data) {
$("#main_content").slideUp("normal",function(){
for (i = 0; i < data.length; i++) {
$(".the-return").html("<div>Name:" + data[i].name + "<br/>Id:" + data[i].id);
}
}
}
Of course, you can add style or class to the div.
I hope it helps.

Related

jQuery Ajax Request fails to bring all data with SQL Query to fields

i have a form that works by filling the next select fields with data based on the previous ones, it works perfect on Localhost / Xampp with PHP8 but now when i try to get it on my server it only works "once" per category.
My problem simplified.
I select category1 and get two results based on that to the next select
Only one of these results works with returning data to the 3rd Select and the other one doesn't return anything with json_encode and only throws an error
More info:
Request that works.
{
"request": "2",
"subcategoryid": "11",
"alakategoriaID": "15"
}
[
Response which is correct.
{
"ID": "23",
"name": "Puu 25"
},
{
"ID": "24",
"name": "Puu 50"
}
Request that doesn't return anything
{
"request": "2",
"subcategoryid": "10",
"alakategoriaID": "15"
}
Main function that contains the select fields etc..
´´´<script>
$(function () {
// Country
$('#sel_country').change(function () {
var categoryID = $(this).val();
// Empty state and city dropdown
$('#sel_state').find('option').not(':first').remove();
$('#sel_city').find('option').not(':first').remove();
$('#varichanger').find('option').not(':first').remove();
// AJAX request
$.ajax({
url: 'helper.php',
type: 'post',
data: {
request: 1,
categoryID: categoryID
},
dataType: 'json',
success: function (response) {
var len = response.length;
for (var i = 0; i < len; i++) {
var id = response[i]['id'];
var name = response[i]['name'];
$("#sel_state").append("<option value='" + id + "'>" + name + "</option>");
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("some error");
}
});
$.ajax({
url: 'helper.php',
type: 'post',
data: {
request: 3,
categoryID: categoryID
},
dataType: 'json',
success: function (response) {
var len = response.length;
for (var i = 0; i < len; i++) {
var id = response[i]['id'];
var name = response[i]['name'];
$("#varichanger").append("<option value='" + id + "'>" + name + "</option>");
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("some error");
}
});
});
// State
$('#sel_state').change(function () {
var subcategoryid = $(this).val();
var alakategoriaID = $('#sel_country').val();
// Empty city dropdown
$('#sel_city').find('option').not(':first').remove();
// AJAX request
$.ajax({
url: 'helper.php',
type: 'post',
data: {
request: 2,
subcategoryid: subcategoryid,
alakategoriaID: alakategoriaID
},
dataType: 'json',
success: function (response) {
console.log(response);
var len = response.length;
for (var i = 0; i < len; i++) {
var id = response[i]['ID'];
var name = response[i]['name'];
$("#sel_city").append("<option value='" + id + "'>" + name + "</option>");
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("some error");
}
});
});
});
</script>´´´
Helper.php
include "pdoconfig.php";
error_reporting(0);
$request = 0;$request = 0;
if(isset($_POST['request'])){
$request = $_POST['request'];
}
// Fetch subcategory list by categoryID
if(trim($request) == 1){
$categoryID = $_POST['categoryID'];
$stmt = $conn->prepare("SELECT * FROM alakategoriat WHERE kategoriaID=:kategoriaID ORDER BY subcategoryname");
$stmt->bindValue(':kategoriaID', (int)$categoryID, PDO::PARAM_INT);
$stmt->execute();
$subcategorysList = $stmt->fetchAll();
$response = array();
foreach($subcategorysList as $subcategory){
$response[] = array(
"id" => $subcategory['id'],
"name" => $subcategory['subcategoryname']
);
}
echo json_encode($response);
exit;
}
// Fetch city list by subcategoryid
if(trim($request) == 2){
$kategoriaID = $_POST['alakategoriaID'];
$alakategoriaID = $_POST['subcategoryid'];
$stmt = $conn->prepare("SELECT * FROM tuotteet
WHERE kategoriaID=$kategoriaID
AND alakategoriaID=$alakategoriaID
ORDER BY productname");
$stmt->execute();
$productslist = $stmt->fetchAll();
$response = array();
foreach($productslist as $product){
$response[] = array(
"ID" => $product['ID'],
"name" => $product['productname']
);
}
echo json_encode($response);
exit;
}
if(trim($request) == 3){
$categoryID = $_POST['categoryID'];
$stmt = $conn->prepare("SELECT *
FROM kategoriavarit
INNER JOIN varit ON kategoriavarit.variID = varit.variID
WHERE kategoriaID=:kategoriaID");
$stmt->bindValue(':kategoriaID', (int)$categoryID, PDO::PARAM_INT);
$stmt->execute();
$varilist = $stmt->fetchAll();
$response = array();
foreach($varilist as $vari){
$response[] = array(
"id" => $vari['variID'],
"name" => $vari['varinimi']
);
}
echo json_encode($response);
exit;
}
you have to save your first category value to session and use it for second time ajax call. As per your code you always get
trim($request) == 1
because each time ajax call it consider as new request. So use session or cookie for store and use parent category.
Solved the problem by clearing and reinserting my database values and following #Foramkumar Patel's answer
EDIT: Cancel that, problem was with scandinavian letters in the response from JSON causing many different problems, solved the problem by utf_8 encoding the response.

Ajax never initiating success: when using xhrFields

I am having trouble getting the success call to fire in my ajax request. I know the communication is working fine, but the last call in my PHP script, which is a return json_encode($array); will fire as if it is a part of the onprogress object. I would like to "break" the onprogress call and run the success function on the last data sent via return json_encode when the PHP script has terminated...
Here is my AJAX call:
$( document ).ready(function(e) {
var jsonResponse = '', lastResponseLen = false;
$("#btn_search").click(function(e){
var firstname = document.getElementById('firstname').value;
var lastname = document.getElementById('lastname').value;
$.ajax({
type: "POST",
url: 'search.php',
data: $('#search_fields').serialize(),
dataType: "json",
xhrFields: {
onprogress: function(e) {
var thisResponse, response = e.currentTarget.response;
if(lastResponseLen === false) {
thisResponse = response;
lastResponseLen = response.length;
} else {
thisResponse = response.substring(lastResponseLen);
lastResponseLen = response.length;
}
jsonResponse = JSON.parse(thisResponse);
document.getElementById('progress').innerHTML = 'Progress: '+jsonResponse.msg;
}
},
success: function(data) {
console.log('done!');
document.getElementById('progress').innerHTML = 'Complete!';
document.getElementById('results').innerHTML = data;
}
});
e.preventDefault();
});
});
And here is the basic PHP server script:
<?php
function progress_msg($progress, $message){
echo json_encode(array('progress' => $progress, 'msg' => $message));
flush();
ob_flush();
}
$array = array('msg' => 'hello world');
$count = 0;
while($count < 100){
progress_message($count, "working....");
$count += 10;
sleep(2);
}
return json_encode($array);
?>
I made your code work, there were 2 errors. First, in your while loop, your function name is incorrect, try this:
progress_msg($count, "working... ." . $count . "%");
Secondly, the very last line outputs nothing, so technically you don't get a "successful" json return. Change the last line of your server script from:
return json_encode($array);
to:
echo json_encode($array);
UPDATE: Full working code with hacky solution:
Ajax:
$( document ).ready(function(e) {
var jsonResponse = '', lastResponseLen = false;
$("#btn_search").click(function(e){
var firstname = document.getElementById('firstname').value;
var lastname = document.getElementById('lastname').value;
$.ajax({
type: "POST",
url: 'search.php',
data: $('#search_fields').serialize(),
xhrFields: {
onprogress: function(e) {
var thisResponse, response = e.currentTarget.response;
if(lastResponseLen === false) {
thisResponse = response;
lastResponseLen = response.length;
} else {
thisResponse = response.substring(lastResponseLen);
lastResponseLen = response.length;
}
jsonResponse = JSON.parse(thisResponse);
document.getElementById('progress').innerHTML = 'Progress: '+jsonResponse.msg;
}
},
success: function(data) {
console.log('done!');
dataObjects = data.split("{");
finalResult = "{" + dataObjects[dataObjects.length - 1];
jsonResponse = JSON.parse(finalResult);
document.getElementById('progress').innerHTML = 'Complete!';
document.getElementById('results').innerHTML = jsonResponse.msg;
}
});
e.preventDefault();
});
Search.php:
<?php
function progress_msg($progress, $message){
echo json_encode(array('progress' => $progress, 'msg' => $message));
flush();
ob_flush();
}
$array = array('msg' => 'hello world');
$count = 0;
while($count <= 100){
progress_msg($count, "working... " . $count . "%");
$count += 10;
sleep(1);
}
ob_flush();
flush();
ob_end_clean();
echo json_encode($array);
?>
The problem with the "success" method of the ajax call was that it couldn't interpret the returning data as JSON, since the full return was:
{"progress":0,"msg":"working... 0%"}{"progress":10,"msg":"working... 10%"}{"progress":20,"msg":"working... 20%"}{"progress":30,"msg":"working... 30%"}{"progress":40,"msg":"working... 40%"}{"progress":50,"msg":"working... 50%"}{"progress":60,"msg":"working... 60%"}{"progress":70,"msg":"working... 70%"}{"progress":80,"msg":"working... 80%"}{"progress":90,"msg":"working... 90%"}{"progress":100,"msg":"working... 100%"}{"msg":"hello world"}
Which is not a valid JSON object, but multipje JSON objects one after another.
I tried removing all previous output with ob_end_clean(); , but for some reason I can't figure out, it didn't work on my setup. So instead, the hacky solution I came up with was to not treat the return as JSON (by removing the dataType parameter from the AJAX call), and simply split out the final Json element with string operations...
There has got to be a simpler solution to this, but without the use of a third party jQuery library for XHR and Ajax, I couldn't find any.

Select multiple rows into array and send them via AJAX

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);
});
}

How to pass mysql result as jSON via ajax

I'm not sure how to pass the result of mysql query into html page via ajax JSON.
ajax2.php
$statement = $pdo - > prepare("SELECT * FROM posts WHERE subid IN (:key2) AND Poscode=:postcode2");
$statement - > execute(array(':key2' => $key2, ':postcode2' => $postcode));
// $row = $statement->fetchAll(PDO::FETCH_ASSOC);
while ($row = $statement - > fetch()) {
echo $row['Name']; //How to show this in the html page?
echo $row['PostUUID']; //How to show this in the html page?
$row2[] = $row;
}
echo json_encode($row2);
How to pass the above query result to display in the html page via ajax below?
my ajax
$("form").on("submit", function () {
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "ajax2.php", //Relative or absolute path to response.php file
data: data,
success: function (data) {
//how to retrieve the php mysql result here?
console.log(data); // this shows nothing in console,I wonder why?
}
});
return false;
});
Your json encoding should be like that :
$json = array();
while( $row = $statement->fetch()) {
array_push($json, array($row['Name'], $row['PostUUID']));
}
header('Content-Type: application/json');
echo json_encode($json);
And in your javascript part, you don't have to do anything to get back your data, it is stored in data var from success function.
You can just display it and do whatever you want on your webpage with it
header('Content-Type: application/json');
$row2 = array();
$result = array();
$statement = $pdo->prepare("SELECT * FROM posts WHERE subid IN (:key2) AND Poscode=:postcode2");
$statement->execute(array(':key2' => $key2,':postcode2'=>$postcode));
// $row = $statement->fetchAll(PDO::FETCH_ASSOC);
while( $row = $statement->fetch())
{
echo $row['Name'];//How to show this in the html page?
echo $row['PostUUID'];//How to show this in the html page?
$row2[]=$row;
}
if(!empty($row2)){
$result['type'] = "success";
$result['data'] = $row2;
}else{
$result['type'] = "error";
$result['data'] = "No result found";
}
echo json_encode($row2);
and in your script:
$("form").on("submit",function() {
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "ajax2.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
console.log(data);
if(data.type == "success"){
for(var i=0;i<data.data.length;i++){
//// and here you can get your values //
var db_data = data.data[i];
console.log("name -- >" +db_data.Name );
console.log("name -- >" +db_data.PostUUID);
}
}
if(data.type == "error"){
alert(data.data);
}
}
});
return false;
});
In ajax success function you can use JSON.parse (data) to display JSON data.
Here is an example :
Parse JSON in JavaScript?
you can save json encoded string into array and then pass it's value to javascript.
Refer below code.
<?php
// your PHP code
$jsonData = json_encode($row2); ?>
Your JavaScript code
var data = '<?php echo $jsonData; ?>';
Now data variable has all JSON data, now you can move ahead with your code, just remove below line
data = $(this).serialize() + "&" + $.param(data);
it's not needed as data variable is string.
And in your ajax2.php file you can get this through
json_decode($_REQUEST['data'])
I would just..
$rows = $statement->fetchAll(FETCH_ASSOC);
header("content-type: application/json");
echo json_encode($rows);
then at javascript side:
xhr.addEventListener("readystatechange",function(ev){
//...
var data=JSON.parse(xhr.responseText);
var span=null;
var i=0;
for(;i<data.length;++i){span=document.createElement("span");span.textContent=data[i]["name"];div.appendChild(span);/*...*/}
}
(Don't rely on web browsers parsing it for you in .response because of the application/json header, it differs between browsers... do it manually with responseText);

is php json_encode & AJAX breaking my array?

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"? */ }
});

Categories