AJAX call the PHP script not outputting any results - javascript

I am trying to update my list of tweets via AJAX. I have ran the script on the page and know that script works, and I have a console.log line in my ajax call so I know that is getting hit as well.
setInterval(function () {sendRequest()}, 5000);
function sendRequest(){
var xmlhttp;
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
console.log("yay");
}
}
xmlhttp.open("GET","getTweets.php",true);
xmlhttp.send();
}
My AJAX should run every 5 seconds, and the hit the PHP script to return new results that have been stored in the database. My PHP looks like:
$conn = mysqli_connect("localhost", "*", "*", "*");
if (!$conn) {
echo("Connection failed: " . mysqli_connect_error());
}
$query = "SELECT * FROM tweets;";
$results = mysqli_query($conn, $query);
while($list = mysqli_fetch_assoc($results)){
echo '<div class="tweet-containter">';
echo '<img class="user-img" alt="user-img" src="images/gb.png">';
echo '<h3 class="tweet-username">#'.$list['username'].'</h3>';
echo '<p class="tweet-body">'.$list['tweetBody'].'</p>';
echo '<p class="tweet-body">Tweeted: '.$list['datePosted'].'Retweet: <i class="fa fa-retweet" id="retweet4" onclick="retweetAJAX()"></i> Like: <i class="fa fa-thumbs-up" id="likes4" onclick="likeAJAX()"></i> Dislike: <i class="fa fa-thumbs-down" id="dislikes4" onclick="dislikeAJAX()"></i></p>';
echo '</div>';
}

This goes for those that do not understand ReadyState codes. You should know the following codes for ReadyState:
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
And Status Code
200: "OK"
404: Page not found
with that said, try doing this:
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if(xmlhttp.status == 200){
console.log(xmlhttp.responseText);
} else if(xmlhttp.status == 400) {
alert('There was an error 400')
} else {
alert('something else other than 200')
}
}
}

ryandonohue,
PHP is a Hyper-Text Processor. PHP runs on your server & the results are generated before the page is loaded. You should not be using PHP to output results like HTML elements, it is much more appreciated if you use JavaScript to manipulate the Document Object Model (DOM).
Though, for your intermediate purposes you might not notice an immediate difference.
For PHP5 you should look into the usage of PHP-PDO http://php.net/manual/en/class.pdo.php to prevent SQL injection.
Modification:
function getall($table, $values, $conditions = null, $limit = null, $ascdesc = null){
$values_str = "";
foreach($values as $key => $value){
$values_str .= $value . ", ";
}
$cond_str = "";
$hascond = false;
if($conditions != null){
$hascond = true;
foreach($conditions as $key => $value){
$cond_str .= $key . "='" . $value . "' AND ";
}
$cond_str = rtrim($cond_str, " AND ");
}
$values_str = rtrim($values_str, ", ");
$cond_str = " WHERE (" . $cond_str . ")";
$orderby = "";
$hasorder = false;
if($ascdesc != null){
$hasorder = true;
foreach($ascdesc as $key => $value){
$orderby = " ORDER BY " . $value . " " . $key;
break;
}
}
$sql = "SELECT " . $values_str . " FROM " . $table . " " . (($hascond)? $cond_str: "") . (($hasorder)? $orderby: "") . (($limit)? " LIMIT " . $limit: "");
//echo $sql;
$sql_prep = (new PDO('mysql:host=localhost;dbname=' . 'database', 'username', 'Password'))->prepare($sql);
$sql_prep->execute();
return $result = $sql_prep->fetchAll(PDO::FETCH_ASSOC);
}
initialization: ( returns an array so you need to json encode)
getall('table',
Array(
'*'
),
null, 5, null);
AJAX:
function ajax(file,type, params, func){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//xmlhttp.responseText
func(xmlhttp.responseText);
}
}
if(type.toLowerCase() != "post"){
xmlhttp.open(
type, file + "?" + params_to_get(params),
true
);
xmlhttp.send();
}else{
xmlhttp.open(
type, file,
true
);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(params_to_get(params));
Since you have an error code of readystate of 4 with a status of 500 i would say the issue is more with the compatibility of MYSQLi or the way your table is set up with your database.
check out this POST for more information about headers:
Ajax call to PHP is returning nothing

Related

xmlhttp.status returns 0 in localhost XAMPP

i am a beginner that is doing an app for my school work.
Currently, i am using XAMPP to host my app and phpmyadmin for my database.
The problem i am facing is that the xmlhttp.status is returning 0 instead of 200. I do not have this problem with my previous project where i am using microsoft azure instead of XAMPP.
Here is the code of my script in index.html
var userid;
var password;
function serverURL(){
return "http://localhost/webP/FYP/workshop/platforms/android/assets/www/";
}
function login(){
userid = $("#userid").val();
password = $("#password").val();
if (validate()){
alert("validate pass");
var xmlhttp = new XMLHttpRequest();
var url = serverURL() + "/login.php";
url += "?userid=" + userid + "&password=" + password;
alert(url);
xmlhttp.onreadystatechange=function() {
alert("xmlhttponready running");
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.status);
alert(xmlhttp.readyState);
}
getLoginResult(xmlhttp.responseText);
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
}
Here is my login.php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
error_reporting(E_ERROR);
try{
$conn = new mysqli("127.0.0.1", "root", "root", "bencoolen");
$userid = $_GET["userid"];
$password = $_GET['password'];
$query = "SELECT count(*) as found from profiles where userid ='" .
$userid . "' and password = '" . $password . "'";
$result = $conn->query($query);
$count = $result->fetch_array(MYSQLI_NUM);
$json_out = "[" . json_encode(array("result"=>$count[0])) . "]";
echo $json_out;
$conn->close();
}
catch(Exception $e) {
$json_out = "[".json_encode(array("result"=>0))."]";
echo $json_out;
}
The PHP returns result='0'
I personally feel that the problem could lies in
function serverURL(){
return "http://localhost/webP/FYP/workshop/platforms/android/assets/www/";
}
Please advise :(
Some liitle mistakes:
Your saveUrl function returns "http://localhost/webP/FYP/workshop/platforms/android/assets/www/"
Now when you are trying to concat
var url = serverURL() + "/login.php";
The url becomes
"http://localhost/webP/FYP/workshop/platforms/android/assets/www//login.php"
I excpect you want json response. Then why you are adding? "[".json_encode()."]"
json_encode(array("result"=>0))
Outputs:
{"result":0}
and
getLoginResult(xmlhttp.responseText);
You are keeping out of the if block. This is the main reason you are getting 0 response. For this let me explain little bit about xmlhttp
When a ajax request is triggered, it is completed with 4 states
state value = 0 :=> (state = UNSET): the xmlhttp instance is initiated
state value = 1 :=> (state = OPENED): The browser sends the data to the server
state value = 2 :=> (state = HEADERS_RECEIVED): request reached at server
state value = 3 :=> (state = LOADING): server processing the request
state value = 4 :=> (state = DONE): response reached from server to browser
Now comming to the coding part:
// When ever there is a state chgange in
// the xmlhttp object
xmlhttp.onreadystatechange=function() {
alert(xmlhttp.readyState);
// when the response from server is reached (state = 4)
// and the response header http code is 200 (xmlhttp.status == 200)
// do the following
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.status);
alert(xmlhttp.readyState);
getLoginResult(xmlhttp.responseText);
}
}
But as you have kept getLoginResult(xmlhttp.responseText); out of if block, so it get executed when state is zero (means when the request was not sent to server)
Try this js code:
var userid;
var password;
function serverURL() {
return "http://localhost/webP/FYP/workshop/platforms/android/assets/www/";
}
function login(){
userid = $("#userid").val();
password = $("#password").val();
if (validate()){
alert("validate pass");
var xmlhttp = new XMLHttpRequest();
var url = serverURL() + "login.php";
url += "?userid=" + userid + "&password=" + password;
alert(url);
xmlhttp.onreadystatechange=function() {
alert("xmlhttponready running");
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.status);
alert(xmlhttp.readyState);
getLoginResult(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
}
And your php code:
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
error_reporting(E_ERROR);
try{
$conn = new mysqli("127.0.0.1", "root", "root", "bencoolen");
$userid = $_GET["userid"];
$password = $_GET['password'];
$query = "SELECT count(*) as found from profiles where userid ='" .
$userid . "' and password = '" . $password . "'";
$result = $conn->query($query);
$count = $result->fetch_array(MYSQLI_NUM);
$json_out = json_encode(array("result"=>$count[0]));
echo $json_out;
$conn->close();
}
catch(Exception $e) {
$json_out = json_encode(array("result"=>0));
echo $json_out;
}
?>
Suggestions
As you are using jquery, try to use, jquery.ajax() instaed of XMLHttpRequest (if you are doing it for learning purpose, then its fine). This will fix your browser compatibility issue.
To avoid sql injection, try to use mysqli::prepare. http://php.net/manual/en/mysqli.prepare.php
For more about the XMLHTTPRequest: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState

Query not working through JavaScript with 500 internal server error

I'm new to AJAX and I'm trying to create two dropdownlists of options from a database depending on what the user selects in two previous dropdowns. I've checked every way shape and form I've looked up but one dropdownlist doesn't return any values and the other says internal server error 500.
This is where the onChange event is, triggering the AJAX functions:
<select required="true" id="oficinaLoc" name="oficinaLoc" onchange="getAgent(this.value); selClub(this.value)">
<option value="">Seleccione Unidad</option>
<option value="680 - Centro de Tecnología de Información">680 - Centro de Tecnología de Información</option>
<option value="681 - Educación Agrícola">681 - Educación Agrícola</option>
<option value="682 - Planificación y Evaluación">682 - Planificación y Evaluación</option>
<option value="683 - Medios Educativos e Información">683 - Medios Educativos e Información</option>
<option value="684 - Ciencias de la Familia y el Consumidor">684 - Ciencias de la Familia y el Consumidor</option>
etc...
These are my AJAX functions:
function getAgent(str) {
if (str == "") {
document.getElementById("dispAgente").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("dispAgente").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getagent.php?q="+str,true);
xmlhttp.send();
}
}
function selClub(unidad) {
if (unidad == "") {
document.getElementById("dispNombre").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("dispNombre").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getnombre.php?j="+unidad,true);
xmlhttp.send();
}
}
And these are the PHP pages it calls to through the XMLHttpRequest respectively:
getagent.php
<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
$q = ($_GET['q']);
$con = mysqli_connect('intrasise.uprm.edu','jchristian','registro4h','4h');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"4h");
$sql="SELECT nombre FROM personal4h WHERE unidadProg LIKE '%".$q."%'";
$result = mysqli_query($con,$sql);
echo '<select name="agenteExt"';
while($row = mysqli_fetch_array($result)) {
echo "<option value = " . $row['nombre'] . ">" . $row['nombre'] . "</option>";
}
echo "</select>";
mysqli_close($con);
?>
getnombre.php
<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
$j = ($_GET['j']);
$con = mysqli_connect('intrasise.uprm.edu','jchristian','registro4h','4h');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"4h");
$sql="SELECT nombreClub FROM club4h WHERE oficinaLoc LIKE '%".$j."%'";
$result = mysqli_query($con,$sql);
echo '<select name="nombreClub"';
while($row = mysqli_fetch_array($result)) {
echo "<option value = " . $row['nombreClub'] . ">" . $row['nombreClub'] . "</option>";
}
echo "</select>";
mysqli_close($con);
?>
The getAgent function doesn't return any options in the dropdownlist even though it creates the empty select. The selClub function gives me a 500 internal server error on the xmlhttp.open("GET","getagent.php?q="+str,true); line. I really don't know what else to do, I've followed every online article I've found about this to the dot.
A 500 error is a server error, so that means the problem will be in PHP and I'm seeing alot of issues there. I'm not sure that this is a complete list,...you'll need to debug it yourself, but here's a couple that aren't helping.
$j = ($_GET['j']);
$j = $_GET['j'];
//dump the ()
echo '<select name="nombreClub"';
echo '<select name="nombreClub">';
//closing > is missing
echo "<option value = " . $row['nombre'] . ">" . $row['nombre'] . "</option>";
echo "<option value=\"".$row['nombre']."\">".$row['nombre']."</option>";
//quotes around the value are missing
If you view the errors thrown by the PHP files, then you'll be on your way.
Good luck

HTML, js, ajax form action="", after first send XMLHttpRequest stop working

I'm using a XMLHttpRequest to get data from another server. The JS is executed from the keyup-event from a input-field in my html-document.
After i've sent the formular data one time to the same html-document the XMLHttpRequest stops working.
I used this example:
http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_callback
HTML
<label for="lieferant">Lieferant:</label>
<input name="lieferant" id="eintragen_lieferant" value="' . $lieferant . '" type="text" maxlength="50" onkeyup="eintragen_get_lieferanten(this.value)">
<div id="eintragen_lieferanten"></div>
js
function loadxhtml(url, cfunc)
{
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=cfunc;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
function eintragen_get_lieferanten(value)
{
loadxhtml("functions/eintragen_get_lieferanten.php?suchstring=" + encodeURIComponent(value) + "&lol=" + timestamp, function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("eintragen_lieferanten").innerHTML=xmlhttp.responseText;
}
}
);
}
php
$query = " SELECT * FROM lieferant WHERE name LIKE '%" . $suchstring . "%'";
$result = $con->query($query);
while($row = $result->fetch_assoc())
{
echo "<br>" . $row['name'];
}
?>
Can someone tell my, why the xhtmlrequest stops working after i've sent the data to the same php/html file (aciton="")?
Thanks for any advice.

ReferenceError because of word

I need to write a word in database, and i cant couse i get an error that: ReferenceError: Patikrinta is not defined Here is my ajax script which sends data to php file. Bellow there is php script if you need it. Cant find solution in stackowerflow.
$s .= "\n\t<td>";
$canEdit = getPermission('tasks', 'edit', $a['task_id']);
$canViewLog = getPermission('task_log', 'view', $a['task_id']);
$currentTasken=$a['task_id'];
$currentUser=$AppUI->user_id;
$currentPercent="5";
$currentDescription="Patikrinta";
if ($canEdit) {
$s .= ("\n\t\t".'<a href="#">'
. "\n\t\t\t".'<img src="./images/icons/tick.png" alt="' . $AppUI->_('Check')
. '" border="0" width="12" height="12" onclick="javascript:insertData('. $currentTasken .', '.$currentUser.', '.$currentPercent.', '.$currentDescription.')" />' . "\n\t\t</a>");
}
$s .= "\n\t</td>";
?>
<script type="text/javascript">
// Note that you should use `json_encode` to make sure the data is escaped properly.
var currentTasken = <?php echo json_encode($currentTasken=$a['task_id']); ?>;
var currentUser = <?php echo json_encode($currentUser=$AppUI->user_id); ?>;
function insertData(currentTasken, currentUser, currentPercent, currentDescription)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST","modules/tasks/datafile.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
// Here, use the JS variables but, likewise, make sure they are escaped properly with `encodeURIComponent`
xmlhttp.send("currentUser=" + encodeURIComponent(currentUser) + "&currentTasken=" + encodeURIComponent(currentTasken) + "&currentPercent=" + encodeURIComponent(currentPercent)+ "&currentDescription=" + encodeURIComponent(currentDescription));
}
</script>
Here is my php script:
<?php
$currentUser = isset($_POST['currentUser']) ? $_POST['currentUser'] : '';
$currentTasken = isset($_POST['currentTasken']) ? $_POST['currentTasken'] : '';
$currentPercent = isset($_POST['currentPercent']) ? $_POST['currentPercent'] : '';
$currentDescription = isset($_POST['currentDescription']) ? $_POST['currentDescription'] : '';
$con = mysql_connect("localhost", "root", "") or die(mysql_error());
if(!$con)
die('Could not connectzzz: ' . mysql_error());
mysql_select_db("foxi" , $con) or die ("could not load the database" . mysql_error());
$check = mysql_query("SELECT * FROM dotp_task_log");
$numrows = mysql_num_rows($check);
if($numrows >= 1)
{
//$pass = md5($pass);
$ins = mysql_query("INSERT INTO dotp_task_log (task_log_creator, task_log_Task, task_log_description) VALUES ('$currentUser' , '$currentTasken', '$currentDescription')" ) ;
if($ins)
{
$check = mysql_query("SELECT * FROM dotp_tasks");
$numrows = mysql_num_rows($check);
if($numrows > 1)
{
//$pass = md5($pass);
$inss = mysql_query("UPDATE dotp_tasks SET task_percent_complete = '$currentPercent' WHERE task_id='$currentTasken'") ;
if($inss)
{
die("Succesfully added Percent!");
}
else
{
die("GERROR");
}
}
else
{
die("Log already exists!");
}
}
else
{
die("ERROR");
}
}
else
{
die("Log already exists!");
}
?>
Have you tried adding quotes around the function arguments which are strings? JS is looking for a reference to 'Patikrinta' because you are not adding quotes around the string. It should be a bit more like this:
javascript:insertData('. $currentTasken .', '.$currentUser.', '.$currentPercent.', \''.$currentDescription.'\')" />' . "\n\t\t</a>");
The other arguments work because they are being passed as numbers and Javascript interprets them as such. The difference here is the value of $currentDescription is Patikrinta which is not a number and so JS looks for a variable or object called that.
As a side note - it's worth switching to use MySQLi if you can. MySQL_* functions are deprecated.

I am trying to fetch image from database using ajax in php

here's my code i am trying to fetch image from Data Base using ajax but its not working please hep me out . image uploading working properly when i am trying to fetch image using anchor tag but it show my image on another page . but i want on same page at window load time.
getImage.php
if(filter_has_var(INPUT_GET, "image_id") !== false && filter_input(INPUT_GET, 'image_id', FILTER_VALIDATE_INT) !== false)
{
$image_id = filter_input(INPUT_GET, "image_id", FILTER_SANITIZE_NUMBER_INT);
try {
$dbh = new PDO("mysql:host=localhost;dbname=flipbook", 'root', '');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT image, image_type FROM testblob WHERE user_id=$image_id";
/*** prepare the sql ***/
$stmt = $dbh->prepare($sql);
$stmt->execute();
/*** set the fetch mode to associative array ***/
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$array = $stmt->fetch();
if(sizeof($array) == 2)
{
header("Content-type: ".$array['image_type']);
echo $array['image'];
}
else
{
throw new Exception("Out of bounds Error");
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
catch(Exception $e)
{
echo $e->getMessage();
}
}
else
{
echo 'Please use a real id number';
}
}
index.php
<body onload="showUserProfilePic(<?php echo $_SESSION['current_user_id'];?>)">
<div id="txtHint">Child Picture will be listed here.</div>
<script>
function showUserProfilePic(str) {
//alert(str);
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getImage.php?image_id="+str,true);
xmlhttp.send();
}
}
Try using
$sql = "SELECT image, image_type FROM testblob WHERE user_id='" . $image_id . "';
and where is your tag?

Categories