How to reload a table with ajax after deleting a single row - javascript

I am doing a pagination with random values in my database. Now that my pagination is done, I am working on how to delete a row and, without refreshing the browser, when you click on the X button, I want a confirm() and if it's yet, that row must disappear but my table should still be there.
So this is my script :
<?php
include_once("connectDB.php");
$db = new Connect;
$db = $db->ConnectDB();
$st = $db->prepare("SELECT COUNT(id) FROM users WHERE type='Concessionnaire'");
$st->execute();
$res = $st->fetch(PDO::FETCH_NUM);
$total_rows = $res[0];
$rpp = 5;
$last = ceil($total_rows/$rpp);
if ($last < 1) {
$last = 1;
}
?>
<!DOCTYPE html>
<html>
<head>
<style>
table,td {
padding:5px;
border:1px solid black;
}
table {
width:800px;
}
#pagination_controls {
width:200px;
float:right;
padding-bottom:15px;
}
#container {
width:850px;
margin:auto;
}
</style>
<script>
function request_page(pn) {
var rpp = <?php echo $rpp; ?>;
var last = <?php echo $last; ?>;
var results_box = document.getElementById("results_box");
var pagination_controls = document.getElementById("pagination_controls");
results_box.innerHTML = "Processing...";
var hr = new XMLHttpRequest();
hr.open("POST","pagination_parser.php",true)
hr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
hr.onreadystatechange = function () {
if(hr.readyState == 4 && hr.status == 200) {
var dataArray = hr.responseText.split("||");
var html_output = "<table><tr><th></th><th>ID</th><th>username</th><th>password</th><th>e-mail</th><th>creer par:</th><th></th></tr>";
for(i=0;i<dataArray.length - 1;i++) {
var itemArray = dataArray[i].split("|");
html_output += "<tr><td><input type='submit' onclick=''; value='O'></td><td>"+itemArray[0]+"</td><td>"+itemArray[1]+"</td><td>"+itemArray[2]+"</td><td>"+itemArray[3]+"</td><td>"+itemArray[4]+"</td><td><input type='submit' onclick='javascript:supprimer("+itemArray[0]+");'; value='X'></td></tr>";
}
results_box.innerHTML = html_output;
}
}
hr.send("rpp="+rpp+"&last="+last+"&pn="+pn);
var paginationCtrls = "";
if(last != 1) {
if(pn > 1) {
paginationCtrls += '<button onclick="request_page('+(pn-1)+')"><</button>';
}
paginationCtrls += ' <b> Page '+pn+' of '+last+' ';
if(pn != last) {
paginationCtrls += '<button onclick="request_page('+(pn+1)+')">></button>';
}
}
pagination_controls.innerHTML = paginationCtrls;
}
function supprimer(id) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
if(confirm("Etes-vous sur?")) {
document.getElementById('container').innerHTML = xhr.responseText;
}
}
}
xhr.open("GET","supprimer2.php?id="+id,true);
xhr.send();
}
</script>
</head>
<body>
<div id="container">
<div id="pagination_controls"></div>
<div id="results_box"></div>
</div>
<script>request_page(1);</script>
</body>
</html>
This is my supprimer function php (in my test.php)
public function supprimer($id) {
$st = $this->db->prepare("DELETE FROM `phplogin`.`users` WHERE id='$id'");
$st->execute();
}
And this is where I get stuck :
<?php
$id = $_GET['id'];
include_once('connect.php');
$obj = new User;
$obj->supprimer($id);
echo 'TABLE HERE';
?>
As you can see, with the help of ajax I can do innerHTML of my container div id. But at first, when you go on my page I call that table with a javascript function: request_page(1); So I tried echo 'request_page(1) inside my supprimer2.php but it doesn't work. Blank page. So tell me guys, how can I put back my table??

Define a global variable like;
var page = 1;
and in your request_page function set it like;
function request_page(pn) {
.....
page = pn;
.....
}
and in your supprimer function call request_page function after ajax result,
function supprimer(id) {
...........
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
if(confirm("Etes-vous sur?")) {
document.getElementById('container').innerHTML = xhr.responseText;
request_page(page); // Call to refresh table
}
}
}
xhr.open("GET","supprimer2.php?id="+id,true);
xhr.send();
}

Related

Send text of a LI element in to a text input

Getting the data from mySql is easy, but after getting the list of items, I've been trying to get togheter a function to click on any of the list items to send the text up to the value of the input... Heres what I have after a couple of days of trying.
// AJAX Request to cityes database
function buscarCiudades(str) {
var respuestas = document.getElementById('sugerencias');
if (str.length == 0) {
respuestas.innerHTML = "";
respuestas.setAttribute("style", "display:none;border:none;outline:none;");
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
respuestas.innerHTML = this.responseText;
respuestas.setAttribute("style","display: block;border-top: 1px solid #272C33;border-radius: 0 0 4px 4px;padding: 10px;");
}
};
xmlhttp.open("GET", "/editor/queries/paises.php?ciudad=" + str, true);
xmlhttp.send();
}
}
// my final effort to achive sending the content to a input field
var items = document.querySelectorAll("#sugerencias li");
for(var i = 0; i < items.length; i++ )
{
items[i].onclick = function(){
document.getElementById('campomx').value = this.innerHTML;
};
}
Hense the two html elements in the dynamic process
<input type="search" class="searchBox" name="ciudad" id="campomx" placeholder="Escribe el nombre del destino" onkeyup="buscarCiudades(this.value)" for="sugerencias">
<ul id="sugerencias" class="sugerencias">
</ul>
And this is the query structure:
$ciudad = htmlentities( $_GET['ciudad'], ENT_COMPAT, 'UTF-8' );
$pq = $dcon
->query( "
SELECT *
FROM ciudades
WHERE ciudad LIKE '%$ciudad%'
ORDER BY ciudad
ASC LIMIT 10" );
while ( $pr = $pq->fetch() )
{
echo $ciudadx = '<li>' . $pr['ciudad'] . ', ' . $pr['estado']. ", " . $pr['pais'] . '</li>';
}
Could it be that the function doesn't fire up because it needs to load a pre-existent list? And if so... HOW????
The issue was that the querySelector was loading before the list got populated.
My solution was to put the querySelector inside the onreadystatechange function after the response itself. like so...
// AJAX Request to cityes database
function buscarCiudades(str) {
var respuestas = document.getElementById('sugerencias');
if (str.length == 0) {
respuestas.innerHTML = "";
respuestas.setAttribute("style", "display:none;border:none;outline:none;");
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
respuestas.innerHTML = this.responseText;
respuestas.setAttribute("style","display: block;border-top: 1px solid #272C33;border-radius: 0 0 4px 4px;padding: 10px;");
// newly Included querySelector ------------------
var items = document.querySelectorAll("#sugerencias li");
for(var i = 0; i < items.length; i++ )
{
items[i].onclick = function(){
document.getElementById('campomx').value = this.innerHTML;
};
}
// EO include --------------------------------------
}
};
xmlhttp.open("GET", "/editor/queries/paises.php?ciudad=" + str, true);
xmlhttp.send();
}
}
If this is wrong please feel free to comment.

AJAX function gives void, fread (php) output to html div

This is a PHP function that reads first the title then the content of a txt file that has been uploaded,
<?php
$q = $_REQUEST["q"];
$output = "";
if ($q !== "") {
$bestand = fopen("Blogs.txt", "r");
if (!$bestand) {
echo "Kon geen bestand openen";
}
while (!feof($bestand)) {
$blog = fgets($bestand);
$blog = explode(",", $blog);
$i = 0;
foreach ($blog as $key) {
$i++;
if ($i % 2 == 0) {
$output = $key;
}
elseif (!$i % 2 == 0) {
$Blogname = fopen("Blogs/$key", "r");
$Blogtext = fread($Blogname, filesize("Blogs/$key"));
$output = $Blogtext;
}
}
}
fclose($bestand);
}
?>
but then i wanted to have it show up in html instead of php so i search solution and found AJAX but have been struggling for hours on why it doesn't work
function Getblog() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "Blogreader.php?q=" + str, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var para = document.createElement("div");
var t = document.createElement(this.responseText);
para.appendChild(t);
document.getElementById("BlogDiv").appendChild(para);
}
};
}
This is the Javascript code that gives a void function.
What i want it to do is make a DIV of the output of a the php function
<a> <input type="button" onclick="Getblog()"></a>
<div id="BlogDiv"></div>
And this is the refresh button and the div where they are going to be showed

How to get data from PHP in JSON and AJAX?

Hey guys I am fetching some data with PHP with is listing the folders and Inside the folders I have some images. But I am willing to know how can I get that data in JSON with AJAX to get the name of folders in a DropDown.
This is the code that I am using
JS
<html>
<head>
<script type="text/javascript">
function getXmlHttp(){
var xmlhttp;
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}
function readDir(dirName) {
var req = getXmlHttp();
var list = document.getElementById('subDir');
req.onreadystatechange = function() {
if (req.readyState == 4) {
if(req.status == 200) {
list.innerHTML = req.responseText;
}
}
}
req.open('GET', 'getList.php?data=' + dirName, true);
req.send(null);
list.innerHTML = 'loading...';
}
</script>
</head>
<body onload="readDir('');">
<div id="subDir">
</div>
</body>
</html>
PHP
<?php
$dir = "./data/";
if (strlen($_GET['data']) > 0){$dir = $_GET['data'];}
getList($dir);
function getList($name) {
$path = realpath($name);
$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CATCH_GET_CHILD);
foreach($objects as $name => $object){
if (filetype($name) == "dir") {
print "<br/><a href='javascript:void' onClick='readDir(\"" . $path . "/" . basename($name) . "\")'><b>" . basename($name) . "</b></a>";
} else {
print "<br/><a><b>" . basename($name) . "</b></a>";
}
}
}
?>
Here you can see the code how is working: http://tdhdemo.com/phpfetch/
I'm not sure I get your question right but you can add your list to an array in PHP and display it using json_encode.
When receiving data from the ajax call, use JSON.parse to make it easily readable.
You can also separate files and folders if you want to use them in the future.
<?php
$dir = "./data/";
if (strlen($_GET['data']) > 0){$dir = $_GET['data'];}
echo json_encode(getList($dir));
function getList($name) {
$path = realpath($name);
$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CATCH_GET_CHILD);
$folderContent = array("directories" => array(), "files" => array());
foreach($objects as $name => $object){
if (filetype($name) == "dir") {
array_push($folderContent["directories"], basename($name));
} else {
array_push($folderContent["files"], basename($name));
}
}
return $folderContent;
}
?>
Javascript :
function readDir(dirName) {
var req = getXmlHttp();
var list = document.getElementById('subDir');
req.onreadystatechange = function() {
if (req.readyState == 4) {
if(req.status == 200) {
contentList = JSON.parse(req.responseText);
for(i in contentList["directories"]){
list.innerHTML = list.innerHTML + contentList["directories"][i];
}
}
}
}
req.open('GET', 'getList.php?data=' + dirName, true);
req.send(null);
list.innerHTML = 'loading...';
}

Unable to pass value to php POST via javascript

I am trying to update the text from textbox to database using the onclick event and calling a javascript function.
This is the javascript code
function send_post()
{
var hr = new XMLHttpRequest();
var url ="send_post.php";
var fn = document.getElementById("post").value;
var vars = "post="+fn;
hr.open("POST",url,true);
hr.setRequestHeader("Content-type","application/x-www-form-urlencode");
hr.onreadystatechange = function() {
if (hr.readyState == 4 && hr.status ==200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
hr.send(vars);
document.getElementById("status").innerHTML = fn;
}
This is the php file code
<?php include 'inc/connect.inc.php';
$post =#$_POST['post'];
if ($post != "") {
$date_added = date("Y-m-d");
$added_by = "test123";
$user_posted_to = "test123";
$sqlCommand = "INSERT INTO posts VALUES('','$post','$date_added','$added_by','$user_posted_to')";
$query = mysql_query($sqlCommand) or die (mysql_error());
}
else{
echo "Write something to post.";
}
?>
But I get this error from the php :
Undefined index: post on line 3
The MIME type you are trying to use is application/x-www-form-urlencoded (with a d on the end).
PHP doesn't know how to parse data encoded as application/x-www-form-urlencode (without the d) so it doesn't populate $_POST for your code.
Javascript part:
<script>
function getXMLObject(){
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP")
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP")
}
catch (e2) {
xmlHttp = false
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest();
}
return xmlHttp;
}
var xmlhttp = new getXMLObject();
function send_post() {
if(xmlhttp) {
var post = document.getElementById("post").value;
xmlhttp.open("POST","send_post.php",true);
xmlhttp.onreadystatechange = resultPost;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("post=" + post);
}
}
function resultPost() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
}
</script>
PHP part:
<?php
include 'inc/connect.inc.php';
if(isset($_POST['post']) && trim($_POST['post']) != '') $post = mysql_real_escape_string(trim($_POST['post']));
else $post = '';
if ($post != '') {
$date_added = date("Y-m-d");
$added_by = "test123";
$user_posted_to = "test123";
$sqlCommand = "INSERT INTO posts VALUES('','$post','$date_added','$added_by','$user_posted_to')";
$query = mysql_query($sqlCommand);
if(mysql_affected_rows($link) == 1){
echo 'Operation successfully executed';
exit;
}
}
echo 'Write something to post.';
?>

Submit the form when on browser reload/add new tab

Just got some codes from worldofwebcraft.com for my project examination system.I only know PHP,and I actually have no idea on javascripts because our teacher hasnt taught us yet. Please help me on how do I submit the form automatically when the user reloads the page or when he/she opens a new tab.
heres the codes:
<?php if(isset($_GET['question'])){
$question = preg_replace('/[^0-9]/', "", $_GET['question']);
$next = $question + 1;
$prev = $question - 1; ?>
<script type="text/javascript">
function countDown(secs,elem) {
var element = document.getElementById(elem);
element.innerHTML = "You have "+secs+" seconds remaining.";
if(secs < 1) {
var xhr = new XMLHttpRequest();
var url = "userAnswers.php";
var vars = "radio=0"+"&qid="+<?php echo $question; ?>;
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert("You did not answer the question in the allotted time. It will be marked as incorrect.");
clearTimeout(timer);
}
}
xhr.send(vars);
document.getElementById('counter_status').innerHTML = "";
document.getElementById('btnSpan').innerHTML = '<h2>Times Up!</h2>';
document.getElementById('btnSpan').innerHTML += 'Click here now';
}
secs--;
var timer = setTimeout('countDown('+secs+',"'+elem+'")',1000);
}
</script>
<script>
function getQuestion(){
var hr = new XMLHttpRequest();
hr.onreadystatechange = function(){
if (hr.readyState==4 && hr.status==200){
var response = hr.responseText.split("|");
if(response[0] == "finished"){
document.getElementById('status').innerHTML = response[1];
}
var nums = hr.responseText.split(",");
document.getElementById('question').innerHTML = nums[0];
document.getElementById('answers').innerHTML = nums[1];
document.getElementById('answers').innerHTML += nums[2];
}
}
hr.open("GET", "questions.php?question=" + <?php echo $question; ?>, true);
hr.send();
}
function x() {
var rads = document.getElementsByName("rads");
for ( var i = 0; i < rads.length; i++ ) {
if ( rads[i].checked ){
var val = rads[i].value;
return val;
}
}
}
function post_answer(){
var p = new XMLHttpRequest();
var id = document.getElementById('qid').value;
var url = "userAnswers.php";
var vars = "qid="+id+"&radio="+x();
p.open("POST", url, true);
p.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
p.onreadystatechange = function() {
if(p.readyState == 4 && p.status == 200) {
document.getElementById("status").innerHTML = '';
alert("Your answer was submitted.");
var url = 'exam.php?question=<?php echo $next; ?>';
window.location = url;
}
}
p.send(vars);
document.getElementById("status").innerHTML = "processing...";
}
</script>
<script>
window.oncontextmenu = function(){
return false;
}
document.onkeydown = function() {
if(event.keyCode == 116) {
event.returnValue = false;
event.keyCode = 0;
return false;
}
}
</script>
I would do something like :
window.onbeforeunload = function() {
post_answer();
}
If post_answer() is your "submit the form"-handler. Cannot tell exactly from the code.

Categories

Resources