Clear previous ajax response data before appending new data - php

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

Related

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.

How to get loop array from php to AJAX

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++) {...}

Format of PHP Array to read from JQuery after Submit form

I need a PHP array that stores data from MySQL and later use in JQuery.
The sample data from MySQL table
student_id class_id score
001 01 A
001 02 B
002 02 A
In JQuery, I would like to access these data as data.student_id[i].class_id[i].score
How can I construct the PHP array?
My current codes in view_student.php (can choose more than one student_id, class_id)
$student_id = $_POST['student_id'];
$class_id= $_POST['class_id'];
$student_array = array();
for($j=0;$j<sizeof($student_id);$j++) {
$query = "SELECT class_id, score FROM student";
$query .= " WHERE student_id='".$student_id[$j]."'";
for($i=0;$i<sizeof($class_id);$i++){
if($i==0) {
$query .= " AND class_id=".$class_id[$i];
} else {
$query .= " OR class_id=".$class_id[$i];
}
}
if($student_sql=$connection->query($query)){
$student_php = array();
$student_row_php = array();
while($student_row_sql=$student_sql->fetch_array(MYSQLI_ASSOC)){
$student_row_php["student_id"]=$sale_row_sql['student_id'];
$student_row_php["score"]=$sale_row_sql['score'];
array_push($student_php, $student_row_php);
}
}
$student_array[$student_id[$j]]=$student_php;
}
echo json_encode($student_array);
In JavaScript, I need data.student_id[0].class_id[0].score instead of data.001[0].score
<script>
$(document).ready(function() {
$('form').submit(function(event) {
event.preventDefault(); /
var postForm = new FormData(this);
$.ajax({
type : 'POST',
url : 'view_student.php',
data : postForm,
processData: false,
contentType: false,
dataType : 'json',
success : function(data) {
$('#score').html('<font color="#FFFFFF"> <strong>'+data.001[0].score+'</strong> </font>');
}
});
});
});
Try to add this so that it resets the key indexing:
$student_array = array_values($student_array); // simple reindex
echo json_encode($student_array);
Since in the end they are already grouped by the students id, $student_id[$j] (contains 001, 002, etc), reset your keys so that you can access them thru your numeric indices, instead of using .001 which is the student id

Make A Next Button For More More Data?

Hi dear friends,
I hope u are all fine.
I want to make a next button for getting more data from mysql database.
For example:
$sql = mysql_query("SELECT * FROM table LIMIT 0,7");
It get 7 rows.For next data code is that.
$sql = mysql_query("SELECT * FROM table LIMIT 7,7");
I can i do that using ajax.
As you can see in many website like facebook,When you click on comment it give a limited
comment and when you click on more comment it give more and so on.In this proccess you can see
that the other content of page does not change.It means it can use ajax and how can I do that in ajax.
Please help me.Thanks.
your ajax would be something like this
var numberOfdata = 0;
$('#button').click(function () {
$.ajax({
url: 'load.php',
data: {
'limit' : numberOfdata,
// other data ...
},
type : 'post',
// other parameters...
}).success(function (data) {
// adding data to your website
numberOfdata += 7;
});
});
and in your server side, you could do something like this
... other operations
mysql_query("SELECT * FROM table LIMIT " . $_POST['limit'] . ",7");
... continuting the work
Note: You should be able to handle SQL injections on your own.
Edit: please note that mysql_query is not recommended.
You have to send the current comments count via Ajax, get the new ones from the response and display them.
Javascript:
$(document).ready(function() {
$('a.pagination-more').click(function() {
var current_comments_count = $(this).data("current_comments_count");
$.ajax({
type: "POST",
url: "pagination/pagination_ajax_more.php",
data: { "limit_start":current_comments_count },
beforeSend: function() {
$('a.pagination-more').html('<img class="loading-gif" src="pagination/loading.gif" />');
},
success: function(html){
$("#more").remove(); // This is the "More" button. It is appended to the end again in the 'html' variable
$("ul#updates").append(html);
if($("a#end")[0]) {
$("div#more").remove();
}
}
});
return false;
});
});
On the PHP side you just get $limit_start, get results from the database and echo the html like:
$limit_start = $_POST['limit_start'];
$query = mysql_query("SELECT COUNT(*) FROM `table` LIMIT 0, $limit_start");
$current_comments_count = mysql_num_rows($query);
$query = mysql_query("SELECT * FROM `table` LIMIT $limit_start, 7");
while($row = mysql_fetch_assoc($query)) {
echo '<li>
blah blah...
</li>';
}
if(mysql_num_rows($query) == 7)
echo '<div id="more"><a data-current_comments_count="$current_comments_count" class="button pagination-more" href="#">More</a></div>';
else
echo '<div id="more"><a id="end" class="button pagination-more" href="#">The button will be removed from jQuery...</a></div>';
Of course it is strongly recommended to secure your application and not to use only mysql_query(). This code is working but I removed some other stuff and didn't test it now. So, some errors may occur.

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