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

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

Related

Send php while loop variables to javascript file

My file.js is calling a php file to fetch from database and return an encoded JSON object so I can put it on a table. Here is the file.js -
url = "backend.php"
xmlhttp.open("GET", url, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
myJSONObj = JSON.parse(this.responseText);
for ( i=0;i<myJSON.length;i++)
{
var x = document.getElementById("datatable").rows[i].cells;
x[6].innerHTML =obj[i].age;
}
}
}
And the backend.php file goes -
$sql_stmt= "SELECT * FROM TABLE ";
$result = odbc_exec($conn_id, $sql_stmt);
while ($row = odbc_fetch_array($result)) {
$age=$row['age'];
$ages[] = array('age'=> $age);
}
$myJSON = json_encode($ages);
echo $myJSON;
This works completely fine, but I have to wait for the PHP while loop to finish, which takes too long with large number of entries. I want to be able to return the JSON within the loop, not at the end.
Is there any way I can make the xmlhttp request and keep receiving JSON while the PHP while loop runs, not having to wait for it to finish and then send across all the rows together? Thanks
I think you should use mysql limit
JS:
var hasData = true;
var loop = 0;
while(hasData){
url = "backend.php?page="+loop;
xmlhttp.open("GET", url, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
if(this.reponseText != ""){
myJSONObj = JSON.parse(this.responseText);
for ( i=0;i<myJSON.length;i++)
{
var x = document.getElementById("datatable").rows[i].cells;
x[6].innerHTML =obj[i].age;
}
}else{
hasData = false; //if no data retrieved
}//end if
}//end if
}
loop++; //increment loop
}//end while
PHP:
$loop = $_GET['loop'];
if($loop != ""){
$max_output = 10; //how many rows you want to display per query
$starting_row = $max_output * $loop;
// LIMIT 0, 10 = if loop is 0
// LIMIT 10, 10 = if loop is 1
// LIMIT 20, 10 = if loop is 2
$sql_stmt= "SELECT * FROM TABLE LIMIT {$starting_row}, {$max_output}";
$result = odbc_exec($conn_id, $sql_stmt);
if($result){
while ($row = odbc_fetch_array($result)) {
$age=$row['age'];
$ages[] = array('age'=> $age);
}
$myJSON = json_encode($ages);
echo $myJSON;
}else{
exit; //make sure nothing is echoed/print
}
}
{
myJSONObj = JSON.parse(this.responseText);
for ( i=0;i<myJSON.length;i++)
{
var x = document.getElementById("datatable").rows[i].cells;
x[6].innerHTML =obj[i].age;
}
}
}
Hope this helps

Value not found in php

For login i'm passing mail id and password from javascript file and i've checked through console.log that the values are printed. But when i echo both values in php only password is showed not the mail. But i can't find any error.Here i'm pasting the php file.
<?php
require_once('DBconnection.php');
ini_set('display_errors', 1);
ini_set('log_errors', 1);
$datamail = $_GET["mailID"];
$datapass = $_GET["psw"];
//$datamail = isset($_GET["mailID"]) ? $_GET["mailID"] : '';
echo $datamail;
echo $datapass;
$login_query = "SELECT * FROM student_table where mail_id = '$datamail' AND password='$datapass'";
//echo $login_query;
$login_res = $db->query($login_query);
if( $login_res->num_rows == 1 ){
//if( $login_res == true ){
echo "success";
}
else {
//echo $login_res;
echo mysqli_error($db);
exit;
}
$db->close();
?>
Javascrit file Here
function globalLogin() {
checkLogInMail();
//pageEntry();
}
function checkLogInMail() {
var mailET = document.getElementById("mailID");
var mailIdError = document.getElementById("mailIdErr");
mailID = mailET.value;
var regex = /^(([^<>()\[\]\.,;:\s#\"]+(\.[^<>()\[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()[\]\.,;:\s#\"]+\.)+[^<>()[\]\.,;:\s#\"]{2,})$/i;
if (!regex.test(mailID)) {
mailIdError.innerHTML = "Enter a valid Email id";
//loginFlag = 1;
}
else{
checkmailPass();
}
}
function checkmailPass() {
var passET = document.getElementById("psw");
var passError = document.getElementById("pswErr");
psw = passET.value;
console.log(mailID);
console.log(psw);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
console.log(this.readyState);
if(this.readyState == 4 && this.status == 200)
{
console.log(this.status);
var response = xhttp.responseText;
alert(response);
if(!response.localeCompare( "success" )){
document.getElementById("loginErr").innerHTML = "Mail or Password is correct";
//alert("Successfully logged in :)");
//window.location.href = "index.html";
}
else{
document.getElementById("loginErr").innerHTML = response;
}
}
}
xhttp.open("GET", "passwordChecker.php?psw="+psw+"&mailID"+mailID, true);
xhttp.send();
}
you miss = in your get request in mailID
xhttp.open("GET", "passwordChecker.php?psw="+psw+"&mailID="+mailID, true);
You missed an equal sign '=' in your javascript at your mailid parameter.

Why do I always get undefined response with this ajax post to php?

I am using mouseover event on span element to initiate an ajax post call to php page, but I always get undefined, first for responseText when I used a simple echo to get response and now when I use responseXML. Can somebody please explain me why.
Here is ajax code:
var span = document.getElementsByTagName('span');
for (var i = 0; i < span.length; i++) {
span[i].addEventListener("mouseover", showInformation, false);
}
function showInformation(event) {
var xhr = new XMLHttpRequest();
xhr.open("POST", "../includes/ajax_response.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
content(xhr, event);
}
};
xhr.send("uname=" + event.target.firstChild.textContent);
}
function content(xhr, event) {
var info = document.getElementById('displayInformation');
var xmlResponse = xhr.resopnseXML;
var xmlDocumentElement = xmlResponse.documentElement;
var message = xmlDocumentElement.firstChild.data;
info.innerHTML = message;
info.style.visibility = "visible";
event.target.addEventListener("mouseout", function() {
document.getElementById('displayInformation').style.visibility = "hidden";
}, false);
}
And this is php code:
$username = $_POST['uname'];
$query = "SELECT id, joined FROM users WHERE username = '{$username}' LIMIT 1";
$first_result = Database::getInstance()->query($query);
if ($first_result->num_rows == 1) {
foreach ($first_result as $first) {
$id = $first['id'];
$joined = $first['joined'];
}
}
$first_result->free();
$query = "SELECT COUNT(message) AS count FROM blogs WHERE user_id = '{$id}'";
$results = Database::getInstance()->query($query);
if ($results) {
foreach ($results as $result) {
$number = $result['count'];
}
}
header("Content-Type: text/xml");
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo '<response>';
echo "joined: {$joined}";
echo "number of posts: {$number}";
echo '</response>';
This is version of php with xml, I tired simpler versions with just
$username = $_POST['uname'] and then echo $username, but always response is
undefined.
I read your code once and there does not seem to be any major error. However, I found out this minor bug:
var xmlResponse = xhr.resopnseXML;
spelling of responseXML is incorrect .. maybe that's what's causing the xmlResponse to be undefined?

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

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

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.';
?>

Categories

Resources