Fastest way to get the Ajax callbacks - php

I have a table called 'items' which has 10 rows. This 'items' table contain 2 columns(id, item_name). item_name is where I store the images' names such as item_fdsj43.jpg, item_bdf34.jpg, and so on...
If I want to displayed all these images, I do something like this:
fetching.php:
$query = "SELECT item_name FROM items";
$mysql_query = mysql_query($query);
while($mysql_fetch_assoc = mysql_fetch_assoc($mysql_query)){
$mysql_fetch_assoc_item_name = $mysql_fetch_assoc['item_name'];
echo 'img/'.$mysql_fetch_assoc_item_name;
}
JAVASCRIPT
$('fetching.php', function(data)){
$('#inner_container').append(data);
});
This will display all the data simultaneously and append it on '#inner_container' once the fetching is done. However, this callbacks takes a while and slower compare to search engine of this website (http://www.bedbathstore.com/). Is there any way to boost its speed?

Here i can suggest to you JSON instead of output data using echo below are the sample code
you can modify it for your needs
PHP code
ob_start();
imagepng($my_img);
$imageData = ob_get_contents();
ob_clean();
$results = array(
'price' => $_GET['priceX'],
'image' => base64_encode($imageData)
);
$json = json_encode($results);
echo $json;
Javascript code:
$.getJSON("/ajax-script.php", function(data) {
$("#element").append($("<img />").attr('src', 'data:image/png;charset=utf8;base64,' + data.image));
});

You can use json to retrieve the image paths at once from the server asynchronously and then you can append these images to image container like this,
//fetching.php:
$query = "SELECT item_name FROM items";
$mysql_query = mysql_query($query);
$file_names = array();
while($mysql_fetch_assoc = mysql_fetch_assoc($mysql_query)){
$mysql_fetch_assoc_item_name = $mysql_fetch_assoc['item_name'];
array_push($file_names, 'img/'.$mysql_fetch_assoc_item_name);
}
echo json_encode($file_names);
//JAVASCRIPT
$.getJSON("fetching.php", function(data) {
$.each(data, function() {
$('#inner_container').append($("<img />").attr('src', this);
});
});

Related

How to bring more than one row (mysql) result inside the same variable when running a json_encode?

I am running a POST + json code to collect data from database, all results come with only one value (this is correct), however there is only one column which should show more than one value but shows only the first one. What I need to change in my code to get this list instead of the first row result?
I've run one MYSQL query linking three databases those share the same id PCRNo, the first two databases tPCR and tcomplement should only have one result and the third one should receive more results due to we can have more lines with the same id.
This is my JavaScript
<script>
$(document).ready(function(){
$('#table').on('click', '.fetch_data', function(){
var pcr_number = $(this).attr('id');
$.ajax({
url:'fetch.php',
method:'post',
data:{pcr_number:pcr_number},
dataType:"json",
success:function(data){
$('#PCR').val(data.PCRNo);
$('#PCC').val(data.PCC);
$('#PCR_Creation').val(data.Creation_Date);
$('#PCR_Status').val(data.Stage);
$('#Required_Completion').val(data.Required_Completion);
$('#description').val(data.Name);
$('#Comments').val(data.Comments);
$('#originator').val(data.Creator);
$('#change_type').val(data.Category);
$('#product_type').val(data.Product);
$('#req_dept').val(data.Department);
$('#flow').val(data.Flow_Start_Date);
$('#own').val(data.Owning_Site);
$('#impacted').val(data.Impacted_Site);
$('#approval').val(data.Meeting_Status);
$('#review').val(data.Review_Date);
$('#cat').val(data.Cat);
$('#cost').val(data.Cost);
$('#labor').val(data.Labour);
$('#volume').val(data.Volume);
$('#request').val(data.Request);
$('#justification').val(data.Justification);
$('#PCNlist').val(data.PCNNo);
$('#monitor').val(data.Monitor);
$('#env').val(data.Environment);
$('#trial').val(data.Trial);
$('#resp').val(data.Responsible);
$('#deadline').val(data.Deadline);
$('#dataModal').modal('show');
}
});
});
$(document).on('click', '#update', function(){
var pcr_number = document.getElementById("PCR").value;
var Comments= document.getElementById("Comments").value;
var approval= document.getElementById("approval").value;
var review= document.getElementById("review").value;
var cat= document.getElementById("cat").value;
var monitor= document.getElementById("monitor").value;
var env= document.getElementById("env").value;
var trial= document.getElementById("trial").value;
var resp= document.getElementById("resp").value;
var deadline= document.getElementById("deadline").value;
var PCC = document.getElementById("PCC").value;
$.ajax({
url:"edit.php",
method:"POST",
data:{pcr_number:pcr_number, Comments:Comments, PCC:PCC, approval:approval, review:review, cat:cat, monitor:monitor, env:env, trial:trial, resp:resp, deadline:deadline},
dataType:"text",
success:function(data)
{
alert('PCR Information Updated');
}
});
});
});
</script>
this is my fetch.php
<?php
$SelectedPCRNo = $_POST['pcr_number'];
if(isset($_POST['pcr_number']))
{
$output = '';
$hostname = "localhost";
$username = "root";
$password = "";
$databaseName = "change_management";
$dbConnected = #mysqli_connect($hostname, $username, $password);
$dbSelected = #mysqli_select_db($databaseName,$dbConnected);
$dbSuccess = true;
if ($dbConnected) {
if ($dbSelected) {
echo "DB connection FAILED<br /><br />";
$dbSuccess = false;
}
} else {
echo "MySQL connection FAILED<br /><br />";
$dbSuccess = false;
}
$sql = mysqli_query($dbConnected, "SELECT * FROM change_management.tPCR INNER JOIN change_management.tcomplement ON change_management.tPCR.PCRNo = change_management.tcomplement.PCRNo INNER JOIN change_management.tPCN ON change_management.tPCR.PCRNo = change_management.tPCN.PCRNo WHERE tPCR.PCRNo = '".$_POST['pcr_number']."'");
$row = mysqli_fetch_array($sql);
echo json_encode($row);
}
?>
I have no problems with the results and the table is filled OK, only the #PCNlist should be filled with the values of all rows it is related and now just is just coming one value, the first row only. Is there any way to bring the whole PCNlist only changing some code at the fetch.php?
If I understood you correctly, the table tPCN can contain multiple rows associated with each PCR number. And you want to fetch all these rows and return them in your JSON.
If you want to achieve that, but also make sure the other two tables only return one row, then I think simply you should remove the JOIN to tPCN in your first query, and then create a second query to fetch the tPCN rows specifically.
$output = [];
$stmt = $dbConnected->prepare("SELECT * FROM change_management.tPCR INNER JOIN change_management.tcomplement ON change_management.tPCR.PCRNo = change_management.tcomplement.PCRNo WHERE tPCR.PCRNo = ?");
$stmt->bind_param('s', $_POST['pcr_number']);
$stmt->execute();
$result = $stmt->get_result();
//select a single row from the result and assign it as the output variable
if ($row = $result->fetch_assoc()) {
$output = $row;
}
$stmt2 = $dbConnected->prepare("SELECT * FROM change_management.tPCN WHERE PCRNo = ?");
$stmt2->bind_param('s', $_POST['pcr_number']);
$stmt2->execute();
$result2 = $stmt2->get_result();
$output["tPCN"] = array(); //create a new property to put the tPCN rows in
//loop through all the tPCN rows and append them to the output
while ($row2 = $result2->fetch_assoc()) {
$output["tPCN"][] = $row2;
}
echo json_encode($output);
This will produce some JSON with this kind of structure:
{
"PCRNo": "ABC",
"CreationDate": "2019-08-07",
"Name": "A N Other",
//...and all your other properties, until the new one:
"tPCN": [
{
"SomeProperty": "SomeValue",
"SomeOtherProperty": "SomeOtherValue",
},
{
"SomeProperty": "SomeSecondValue",
"SomeOtherProperty": "SomeOtherSecondValue",
}
]
}
You will then need to amend your JavaScript code to be able to deal with the new structure. Since I don't know exactly which fields come from the tPCN table, I can't give you an example for that, but hopefully it's clear that you will need to loop through the array and output the same HTML for each entry you find.
N.B. As you can see I re-wrote the query code to use prepared statements and parameterised queries, so you can see how to write your code in a secure way in future.
P.S. You have a lot of code there in the "success" function just to set the values of individual fields. You might want to consider using a simple JS templating engine to make this less verbose and cumbersome, and generate the HTML you need with the values automatically added into it in the right place. But that's a separate issue, just for the maintainability of your code
I've added this code into my ajax function to bring only what I needed and it works + what #ADyson has posted.
var PCN = data.tPCN;
var i;
var PCNList = '';
for (i = 0; i < PCN.length; i++){
var PCNList = PCNList + PCN[i]['PCNNo'] + ' - ' + PCN[i]['Stage'];
}
$('#PCNlist').val(PCNList);

jQuery datatable large dataset delay

My jQuery datatable is taking a little too long to display some data.
The query is simple. In the database, running the same query returns the same results in microseconds, regardless of size.
Here is how the query looks in my PHP script:
<?php
$searchCommodity = $_POST['commodity'];
$select = "SELECT COMM_CODE, KEY_COMM, MOD_DATE, MOD_USER FROM keyTable WHERE KEY_COMM = '$searchCommodity'";
$query = mysqli_query($dbc, $select);
$out = array();
while($row = $query->fetch_assoc())
{
$out[] = $row;
}
echo json_encode($out);
?>
Most of the data returned is less than 1000 records. But there are a few that return more than 10K to 20K records.
This causes a delay in which if the user is using Firefox, they will receive the "A web page is slowing down your browser. What would you like to do?" error message where they have to select 'Stop' or 'Wait'.
Back in my jQuery, here is how I'm sending the parameter to the PHP script:
$('#commoditySelect').on('change', function()
{
var commodity = $('#commoditySelect').val();
$.post('api/searchKeyComms.php', {commodity:commodity}, function(data)
{
var table = $('#example1').DataTable();
table.clear();
table.search('').draw();
var obj = JSON.parse(data);
obj.forEach(function(item)
{
table.row.add([item.COMM_CODE, item.KEY_COMM, item.MOD_DATE, item.MOD_USER]);
});
table.draw();
});
});
On the main HTML page, near the bottom, I set the datatable like this:
$('#example1').DataTable({
"dataType": "json",
"iDisplayLength": 25,
"order": [[ 6, "desc" ]],
"scrollY": 550,
"scrollX": true,
"bDestroy": true,
"stateSave": true
});
Is there anything that I can add/change to any of the code above that will improve the performance of the rendering of the datatable?
I found this page: https://datatables.net/forums/discussion/2651/alternative-server-side-php-script
But I am not doing any concatenations. As stated above, it's a simple query that I'm using, and in the database, the data is returned quickly.
I even found this page: rendering large server-side datasets in jquery datatables
But the only thing I got from that page is that datatables are not made for large datasets. 20K doesn't seem too large.
Why loop on your $out array since your $row is already an associative array.. No need to loop.. ^_^
<?php
$searchCommodity = $_POST['commodity'];
$select = "SELECT COMM_CODE, KEY_COMM, MOD_DATE, MOD_USER FROM keyTable WHERE KEY_COMM = '$searchCommodity'";
$query = mysqli_query($dbc, $select);
$row = $query->fetch_assoc()
echo json_encode($row);
?>

Create array in php and use Jquery get

I'm trying to make a call to the database and recieve a "toplist" that is limited to 10 in PHP. Here I need to make an array and give it back to the Jquery with $.get().
But it's failing in recieving all the data with this code, How can I make this to be recieved and then do a "for each" in the Jquery for all the data that is being sent back from the PHP?
Jquery:
$.get("core.inc.php?get_toplist=1",
function(data) {
var json = JSON.parse(data);
alert(json['name']);
});
PHP:
if ($_GET['get_toplist']) {
$get_top_list = mysql_query("
SELECT * FROM ".$DBprefix."Submissions
WHERE status='1'
ORDER BY points DESC LIMIT 10");
$i = 0;
$arr = array();
while ($top_list = mysql_fetch_array($get_top_list)) {
$arr[] = array(
'position' => $i++,
'name' => $top_list['name'],
'points' => $top_list['points']
);
}
echo json_encode($arr);
}
You're returning an array, but your Javascript code is treating it as a single element. Try:
alert(json[0].name);
If you want a foreach, you can do:
$.each(json, function(i, el) {
console.log(el.name + " score is " + el.points);
});
Friend your json will be like .
[{"position":1,"name":"name1","points":"points"},{"position":2,"name":"name2","points":"points"}, {"position":3,"name":"name3","points":"points"},....]
so you can not directly access it like ur way.
make a loop then access it.
$.each(data,function(i,val){
alert(val.name);
});
this will work.
your php code is not proper
if ($_GET['get_toplist']) {
$get_top_list = mysql_query("
SELECT * FROM ".$DBprefix."Submissions
WHERE status='1'
ORDER BY points DESC LIMIT 10");
$i = 0;
$arr = array();
while ($top_list = mysql_fetch_array($get_top_list)) {
$arr[] = array(
'position' => $i++,
'name' => $top_list['name'],
'points' => $top_list['points']
);
}
}
echo json_encode($arr);
}
just add '}' before echo json_encode($arr);
also you are getting an array change in alert(json[0]['name']);

Error with my dojo ajax php request

Im trying to use a dojo ajax function to call a PHP file that then returns the contents of a DB table in JSON format.
My function:
var _getWeatherInfo = function(){
dojo.xhrget({
url: "PHP/weather.php?ntown=" + _ntown,
handleAs: "json",
timeout: 5000,
load: function(responce, details) {
_updateWeathertData
},
error: function(error_msg, details) {
_handleError(error_msg);
}
});
}
My PHP:
<?php include('configHome.php'); ?>
<?php
$ntown = $_GET['ntown'];
$weather = array();
$query="SELECT * FROM `weather` WHERE `town` = '$ntown'";
$result=mysql_query($query);
while($row = mysql_fetch_row($result)) {
$weather[] = $row[0];
}
echo json_encode($weather);
mysql_close();
?>
When using this code I am getting an error message saying that "$ntown = $_GET['ntown'];" is an undefined index. I have tried removing the index all together and using an actual value in the select statement (i.e. SELECT * FROM weather WHERE town = 'Auckland') but all I get back is the value i enter ["Auckland"], and not the 3 other values that are meant to be returned, ["Auckland", "Sunny", "8", "14"].
Any ideas? I can try add more info if needed. Thanks!
There are some other issues with your code, but to get to the one you are asking the question about. You have this:
while($row = mysql_fetch_row($result)) {
$weather[] = $row[0];
}
What you are doing is just taking the first value of the row (of which there is probably only one, and just sending that back. This is what you need:
$weather = mysql_fetch_row($result);

Ajax Printing Database Records to Multiple Fields

I currently have code which will pull the first element from a database record and print it in an output box.
What is the easiest way to print the rest of the elements of that record to the other relevant output boxes?
My PHP file takes an 'id' specified by the user.
$id = $_POST['id'];
$query = "SELECT * FROM Customers WHERE ID = $id";
$result= mysql_query($query);
if (mysql_num_rows($result) > 0) {
while($row = mysql_fetch_row($result)) {
echo $row[1];
}
}
And this is the code in the HTML file
jQuery(document).ready(function(){
jQuery("input.myid").keyup(function(e){
e.preventDefault();
ajax_search();
});
});
function ajax_search(){
var search_val=jQuery("input.myid").val();
jQuery.post("find.php", {id : search_val}, function(data){
if (data.length>0){
jQuery("input.fname").val(data);
}
});
}
The code takes the id ('myid') and prints to a text box named 'fname'.
I find it easier to json_encode the whole thing (record I mean) and use something like jquery.populate which basically takes an object and fills a form with it (all fields it can find which names' match properties from the object).
I hope this makes sense.

Categories