$.post never receives a response - javascript

I'm a fairly inexperienced coder, and am seeking help on why I'm not receiving a response to my $.post command.
From the output, (i think) the post is correctly submitting the PHP page, and the PHP correctly creates a JSON file with the values I expect. The issue is that my callback never seems to fire.
I never receive a log message of "Function Response", therefore, I don't think the post is ever entering the callback.
I've read lots and lots, and attempted a bunch of solutions, including some AJAX. But after about 10 hours, I'm stumped. My $.post is based on the this guide: Save JavaScript variables to PHP/MySQL DataBase Securely with Ajax Post
Thanks for any help you can shed on this.
I'm testing the code on a Windows most recent WAMP Server.
index.php (relevant bit)
$('#radarDropdown').change(function () {
currentRadarId = $('#radarDropdown').val();
var radSel = document.getElementById('radarDropdown');
var currentRadarName = radSel.options[radSel.selectedIndex].text;
document.getElementById('radarSelectedLabel').innerHTML = currentRadarId;
document.getElementById('radarSelectedName').innerHTML = currentRadarName;
getBacks(currentRadarName, processResponse);
// getBackground(currentRadarName);
console.log('Start request');
// document.getElementById('returnBackground2').innerHTML = back1;
// get background image filename for this radar.
});
function getBacks(currentRadarId, callbackFn) {
console.log('Enter getBacks');
$.post(
"getBackgrounds.php",
{radarBOMId: currentRadarId},
function(response) {
console.log('function response');
processResponse(response);
},'json');
};
function processResponse(response){
console.log('Entered processResponse');
console.log(response);
var backgroundFile = response.background;
var locationsFile = response.locations;
var roadsFile = response.roads;
var riversFile = response.riverBasins;
var railFile = response.rail;
var rangeFile = response.range;
var topoFile = response.topography;
var catchFile = response.catchments;
var wthrDistrictsFile = response.wthrDistricts;
var waterwaysFile = response.waterways;
document.getElementById('returnBackground2').innerHTML = backgroundFile;
};
});
getBackrounds.php:
<?php
header('Content-type: application/json');
require_once('dbconnect.php');
$typesArray = array(
'background',
'catchments',
'locations',
'rail',
'range',
'riverBasins',
'roads',
'topography',
'waterways',
'wthrDistricts',
);
$idval = mysqli_real_escape_string($connection, $_POST['radarBOMId']);
foreach ($typesArray as $i => $value) {
$sql = 'SELECT backfilename, backtype FROM InUseRadarsBackgroundsView WHERE productidbom ="'. $idval. '" and backtype = "'.$value.'"';
$result = $connection->query($sql);
$response = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$response[$value] = $row["backfilename"];
//console.log('Processed row ' & $i);
}
echo json_encode($response);
} else {
echo " 0 results";
}
}
?>
POST response:
{"background":"IDR503.background.png"}{"catchments":"IDR503.catchments.png"}{"locations":"IDR503.locations.png"}{"rail":"IDR503.rail.png"}{"range":"IDR503.range.png"}{"riverBasins":"IDR503.riverBasins.png"}{"roads":"IDR503.roads.png"}{"topography":"IDR503.topography.png"}{"waterways":"IDR503.waterways.png"}{"wthrDistricts":"IDR503.wthrDistricts.png"}

This is not the complete answer, but try to add other callbacks (e.g. fail callback) to check if some errors occur when you make this POST. Here is an example of how this can be done :
$.post( "example.php", function(data) {
alert( "success" );
})
.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
})
.always(function() {
alert( "finished" );
});

Related

error :[object HTMLParagraphElement], when assignin a variable from a function

i have a function that shows me if a file exists, if so he will return me the file path if it doesnt exist he will still give me the path so he can create the file:
function getnamechats($user1,$user2){
$filename1="chats/chat".$user1."&".$user2.".json";
$filename2="chats/chat".$user2."&".$user1.".json";
if (file_exists($filename1)) {
return $filename1;
}
else if (file_exists($filename2)) {
return $filename2;
}
else{ return $filename1;}
}
it works fine on creating/opening the file to write on it,ive tested a lot of times and my json file gets updated everytime:
function send_chat($nick,$chat){
global $userid;global $chatparse;
$heasda=getnamechats($userid,$chatparse);
$ok=$heasda;
// read/write
$filename = "$heasda";
$fopen = fopen($filename,"r");
$fgets = fgets($fopen);
fclose($fopen);
$decode = json_decode($fgets,true);
// limit 10
end($decode);
if(key($decode) >= 10){
array_shift($decode);
$new_key =10;
}
else{
$new_key = key($decode);
$new_key++;}
$format = array($nick,$chat);
$decode[$new_key] = $format;
$encode = json_encode($decode);
// write
$fopen_w = fopen($filename,"w");
fwrite($fopen_w,$encode);
fclose($fopen_w);
}
but in the function that opens/create it to read i get the following error the first variable is right(1) but the second one (suppost to be after the &) just doesnt work, and the error HTMLParagraphElement appears,example:
chats/chat1&[object HTMLParagraphElement].json
i then called again the getnamechats() function as soon as a new msg is triggered just to check if the file still exists, if it does, it will send me the variable $heasda to show_chat($heasda) and basically it will do the same as send_chat, but instead writing on it, it will read it:
function show_chat($heasda){
print_r($heasda);
$filename = $heasda;
$fopen = fopen($filename,"r");
$fgets = fgets($fopen);
fclose($fopen);
$decode = json_decode($fgets,true);
$val .= "<table id='table' class=\"table table-condensed\">";
foreach($decode as $post){
$val .= "<tr><td><b style=\"color:#{$post[0]}\">{$post[0]}</b>: {$post[1]}</td></tr>";}
$val .= "</table>";
return $val;
}
if(isset($_POST["chat"]) && $_POST["chat"] != ""){
$nick = $_SESSION['iduser'];
$chat = $_POST["chat"];
send_chat($nick,$chat);
}
if(isset($_GET["chat"]) && $_GET["chat"] != ""){
global $userid;global $chatparse;
$heasda=getnamechats($userid,$chatparse);
echo show_chat($heasda);
exit;
}
?>
As someone said it can be JavaScript heres the code too, ive read about it but i still dont understand properly:
function autoloadpage() {
$.ajax({
url: "?chat=1&chat-pars="+secnum,
type: "POST",
success: function(data) {
$("div#chat").html(data);
}
});
}
secnum is a DOM element, not the text inside it. You need to get the text.
You should also call encodeURIComponent in case it contains characters that have special meaning in a URL.
function autoloadpage() {
$.ajax({
url: "?chat=1&chat-pars="+encodeURIComponent(secnum.innerText),
type: "POST",
success: function(data) {
$("div#chat").html(data);
}
});
}

How to retrieve a php form with AJAX at specific time spans

I want to display a form with a script I adapted from this question. The script is in a file I wrote called queries.js, and its purpose is to print the content of a php form called "dbMinAlert.php" in a div like this <div id="recentExits" name="recentExits"></div> located in my project's index, I tried invoking getNewData(); in my index.php file using this tag <body onLoad="getNewData()"> but it doesn't seem to do anything at all.
var data_array = ''; // this is a global variable
function getNewData() {
$.ajax({
url: "dbMinAlert.php",
})
.done(function(res) {
data_array = res; // the global variable is updated here and accessible elsewhere
getNewDataSuccess();
})
.fail(function() {
// handle errors here
})
.always(function() {
// we've completed the call and updated the global variable, so set a timeout to make the call again
setTimeout(getNewData, 2000);
});
}
function getNewDataSuccess() {
//console.log(data_array);
document.getElementById("recentExits").innerHTML=data_array;
}
getNewData();`
---This php code works and it actually does what I expect it to do. The real problem is the javascript, for all I care the next php form could print a "Hello world" message, but I want it displayed inside the div I placed in my index, without having to post a thing to dbMinAlert.php.
define("HOST", "localhost");
define("DBUSER", "root");
define("PASS", "password");
define("DB", "mydb");
// Database Error - User Message
define("DB_MSG_ERROR", 'Could not connect!<br />Please contact the site\'s administrator.');
$conn = mysql_connect(HOST, DBUSER, PASS) or die(DB_MSG_ERROR);
$db = mysql_select_db(DB) or die(DB_MSG_ERROR);
$query = mysql_query("
SELECT *
FROM outputs, products
WHERE products.idProduct=outputs.idProduct
ORDER BY Date DESC, Time DESC limit 5
");
echo '<ul class="news">';
while ($data = mysql_fetch_array($query)) {
$date = date_create($data['Date']);
$time = date_create($data['Time']);
echo '<li><figure><strong>'.date_format($date,'d').'</strong>'.date_format($date,'M').date_format($date,'Y').'</figure>'.$data["idProduct"]." ".$data['prodName'].'</li>';
}
echo '</ul>';
You have to execute the function for the first time.
getNewData();
It could be the way you are returning the result from php. Instead of doing multiple echo, could you first assign your result in single php variable and finally do single echo.
$result = '<ul class="news">';
while ($data = mysql_fetch_array($query)) {
$date = date_create($data['Date']);
$time = date_create($data['Time']);
$result = $result + '<li><figure><strong>'.date_format($date,'d').'</strong>'.date_format($date,'M').date_format($date,'Y').'</figure>'.$data["idProduct"]." ".$data['prodName'].'</li>';}
$result = $result + '</ul>';
echo $result;
I found a solution in this question and my code ended up Like this.
I just had to invoke the function in my index by typing <body onload="return getOutput();">
JavaScript
//Min-Max Alerts
// handles the click event for link 1, sends the query
function getOutput() {
getRequest(
'dbMinAlert.php', // URL for the PHP file
drawOutput, // handle successful request
drawError // handle error
);
return false;
}
// handles drawing an error message
function drawError() {
var container = document.getElementById('recentExits');
container.innerHTML = 'Bummer: there was an error!';
}
// handles the response, adds the html
function drawOutput(responseText) {
var container = document.getElementById('recentExits');
container.innerHTML = responseText;
}
// helper function for cross-browser request object
function getRequest(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req.readyState == 4) {
return req.status === 200 ?
success(req.responseText) : error(req.status);
}
}
req.open("GET", url, true);
req.send(null);
return req;
}

Return value from php to javascript

I writing a registration/login form, I am sending user info via POST to a PHP that is looking in a DB. I would like that the PHP returns an ok or wrong value to the js and I don't now how to do it.
Here my js:
ui.onClick_regsubmit=function()
{
var fname=document.getElementById('fname').value;
var lname=document.getElementById('lname').value;
var password=document.getElementById('password').value;
var mail=document.getElementById('mail').value;
var affiliation=document.getElementById('affiliation').value;
var data = new FormData();
var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new activeXObject("Microsoft.XMLHTTP");
data.append("fname",fname);
data.append("lname",lname);
data.append("password",password);
data.append("mail",mail);
data.append("affiliation",affiliation);
xhr.open( 'post', 'PHP/registration.php', false );
xhr.send(data);
window.alert(affiliation);
}
And the php:
<?php
mysql_connect('localhost','root','') or die('Cannot connect mysql server');
mysql_select_db('ChemAlive_login') or die('cannot connect database');
$lname=$_POST['lname'];
$fname=$_POST['fname'];
$password=$_POST['password'];
$mail=$_POST['mail'];
$affiliation=$_POST['affiliation'];
$q=mysql_query("select * from login where mail='".$mail."' ") or die(mysql_error());
$n=mysql_fetch_row($q);
if($n>0)
{
$q=mysql_query("select password from login where mail='".$mail."' ");
$pp=mysql_fetch_row($q);
if($pp[0]=$password) echo "ok";
else echo "wrong";
}
else
{ $insert=mysql_query("insert into login values('".$fname."','".$lname."','".$mail."','".$password."','".$affiliation."')") or die(mysql_error());}
?>
I would like to return to js this ok or wrong value. How to do it?
xhr.onload=function()
{
if (xhr.status==200)
{
alert(xhr.response);
}else
{
alert("unknown server error");
}
}
it will be better if the server sends a response code, and javascript will transfer this code to the text. For example:
onload=function()
{
switch(xhr.response)
{
case "0":{alert("unknown error")};break;
case "1":{alert("email is already used")};break;
...
}
}
I think thought it is clear
I do not have the rep to comment or I'd ask for details, but if you can consider using ajax, it could look something like this:
php:
$doit = //your query;
if($doit){
$youdid = 'ok';
}
else{
exit('1');
}
js:
$(document).ready(function () {
var foo = $("#formfield")val();
$.ajax({
"foo":foo;
type: 'POST',
url: 'some.php',
success: function(responseText) {
if(responseText == "1") {
alert("Leave instantly");
};
}
else {
alert("One of us");
}
If you want to return either ok or wrong to the JavaScript to handle you could do something like this in your registration.php page:
$q=mysql_query("select password from login where mail='".$mail."' ");
$pp=mysql_fetch_row($q);
if($pp[0]=$password){
header('Content-Type: application/json');
echo json_encode(array('password' => 'ok'));
}else{
header('Content-Type: application/json');
echo json_encode(array('password' => 'wrong'));
}
I have not fully testing this, but the idea is to set the header to return json and then send it a JSON string.
Does that make sense?
Like I said in my comment below I have only used jQuery for AJAX. But here is a little something of what I know about XMLHttpRequest and my undertsanding of how you would test what you get back.
You can set up a listener for when you get a response back onreadystatechange and then put the response in a variable var pass = xhr.response and then just output the text to an alert box like alert(pass.password).
if (xhr.onreadystatechange === 4 && xhr.status === 200){
var pass = xhr.response;
//should output either ok or wrong
alert(pass.password);
}
Read more about XMLHttpRequest here
Let me know if that works.

Delaying browser Ajax output (LongPolling)

I'm trying to complete a connection using Long Polling, where the browser sends a request to the server and to be awaiting a response. To prevent this door is infinitely open, I created a routine that every 10 seconds the server sends an empty response to the browser, stating that there was nothing yet.
It's all working perfectly, had no problems related to that.
My problem is that when the user clicks on a link on the page, the browser waits for the answer call for power upgrade, or can take up to 10-sec. This makes it appear that the tool is slow.
Does anyone have any idea how to solve this?
Image:
Image:
Follows the JavaScript function used to make the call:
function loadJSON() {
if(libera) {
var data_file = http + "bibliotecas/longpolling/notificacoes.php";
var data = {};
data.n = long_n;
data.u = userchat;
data.m = msgchat;
data.c = chatUsuario;
http_request.onreadystatechange = function() {
if(http_request.readyState == 4 && http_request.status == 200) {
try {
var jsonObj = JSON.parse(http_request.responseText);
var qtd = jsonObj.funcao.length;
if(qtd > 0) {
var funcao = "";
for(var key in jsonObj.funcao) {
funcao = jsonObj.funcao[key];
MontarFuncao(eval(funcao),jsonObj.metodo[key]);
}
}
}
catch (e) {
//alert('Erro - '+ http_request.responseText);
}
loadJSON();
}
}
var string = JSON.stringify(data);
http_request.open("POST", data_file, true);
http_request.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
http_request.setRequestHeader("Content-length", string.length);
http_request.setRequestHeader("Connection", "close");
http_request.send(string);
return;
}
}
Follows the PHP function responsible for staying open expecting some changes in the database:
ob_start();
$json = json_decode(file_get_contents(`php://input`));
while($x < 5) {
if(time() >= (15 + $_SERVER['REQUEST_TIME']) || connection_aborted()) {
echo str_pad(NULL,1);
die(json_encode(array()));
flush();
ob_flush();
break;
}
//Query DB
if(count($retorno) > 0) {
flush();
ob_flush();
echo json_encode($retorno);
exit;
}
else {
flush();
sleep(2);
$x++;
}
}

Retrieve from database using PHP and pass to javascript as JSON

I am creating a weather widget using javascript . In this widget the user can select the town they wish to see and the widget will display outlook , min and max temperature without refreshing using ajax . I have stored the city information in a database and had written PHP script to retrieve the data and pass it to js as JSON object
<?php
/**************************
* code to connect to your database here
*/
$con = mysqli_connect("localhost", "user", "pass");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL:".mysqli_connect_error();
}
mysqli_select_db("weather", $con);
$town = $_GET['town'];
/***************************
*
* Query the DB for weather information for the given town.
*
* A PHP array object containing the weather data.
* Return a JSON encoded version of the array to the browser.
*
*/
$sql = "SELECT * from weather where town = $town";
$result = mysqli_query($sql);
while($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
$arr = array(
"town" => $row[town],
"outlook" => $row[outlook],
"min_temp" => $row[min_temp],
"max_temp" => $row[max_temp]
);
}
echo json_encode($arr);
mysqli_close();
?>
And in js i want to show the weather only for selected town . How to parse the JSON object to get only the information of the town selected by the user . Like
if(jsondata == "sydney")
return "sydney information";
I did this using DOJO as
var data;
dojo.xhrGet({
// The URL to request
url: "PHP/weather.php?town=" + ntown,
sync: true,
handleAs: 'json',
// The method that handles the request's successful result
// Handle the response any way you'd like!
load: function(result) {
data = result;
}
});
return data;
}
However , i dont want to use dojo . how do i do that . Any suggestions ?
Suppose you have a select tag with id "town".
<select id="town" onchange="handler(this)"></select>
Now, for the Javascript part. You need to use XMLHttpRequest to make an ajax call.
function handler(elem){
var tname = elem.value;
var request_url = "PHP/weather.php?town=" + tname;
var http_request = new XMLHttpRequest();
try{
// Opera 8.0+, Firefox, Chrome, Safari
http_request = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Some error occured");
return false;
}
}
}
http_request.onreadystatechange = function(){
if (http_request.readyState == 4 )
{
// Javascript function JSON.parse to parse JSON data
var jsonObj = JSON.parse(http_request.responseText);
//Update your page here
}
}
http_request.open("GET", request_url);
http_request.send();
}
<body>
<div id="townInfo">
<div id="town"></div>
<div id="outlook"></div>
<div id="min_temp"></div>
<div id="max_temp"></div>
</div>
<script>
var town = document.getElementById('town');
var outlook = document.getElementById('outlook');
var min_temp = document.getElementById('min_temp');
var max_temp = document.getElementById('max_temp');
var data;
dojo.xhrGet({
// The URL to request
url: "PHP/weather.php?town=" + ntown,
sync: true,
handleAs: 'json',
load: function(result) {
data = result;
town.innerHtml = data['town'];
outlook.innerHtml = data['outlook'];
min_temp.innerHtml = data['min_temp'];
max_temp.innerHtml = data['max_temp'];
}
});
</script>
</body>
warning: not tested

Categories