Refresh page / result after Ajax call - php

So I have a php file printing out result in a table from my database and when i mark a result using checkbox, it sends this variable to a new page deleting it. The problem is, in the same page as he Jquery code is in, all the result is displayed, and I want the result to be updated after something is deleted. Tried using window.location.reload(true); in the Ajax code, but now it only delete one result at the time. Some way to relode the page or refresh the result?
In my sakerselect.php: here it print out all result in my database containg checkbox:
$sql = "SELECT * FROM WHERE Kundenr LIKE '".$_GET['kundenr'] ."'ORDER BY CAST(Status as varchar) DESC ";
$stmt = sqlsrv_query( $conn, $sql);
if( $stmt == false){
die( print_r(sqlsrv_errors(), tue) );
}
echo "<table id='div2' border='1'>";
echo "<tr><th></th><th>Saksnr</th><th>Saksinfo</th><th>Eier</th> <th>Status</th></tr>";
while($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_BOTH))
{
echo "<tr>";
echo "<td><input type='checkbox' name='id[]' class='toedit' value='" . $row[0] . "'></td>";
echo "<td>" . $row[0] . "</td>";
echo "<td>" . $row[1] . "</td>";
echo "<td>" . $row[2] . "</td>";
echo "<td>" . $row[4] . "</td>";
echo "</tr>";
}
sakerselect is included in my KundeDisplay.php page.
KundeDisplay.php is also containing this ajax code sending the marked values to sakerdelete.php:
<script type="text/javascript">
$('#deletesaker').on('click', function () {
var ids = [];
$(".toedit").each(function () {
if ($(this).is(":checked")) {
ids.push($(this).val());
}
});
if (ids.length) {
$.ajax({
type: 'POST',
url: "php/sakdelete.php",
data: {
id: ids
},
success: function (data) {
alert(data);
$("p").text(data);
window.location.reload(true);
}
});
} else {
alert("Please select items.");
}
});
</script>
In my sakdelete.php file:
include 'connect-database.php';
foreach ($_POST['id'] as $id) {
$sql = "DELETE FROM Saker Where Saksnr = $id";
$stmt = sqlsrv_query( $conn, $sql);
if ($stmt == false) {
die( print_r(sqlsrv_errors(), true) );
}
}

you can delete one record at a time by this method
If You want to delete two are more record at a time
try this ....
http://www.codexworld.com/delete-multiple-records-from-mysql-in-php/

Related

Can't get Post value ID from row table to PHP using Jquery

I know that my question may be duplicate, but I've looked through a ton of questions with the same problem, but none of the solutions worked for me.
It's pretty simple, get the item-id value and POST it to del.php.
I can't get the POST value in the php after the click.
<?php
include '../include/db.php';
$result = $mysqli->query("SELECT * FROM usuario WHERE nivel = '1'");
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td class='item-id'>" . $row['id'] . "</td>";
echo "<td>" . $row['nome']. "</td>";
echo "<td>" . $row['email']. "</td>";
echo "</tr>";
}
?>
<script type="text/javascript">
$("tr").click(function() {
var id = $(this).find('.item-id').text();
$.post('del.php',{id: id},function(json){
window.location.href = "http://localhost/unesc/3/admin/del.php";
}, "json")
});
</script>
del.php
<?php
if (isset($_POST['id'])){
$id = $_POST['id'];
echo $id;
} else {
echo "erro";
}
?>
The del.php just get the $_post['id'] and echo it.
The window.location is there so i won't have to enter the address manually.
The trigger may not be necessarily a Click, it can be a Button, woks just fine for me too.
EDIT: got the POST running with $.ajax, but now, with firebug i noticed that the post in del.php keeps returning empty.
EDIT2: got the del.php post response, but as an error, it says that 'id' don't exist.
If THIS is what you need here is the code of both pages I used
del2.php
<script type="text/javascript" language="javascript" src="jquery.min.js"></script>
<?php
//include '../include/db.php';
include 'includeconnect.php';
//$result = $mysqli->query("SELECT * FROM usuario WHERE nivel = '1'");
$result = mysql_query("SELECT * FROM usuario WHERE nivel = '1'");
while($row = mysql_fetch_array($result))
{
echo "
<table border='1'>
<tr>";
echo "<td class='item-id'>" . $row['id'] . "</td>";
echo "<td>" . $row['nome']. "</td>";
echo "<td>" . $row['email']. "</td>";
echo "</tr>
</table>
</br>";
}
echo"<div id='show_responce'>I am a text on page del2.php and I am pretty much useless apart from showing you where the responce will display</div>"
?>
<script type="text/javascript">
$("tr").click(function() {
var rep = $("#show_responce");
var id = $(this).find('.item-id').text();
var dataString = 'id=' + id;
$.ajax({
type: 'post',
url: 'del.php',
data: dataString,
success: function(html) {
rep.empty().append(html);
rep.fadeIn("slow")
}
});
});
</script>
Here is your modified del.php
<?php
if (isset($_POST['id'])){
$id = $_POST['id'];
echo "I am coming from del.php and the ID you clicked on is $id";
} else {
echo "error";
}
?>
By the way because of my account's low reputation I could not ask you what was you trying to do with this window.location but whatever. Instead of what you asked for which was basically to make sure that del.php gets the value of id as you will see I displayed it on del2.php which is the page I am making the request from.
$( "table > td" ).find( ".item-id" ).val();
or
<?php
while($row = mysqli_fetch_array($result))
{
echo "<tr id='row'>";
echo "<td class='item-id'>" . $row['id'] . "</td>";
echo "<td>" . $row['nome']. "</td>";
echo "<td>" . $row['email']. "</td>";
echo "</tr>";
}
?>
<script>
var id = [];
var values = [];
$("#row > .item-id").each(function(index){
id.push($(this).attr("id")); // [a,b,c,....]
values.push($(this).text()); //[ Dummy1, Dummy2, Dummy3, Dummy4,..]
});
</script>
Possible errors:
}, "json") here last argument means, that function expects you return valid JSON string from del.php file.
After window.localtion.href you can't access previous data, because it redirects to another page, and thus you loose all your previous data.

AJAX only responds to the first row of php mysqli data. The other rows doesn't respond and retrieve data.

Basically, this code gets info from id.php by studentid and returns address, document cost, etc The code is returned when the button student id is clicked but only for the first row. The second row does not return any data and i cant seem to figure out the problem. please help.
<div id="briefinfo" style="display:inline-block;text-align:center;margin-left:20px;">
<?php require_once("db.php");
if ($result = $mysqli->query("SELECT * FROM requests WHERE status = 1 ORDER BY id"))
{
if ($result->num_rows > 0)
{
while ($row = $result->fetch_object())
{
echo "<div id='thumbnail'>";
echo " ". $row->lastname;
echo " ". $row->firstname;
echo "</div>";
echo "document id:" . $row->id;
echo "<br>";
echo "requested: " . $row->document;
echo "<br>";
if ($row->paidstatus == 1){
echo "payment status: paid";
}
else{
echo "payment status: not paid";
}
echo "<br>";
echo "<input type='button' value='$row->student_id' id='studentid'/>";
/*echo "<td>" . $row->document . "</td>";
echo "<td><a href='records.php?id=" . $row->id . "'>Edit</a></td>";
echo "<td><a href='delete.php?id=" . $row->id . "'>Delete</a></td>";
echo "<td><a href='unverify.php?id=" . $row->id . "'>unverify</a></td>";
echo "<td><a href='comments.php?id=" . $row->id . "'>comment</a></td>";
echo "<td>" . $row->paymentamount . " pesos";"</td>";
echo "<td><a href='paymentamount.php?id=" . $row->id . "'>set amount</a></td>";*/
}
}
else
{
echo "No results to display!";
}
}
else
{
echo "Error: " . $mysqli->error;
} ?>
</div>
This is the JS
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js'></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
//in your Javascript, put
$(document).ready ( function () {
$("#studentid").click (function(){
var studentid = $(this).val();
$.ajax({
type: 'POST',
url: 'id.php',
data: {
id: studentid
},
success: function(response) {
$("#moredata").html(response);
}
});
});
});
</script>
this id.php
<?php
// connect to the database
include('connect-db.php');
// confirm that the 'id' variable has been set
require_once("db.php");
$id = $_POST['id'];
if ($result = $mysqli->query("SELECT * FROM requests WHERE student_id=$id"))
{
if ($result->num_rows > 0)
{
while ($row = $result->fetch_object())
{
echo $row->paymentamount . " pesos";
echo "<br>";
echo $row->address;
echo "<br>";
echo $row->address2;
echo "<br>";
echo $row->country;
}
}
else
{
echo "No results to display!";
}
}
else
{
echo "Error: " . $mysqli->error;
}
?>
First row of input button shows more data in when clicked the button. Second row does not display anything anymore. help
For following statement in while loop you should use class instead of id. You should not use same ID for multiple element.
echo "<input type='button' value='$row->student_id' class='studentid'/>";
And in your jquery script you should call it this way:
<script>
//in your Javascript, put
$(document).ready ( function () {
$(".studentid").click (function(){
var studentid = $(this).val();
$.ajax({
type: 'POST',
url: 'id.php',
data: {
id: studentid
},
success: function(response) {
$("#moredata").html(response);
}
});
});
});
</script>

Post array from form using xmlhttprequest

I have an php generated table/form with checkboxes like this:
if ($query) {
if (!mysqli_num_rows($query)) {
//Empty storage
echo "There are no items in '$storage'.";
exit();
} else {
//form
echo "<form name='send_parts_form' action='../includes/generatetab.php' method='post'>";
//Table header
echo "
<table>
<tr>
<th>Part</th>
<th>PN</th>
<th>Manufactured</th>
<th>Serial</th>
<th>Site</th>
<th>Date replaced</th>
<th>By user</th>
<th>Faulty</th>
<th>Send</th>
<th>Select</th>
</tr>";
//Retrieved data
while ($row = mysqli_fetch_array($query)) {
echo "<tr>";
echo "<td>" . $row['part_type'] . "</td>";
echo "<td>" . $row['pn'] . "</td>";
echo "<td>" . $row['manufactured'] . "</td>";
echo "<td>" . $row['serial'] . "</td>";
echo "<td>" . $row['site_id'] . "</td>";
echo "<td>" . $row['date'] . "</td>";
echo "<td>" . $row['user'] . "</td>";
echo "<td>" . $row['faulty'] . "</td>";
echo "<td><input type='checkbox' name='send_parts[]' class='checkclass' value=" . $row['id'] . "></td>";
echo "</tr>";};
echo "</table>";
echo "</br>";
echo "</br>";
echo "<input type='button' onclick='sendToZG()' value='Send'/>";
echo "</br>";
echo "<input type='submit' name='submit' value='Generate tab' />";
echo "</form>";
exit();
}
} else {
die("Query failed");
}
User then checks option they want and upon submiting (Generate tab) they get tab delimited text with values they selected.
I now want when they click "Send" to have values posted to another php page and results returned on the same page (under SentList div). I have js like this:
//Browser Support Code
function sendToZG(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200){
var ajaxDisplay = document.getElementById('SentList');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
// Now get the value from page and pass it to server script.
var formData = new FormData( document.getElementsByName("send_parts")[0] );
ajaxRequest.open('POST', "../includes/sendtozg.php", true);
ajaxRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
ajaxRequest.send("send_parts=" + formData);
}
Edited: ajaxRequest.send("send_part=" + formData); to ajaxRequest.send("send_parts=" + formData);
Now it returns:
Invalid argument supplied for foreach() on line 53 (That is where I fetch my data in sendtozg.php).
I'll add sendtozg.php at the end of the post.
If instead of:
<form name='send_parts_form' action='../includes/generatetab.php' method='post'>
I echo:
<form name='send_parts_form' action='../includes/sendtozg.php' method='post'>
Upon submit, script sendtozg.php gets executed fine but on a different page.
So basically what I'm trying to do is to have 2 options for the php generated form:
Generate tab delimited txt file
Execute sendtozg.php and return results on same page
I already have both scripts (generatetab.php and sendtozg.php) and they work fine.
sendtozg.php:
if (!empty($_POST['send_parts'])){
foreach ($_POST['send_parts'] as $send_parts){
$getchecked = mysqli_query($con, "SELECT * FROM $storage WHERE id=$send_parts");
while ($row = mysqli_fetch_array($getchecked)) {
$copypart = mysqli_query($con, "INSERT INTO sent_parts (part_type, pn, manufactured, serial, site_id, date, user, faulty, log)
SELECT part_type, pn, manufactured, serial, site_id, date, user, faulty, log
FROM $storage WHERE id=$send_parts");
// check to see if it copied
$getserial = mysqli_query($con, "SELECT serial FROM $storage WHERE id=$send_parts");
$getserial_row = mysqli_fetch_array($getserial, MYSQLI_NUM);
$foundserial = $getserial_row[0];
$checkcopy = mysqli_query($con, "SELECT id FROM sent_parts WHERE serial = '$foundserial'");
// add user info and date
$addinfo = mysqli_query($con, "UPDATE sent_parts SET sent2zg='$user', date2zg='$strdate' WHERE serial = '$foundserial'");
if (!$check1_res) {
printf("Error: %s\n", mysqli_error($con));
exit();
};
//delete from storage
if($checkcopy > 0) {
$getpart = mysqli_query($con, "SELECT part_type FROM sent_parts WHERE serial='$foundserial'");
$getpart_row = mysqli_fetch_array($getpart, MYSQLI_NUM);
$deletedpart = $getpart_row[0];
$removepart = mysqli_query($con, "DELETE FROM $storage WHERE id = '$send_parts'");
echo "Part " . $deletedpart . " has been transfered";
} else {
echo "Part " . $row['part_type'] . "was NOT transfered";
};
};
} exit ();
} else {
echo "Nothing was selected, please try again!";
}
Your <form> doesn't have an id attribute on it so you'll either need to add id="send_parts" to the <form> or you'll need to change your code from getElementById to getElementsByName like this:
// Now get the value from page and pass it to server script.
// Serialize the data
var formData = new FormData( document.getElementsByName("send_parts")[0] );
ajaxRequest.open('POST', "../includes/sendtozg.php", true);
ajaxRequest.send(formData);
Then inside sendtozg.php you'll need to change the first two lines to:
if (!empty($_POST)){
foreach ($_POST as $send_parts){
This is the final code for the sendtozg.js:
// Get get the value from page and pass it to server script.
var formData = new FormData( document.getElementsByName("send_parts")[0] );
ajaxRequest.open('POST', "../includes/sendtozg.php", true);
ajaxRequest.setRequestHeader("X-Requested-With", "XMLHttpRequest");
ajaxRequest.send(formData);
}
and sendtozg.php should be:
if (!empty($_POST)){
foreach ($_POST['send_parts'] as $send_parts){
$getchecked = mysqli_query($con, "SELECT * FROM $storage WHERE id=$send_parts");
By the way:
print_r ($some_array)
and
if (!$check1_res) {
printf("Error: %s\n", mysqli_error($con));
exit();
};
Are great tools for troubleshooting.

Refresh mysql div content using ajax

Could somebody please point me in the right direction as regards refreshing a particular div using ajax. I know the basics of php, a little jquery, but Zero ajax. My scoreboard is built using php within a table as follows -
<div class="scoreBoard">
<table>
<?php
include("lib/inc/connect.php");
$sql="SELECT * FROM highScores ORDER BY Score DESC";
$result=mysqli_query($con,$sql);
$i = 1;
while ($row = $result->fetch_assoc())
{
echo "<tr>";
echo "<td>" . $i . "</td>";
echo "<td>" . $row["Name"] . "</td>";
echo "<td>" . $row["Score"] . "</td>";
echo "</tr>";
$i++;
}
mysqli_close($con);
?>
</table>
</div>
At the moment I have a little refresh image that refreshses the page onClick via JS. The idea of an ajax refresh would be much nicer.
save your php code in a file named somename.php then call it with
ajax
in somename.php
<?php
include("lib/inc/connect.php");
$sql="SELECT * FROM highScores ORDER BY Score DESC";
$result=mysqli_query($con,$sql);
$i = 1;
while ($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>" . $i . "</td>";
echo "<td>" . $row["Name"] . "</td>";
echo "<td>" . $row["Score"] . "</td>";
echo "</tr>";
$i++;
}
mysqli_close($con);
?>
in your main file
<div class="scoreBoard"></div>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
setInterval( refreshScoreBoard, 5000 );
var inRequest = false;
function refreshScoreBoard() {
if ( inRequest ) {
return false;
}
inRequest = true;
var load = $.get('somename.php');
$(".scoreBoard").html('Refreshing');
load.error(function() {
console.log( "Error" );
// do something here if request failed
});
load.success(function( res ) {
console.log( "Success" );
$(".scoreBoard").html('<table>'+res+'</table>');
});
load.done(function() {
console.log( "Completed" );
inRequest = false;
});
}
</script>
smth. like this in some event triggered function(can be time interval either):
$('.scoreBoard').load('path/to/php_fetching_data_and_building_table');
For more information (like sending post/get) check here:
jQuery - load
ps: you can also use 'ajax' jquery function

Click event for dynamically built table won't fire

I have some jQuery that handles a click event on a table row,which is built with PHP, when it is clicked. It works fine as long as the table is built in the same file. It however will not work if I have jQuery go out to a PHP file, have the PHP build the table, then send the output back to be written in a div tag. I have tried adding .live to the event but that didn't work either? Any suggestions?
The html and jQuery:
<html>
<head>
<script type='text/javascript' src='jquery.js'></script>
<script type='text/javascript'>
var name;
var text;
var subject;
var id;
var key;
$(document).ready(function(){
buildMsgTable();
//Load Message Data in click
$('#messages tr').click(function(){
$(this, 'tr').each(function(index, tr) {
var lines = $('td', tr).map(function(index, td) {
return $(td).text();
});
key = lines[0];
name = lines[1];
textarea = lines[2];
subject = lines[3];
//alert(textarea);
$('#name').val(name);
$('#subject').val(subject);
$('#body').val(textarea);
})
});
function buildMsgTable(){
$.post('/php_webfiles/edit/buildMsgTable.php',
{},
function(output){ $('#existingMessagesDiv').html(output); });
}
</script>
</head>
</body>
<div id='existingMessagesDiv'></div>
<div id = 'debug'></div>
</body>
</html>
And the php called by buildMsgTable:
<?php
include "hawkfunctions.php";
$tsql = "SELECT * FROM Messages";
$conn = mssqlConnect();
$stmt = sqlsrv_query($conn, $tsql);
//$stmt2 = sqlsrv_query($conn, $tsql2);
if ($stmt1 === false) {
echo "Error in query preparation/execution (contacts_in_list).<br/>$tsql1<br/>";
//die( print_r( sqlsrv_errors(), true));
echo "Errors while connecing attempting to run query:<br/><ol>";
$i = 1;
foreach (sqlsrv_errors() as $masterError) {
$errorlist .= "<li>Heading $i<ol>";
foreach ($masterError as $root => $error) {
if (!is_numeric($root)) {
$errorlist .= "<li><b>$root:</b> $error</li>\n";
}
}
$errorlist .= "</ol></li>\n";
$i++;
}
$errorlist .= "</ol>";
die($errorlist);
}
echo "<table border='1' id= 'messages'><th>Key</th><th>Name</th><th>Text</th><th>Subject</th>";
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)){
echo "<tr><td class='key'>";
echo $row['MessageKey'];
echo "</td>";
echo "<td class = 'name'>";
echo $row['Name'];
echo "</td><td class = 'text'>";
echo $row['Text'];
echo "</td><td class = 'subject'>";
echo $row['Subject'];
echo "</td>";
echo "<td class = 'delete'>";
echo "<input type='button' value='Delete' id='delete' onclick='deleteMessage(".$row['MessageKey'].")' />";
echo "</td>";
echo "</tr>";
}
/* Free statement and connection resources.*/
sqlsrv_free_stmt( $stmt);
sqlsrv_close($conn);
echo "</table>";
?>
Think I cut out all the fluff that doesn't pertain to my question.

Categories