How to get loop array from php to AJAX - php

I want to get all of array value with ajax which that is coming from MySQL. I can't get all of result. I can get only 1 result.
My JQuery codes are:
$("input.input-search").keyup(function(){
var name = $(this).val();
if(name !='')
{
$.ajax({
type: 'post',
url: 'ajax.php?bol=search',
data: {'name':name},
dataType: 'json',
success: function(val)
{
x = val.length;
for (i = 1; i<=x; i++){
$(".search-result").html(val[i].user+' * '+x);
}
},
error: function(name){
$(".search-result").html("Nəticə yoxdur...");
}
});
}
});
PHP Codes are:
case "search":
$name = trim($_POST['name']);
$q = mysql_query("SELECT * FROM `users` WHERE `user` LIKE '%".$name."%' ORDER by id;");
if(mysql_affected_rows() > 0){
while($arr = mysql_fetch_array($q)){
$array[] = $arr;
}
echo json_encode($array);
}
break;

It's simple. You are overwriting your elements HTML content every time your loop runs. With the jQuery
.html("...")
method you set a new content for your selected element every time your loop runs.
So use
.append('...')
instead.
Of course at the very beginning of your success - method empty your element with
.html("");

If your query is only returning 2 rows, the problem lies in your Javascript for loop. You're starting at 1 when the array index starts at 0. Try this:
for (i = 0; i <= x; i++) {...}

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

Initialize first ajax data with a preset value then pass it from success response

How can I initialize the lastID in jquery only first time with the value 0 because var lastID = 0; does not work.
I have this ajax script in index.php
<script>
$(document).ready(function () {
var lastID = 0;
function getData() {
$.ajax({
type: 'GET',
url: 'data.php',
data: {lastID: lastID},
dataType: 'json',
success: function (data) {
lastID = data[0].id;
console.log(lastID);
$.each(data, function (i, item) {
var $tr = $('<tr>').append(
$('<td>').text(item.id),
$('<td>').text(item.name),
$('<td>').text(item.details)
).appendTo('#output');
});
}
});
}
getData();
setInterval(function () {
getData();
}, 10000); // it will refresh your data every 10 seconds
});
</script>
This is the url: 'data.php' :
$sql = "select * from oders where id > ".$lastID." ORDER BY id DESC";
...
echo json_encode($dataArray);
With this query I get 0 results, and in console (console.log(lastID);) I have no data.
If I change the query like this :
$sql = "select * from oders where id > 0 ORDER BY id DESC";
In console.log(lastID); I get the correct last id. And in html I get the correct data and every 10 seconds it keeps adding same results over and over again.
I can't figure out how to initialize lastID first time as 0 (or the last ID in the database), and on every 10 seconds refresh, take the last ID from the ajax success data.
Where does your $lastID variable come from, how is it defined?
It looks like you are not getting the correct value from the $_GET array.
What you should do to both solve that problem and the sql injection problem you have, is switch to a prepared statement:
$sql = "select * from oders where id > ? ORDER BY id DESC";
And bind $_GET['lastID'] to the placeholder before / during the execution of your query (depending on whether you are using mysqli or PDO).

Clear previous ajax response data before appending new data

I am trying to .append() a selected data from a radio button but it display all the previous respond result.
My HTML :
$sql = "SELECT DISTINCT(name) FROM table1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$i = 1;
while($row = $result->fetch_assoc()) {
echo '<label>'.$row['name'].'</label>';
$sql2 = "SELECT * FROM table1 WHERE list = '".$row['list']."'";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
while($row2 = $result2->fetch_assoc()) {
echo '<input name="group['.$i.']" class="id" type="radio" data-id="'.$row2['id'].'" />'.$row2['list'];
}
}
$sql2 = NULL;
$i++;
}
}
$sql = NULL;
My ajax to get data and append :
$('.id').on('click', function(){
var id = $(this).data('id');
$.ajax ({
type: 'POST',
url: 'url-here',
data: { id : id },
success : function(data) {
$('#list').append(data);
}
});
});
For PHP side if there is $_POST['id'] then do mysql query to filter from table and return result.
if(isset($_POST['id'])){
$sql = "SELECT * FROM table1 WHERE id = '".$_POST['id']."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo '<label>'.$row['name'].'</label>';
}
}
}
So what happened in my ajax result box, it keep appending the previous data that been processed by ajax together with the new data.
EDIT : Example append result :
First result of selected radio button : string 1
Second result of selected radio button : string 2
So result should be :
string 1
string 2
Sorry there was a mistake with my explanation. My ajax box result is resulting something like this :
string 1
string 2 (new data from another selected radio)
string 2 (new data is duplicating)
If adding select another radio it will become like this :
string 1
string 2
string 2
string 3 (new data)
string 3 (new data duplicating)
string 3 (new data duplicating)
string 3 (new data duplicating)
My ajax box result :
<div id="list"></div>
Add any class in label and input
echo '<label class="ajax">'....
....
echo '<input class="ajax" ...
....
And Remove in each selection or change in ajax
$('.ajax').remove();
$('#list').append(data);
Or better
$('#list .ajax').remove();
$('#list').append(data);
Update
Or simple add div to your ajax response
$('#list').append("<div class='ajax'>"+data+"</div>");
and then use this code
$('#list .ajax').remove();
$('#list').append(data);
I think you jQuery looks ok. It would be possible for your SQL query to have multiple rows as a result. This could mean that your id value is actually returning two rows. They include the first row and the second row.
You should remove a previously-attached event handler from the elements to avoid multiple click.
$('.id').on('click', function(){
var id = $(this).data('id');
$.ajax ({
type: 'POST',
url: 'url-here',
data: { id : id },
success : function(data) {
$('#list').append(data);
$('.id').off('click'); // remove a previously-attached event handler from the element.
}
});
});

Ajax post request is not functioning

I don't understand why my ajax did not returning any value after post. I am displaying count of registered user in a html table and allowing admin to click each of the count to see list of user name.
My html displaying count of registered user :
$sql2 = "SELECT COUNT(*) AS count FROM reg WHERE reg_id = '".$row['reg_id']."'";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
while($row2 = $result2->fetch_assoc()) {
echo '<a class="slot" data-slotid='.$row['reg_id'].' href="">'.$row2['count'].'</a>';
}
}
$sql2 = NULL;
Ajax request :
$('.slot').on('click', function(){
var slotid = $(this).data('slotid');
$.ajax ({
type: 'POST',
url: 'my-domain.com/ajax-request',
data: { slotid : slotid },
success : function(htmlresponse) {
$('#user_list').html(htmlresponse);
console.log(htmlresponse);
}
});
});
My php function from another file to filter database row :
if(isset($_POST['slotid'])){
// Mysql SELECT statement and echo query result
}
If I place a alert(slotid) right after var slotid = $(this).data('slotid'); in the ajax function, it will display the correct value for each of the clicked link. But when I try to echo $_POST['slotid']; at php side, there is not value returned. It seems like the whole page is refreshing.

Php: Display something if First Record is Reached

I have a database where it has 10+ records:
Accid | Firstname | Lastname
1. John Marshall
2. Sherlock Holmes
3. Random Dude
...
I'd display this using echo on php but with AJAX... it first loads up 5 users, and when the user has scrolled at the bottom of the page, it will load another 5 on the list (it adds the Offset's value +=5). Here's my display code:
$sql = "SELECT * FROM users ORDER BY lastname DESC LIMIT 5 OFFSET 5";
$result = mysqli_query($connection,$sql);
While($row=mysqli_fetch_assoc) {
echo $row['lastname']." ".$row['firstname']."<br/>";
}
This list could be very long if I have 100 users let's say.
Whenever the user scrolls at the bottom, another 5 users pops up. Now, if I reached the end of the whole records in the USERS database, I'd like to display something like - "End of User List"
How can I achieve this?
Jquery Code
$.ajax({
type: "GET",
url: "getusers.php",
data: {
'offset': 4
},
success: function(data){
$('#displayusers').append(data);
}
});
I'd like to disagree with #PressingOnAlways answer.
You can just send back a different response from PHP and check it in javascript.
$sql = "SELECT * FROM users ORDER BY lastname DESC LIMIT 5 OFFSET 5";
$result = mysqli_query($connection,$sql);
if(mysqli_num_rows($result) == 0){
die("last");
}
While($row=mysqli_fetch_assoc) {
echo $row['lastname']." ".$row['firstname']."<br/>";
}
Now you can just check it in javascript:
if(response == "last"){
mydiv.append('This is the end');
}
Now, I would like to show you my way of doing things, which (imo) is a lot cleaner:
First, your ajax calls
We're going to make sure our data will be in json format automatically from now on:
$.ajax({
type: 'GET',
url: "getusers.php",
cache: false,
data: {'offset': 4},
dataType: "json"
}).done(function(json){
if(json.hasOwnProperty("last"){
//No more results
//do your thang;
return false;
}
if(getLength(json) < 5){
//Smaller then 5, must have hit the last. Do your thang;
return false;
}
//It came here, so it's all good. Go on
$('#displayusers').append(data);
});
Secondly: Your PHP side
It's never a good plan to echo html over AJAX. It's way more efficient (takes up less servertime + sends smaller amounts of data over the internet highway) than doing it in PHP.
$sql = "SELECT * FROM users ORDER BY lastname DESC LIMIT 5 OFFSET 5";
$result = mysqli_query($connection,$sql);
$lastResponse = array("last" => "last");
if(mysqli_num_rows($result) == 0){
//Always send back json or it'll give you an error
die(json_encode($lastResponse));
}
$return = array();
While($row=mysqli_fetch_assoc) {
$return[] = $row['lastname']." ".$row['firstname'];
}
echo json_encode($return);
Third: A js function to check the arrayLength
//Checks the length of a json object or array
//Returns false if length is 0 or unable to check it
function getLength(obj) {
if (typeof obj == 'undefined') {
return false;
}
var l = 0;
if (typeof obj == 'object') {
l = Object.keys(obj).length;
}
else {
l = obj.length;
}
return (l == 0 ? false : l);
}
The best place to implement this feature would be on the JS client side. Since your PHP script has no way of knowing if it is the end of the list or not, you need to do this on the client. The JS code should check if the results returned from your php script is less than 5, if so, the "End of User List" should be printed.

Categories