AJAX without jQuery is not sending POST data to PHP file - javascript

I've been trying to get an ajax alert layer to work with a POST method for several days and I can't come up with a reason for it not working. I use the same basic code to send form data through ajax with POST on other admin pages without trouble but when I try to send data that does not come from a form nothing gets to the server in $_POST.
Here's the flow of the code...
I use variables on a page like these:
$alertLayer = 1;
$autoCloseAlertLayer = 1;
$addAlertLayerCloseButton = 1;
$alertLayerMessage = $alertLayerMessage . '<h1>Test</h1><p>3rd test of the alert layer module.</p>';
$redirect = 0;
$redirectTo = 0;
and I include a script that calls a function at the bottom of the page like this:
if ($alertLayer == true)
{
echo "<script type='text/javascript' id='alertLayerScript'>Lib.ajaxAlertFunction('/Modules/AlertLayer', $autoCloseAlertLayer, $addAlertLayerCloseButton, '$alertLayerMessage', $redirect, '$redirectTo');</script>";
}
Here's the script that gets called:
Lib.ajaxAlertFunction = function (senturl, autoClose, closeButton, message, redirect, redirectTo)
{
var ajaxRequest;
try
{
ajaxRequest = new XMLHttpRequest();
}
catch (e)
{
try
{
ajaxRequest = new ActiveXObjext("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
ajaxRequest = new ActiveXObjext("Microsoft.XMLHTTP");
}
catch (e)
{
alert ("Your browser can't handle the truth!");
return false;
}
}
}
if (!senturl)
{
return false;
}
else
{
// var data = "autoClose=" + encodeURIComponent(autoClose) + "&closeButton=" + encodeURIComponent(closeButton) + "&message=" + encodeURIComponent(message) + "&redirect=" + encodeURIComponent(redirect) + "&redirectTo=" + encodeURIComponent(redirectTo);
// var data = encodeURIComponent("autoClose=" + autoClose + "&closeButton=" + closeButton + "&message=" + message + "&redirect=" + redirect + "&redirectTo=" + redirectTo);
var data = "autoClose=" + autoClose + "&closeButton=" + closeButton + "&message=" + message + "&redirect=" + redirect + "&redirectTo=" + redirectTo;
}
ajaxRequest.onreadystatechange = function()
{
if (ajaxRequest.readyState == 4 && ajaxRequest.status == 200)
{
document.getElementById('outerFrame').innerHTML += ajaxRequest.responseText;
newAlertLayer = document.getElementById('alertLayer');
var arr = newAlertLayer.getElementsByTagName('script')
for (var n = 0; n < arr.length; n++)
{
eval(arr[n].innerHTML)
}
}
}
ajaxRequest.open('POST', senturl, true);
ajaxRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
ajaxRequest.send(data);
}
NOTE: I have no problem sending this data with a 'GET' method but then a long message gets cut off. I have also tried to set up the 'data' variable in several different methods that I've searched over the past 3 days with no success.
The code that expects $_POST data goes as follows:
<?php
$ROOT = $_SERVER['DOCUMENT_ROOT'];
?>
<div id="alertLayer">
<link rel="stylesheet" href="<?php $ROOT ?>/Modules/AlertLayer/alertLayer.css">
<script src="/Modules/AlertLayer/alertLayer.js"></script>
<div id="alertBlock">
<?php
foreach ($_POST as $key => $value)
{
echo "<p>" . $key . " = " . $value . "</p>";
}
foreach ($_GET as $key => $value)
{
echo "<p>" . $key . " = " . $value . "</p>";
}
?>
</div>
</div>
What am I missing? What is different from sending form data with POST and sending variables concatenated the same way?
Again, GET is working when I add the data to the url string but not sufficient, POST = no data at all received on the other end of the ajaxRequest but the rest of the request returns exactly what is expected. The $_POST data missing from the server request is currently the only problem that I cannot solve with this code.
It's looking like the request is not being sent properly but I'm unable to determine the reason. Here's a screenshot of what NETWORK tab in chrome:

Problem was a redirection (301) issued by nginx due to a missing slash at the end of the URL. This caused the POST request to be changed to GET.
Technical Details: https://softwareengineering.stackexchange.com/questions/99894/why-doesnt-http-have-post-redirect
Old approach that started the discussion:
Your Problem seems to be the encodeURIComponent() function that you're wrapping around the whole data string. This replaces the & signs with & values. If you debug this in the browsers developer console you'll see that it is not recognized as form data in the request. You should only escape the variables you're filling in.
Btw: This should also be problematic when you use GET.

This is more or less what I tried and it was sending data via POST.
window.onload=function(){
Lib.ajaxAlertFunction( '/test/target.php', 0, 0, 'Fantastic - data is being sent via POST! Amazeballs!', 0, 0 );
};
var Lib={}; /* Because I don't have the rest of `Lib` at my disposal */
Lib.ajaxAlertFunction = function ( senturl, autoClose, closeButton, message, redirect, redirectTo ) {
var ajax;/* renamed only for brevity */
try {
ajax = new XMLHttpRequest();
} catch (e) {
try {
ajax = new ActiveXObjext("Msxml2.XMLHTTP");
} catch (e) {
try {
ajax = new ActiveXObjext("Microsoft.XMLHTTP");
} catch (e) {
alert ("Your browser can't handle the truth!");
return false;
}
}
}
if ( !senturl ) return false;
else {
var data = "autoClose=" + autoClose + "&closeButton=" + closeButton + "&message=" + message + "&redirect=" + redirect + "&redirectTo=" + redirectTo;
}
ajax.onreadystatechange = function() {
if( ajax.readyState == 4 && ajax.status == 200 ) {
/*
document.getElementById('outerFrame').innerHTML += ajax.responseText;
newAlertLayer = document.getElementById('alertLayer');
var arr = newAlertLayer.getElementsByTagName('script')
for ( var n = 0; n < arr.length; n++ ) {
eval( arr[n].innerHTML );
}
*/
console.log( ajax.responseText );
}
}
ajax.open( 'POST', senturl, true );
ajax.setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded' );
ajax.send( data );
}
For the sake of the test, /test/target.php was simply:
<?php
exit( print_r($_POST,true) );
?>
and the response:
Array
(
[autoClose] => 0
[closeButton] => 0
[message] => Fantastic - data is being sent via POST! Amazeballs!
[redirect] => 0
[redirectTo] => 0
)
If it helps any, here is a basic ajax function I use in tests, perhaps something in there might be of use?
function _ajax( url, options ){
var factories=[
function() { return new XMLHttpRequest(); },
function() { return new ActiveXObject('Msxml2.XMLHTTP'); },
function() { return new ActiveXObject('MSXML2.XMLHTTP.3.0'); },
function() { return new ActiveXObject('MSXML2.XMLHTTP.4.0'); },
function() { return new ActiveXObject('MSXML2.XMLHTTP.5.0'); },
function() { return new ActiveXObject('MSXML2.XMLHTTP.6.0'); },
function() { return new ActiveXObject('Microsoft.XMLHTTP'); }
];
/* Try each factory until we have a winner */
for( var i=0; i < factories.length; i++ ) {
try { var req = factories[ i ](); if( req!=null ) { break; } }
catch( err ) { continue; }
};
var method=options.hasOwnProperty('method') ? options.method.toUpperCase() : 'POST';
var callback=options.hasOwnProperty('callback') ? options.callback :false;
if( !callback ){
alert( 'No callback function assigned - a callback is required to handle the response data' );
return false;
}
var headers={
'Accept': "text/html, application/xml, application/json, text/javascript, "+"*"+"/"+"*"+"; charset=utf-8",
'Content-type': 'application/x-www-form-urlencoded',
'X-Requested-With': 'XMLHttpRequest'
};
/* The main parameters of the request */
var params=[];
if( options.hasOwnProperty('params') && typeof( options.params )=='object' ){
for( var n in options.params ) params.push( n + '=' + options.params[n] );
}
/* Additional arguments that can be passed to the callback function */
var args=options.hasOwnProperty('args') ? options.args : options;
/* Assign callback to handle response */
req.onreadystatechange=function(){
if( req.readyState==4 ) {
if( req.status==200 ) options.callback.call( this, req.response, args );
else console.warn( 'Error: '+req.status+' status code returned' );
}
}
/* Execute the request according to desired method */
switch( method ){
case 'POST':
req.open( method, url, true );
for( header in headers ) req.setRequestHeader( header, headers[ header ] );
req.send( params.join('&') );
break;
case 'GET':
req.open( method, url+'?'+params.join('&'), true );
for( header in headers ) req.setRequestHeader( header, headers[ header ] );
req.send( null );
break;
}
}
/* to use */
_ajax.call( this, '/test/target.php',{ callback:console.info, method:'post',params:{'field':'value','field2':'value2'} } );

When calling the ajaxRequest the url MUST have a "/" at the end of the url (if you're not specifying an /index.php file for example).
I was using '/Modules/AlertLayer' and changing to '/Modules/AlertLayer/' has fixed the problem!

Related

Download with post to hide username and password?

I have the code below. I want to use Post() instead of Get() because I don't want to show the username and password in the string. First I get auth and download a cookie with post(). This works fine. But then I download a xml-file with get() and the username and password is visible in the download string. How can I download latest.xml with post()? I don't get any file at all (latest.xml) if I change to post whre I have the comment (Does not work if I change to Post()).
The url is https and not http.
var apiUrl = s.getPropertyValue('apiUrl');
var apiUser = s.getPropertyValue('apiUser');
var apiPass = s.getPropertyValue('apiPass');
var anyOrders = "";
var theHTTP = new HTTP();
theHTTP.resetParameters();
theHTTP.url = apiUrl + "/wsauth?";
theHTTP.addParameter("username", apiUser);
theHTTP.addParameter("password", apiPass);
theHTTP.authScheme = HTTP.BasicAuth;
theHTTP.post(); //Works fine
while( !theHTTP.waitForFinished( 1 ) ) { }
job.log(-1, "Server response: " + theHTTP.getServerResponse().toString("UTF-8"));
if( theHTTP.finishedStatus != HTTP.Ok )
{
job.fail("The request failed: %1", theHTTP.lastError);
return;
}
var theCookie = theHTTP.getHeaderValue( HTTP.SetCookie ).toString( "UTF-8" );
if( theCookie.isEmpty() )
{
job.fail("Invalid cookie response: %1", theHTTP.lastError);
return;
}
s.log(-1, "Cookie: " + theCookie);
//Perform query to get xml file
theHTTP.addHeader( HTTP.Cookie, theCookie );
theHTTP.url = apiUrl + "/order/latest";
theHTTP.localFilePath = job.createPathWithName("latest.xml", false);
job.log(1,theHTTP.localFilePath, false);
theHTTP.get(); //Does not work if I change to Post()
job.log( 4, "Download started", 100 );
while( !theHTTP.waitForFinished( 3 ) ) {
job.log( 5, "Downloading...", theHTTP.progress() );
}
job.log( 6, "Download finished" );
//open file to read if there are any orders
var f = new File(theHTTP.localFilePath);
f.open(File.ReadOnly);
anyOrders = f.read();
f.close();
if( theHTTP.finishedStatus == HTTP.Ok && File.exists(theHTTP.localFilePath)) {
if(anyOrders == "No non-processed order found!") {
job.sendToNull( job.getPath() );
job.log( 1, "No non-processed order found! File deleted!");
} else {
job.log( 1, "Download completed successfully");
job.sendToSingle(theHTTP.localFilePath);
}
}
else {
job.fail("Download failed with the status code %1", theHTTP.statusCode);
job.sendToNull( job.getPath() );
return;
}

Trigger a php script using ajax - how and where to program this?

Good day,
I have a php file (db.php) which contains the following function
function edit_record($id, $value){
if($this->db->query('UPDATE tbl_prototype SET value = ' . $value .' WHERE id_component = '.$id)){
$this->register_changes();
return TRUE;
}
return FALSE;
}
Besides, I have some checkboxes in my html page as follows :
<input id="chk01" type="checkbox" data-onstyle="success" data-toggle="toggle">
<input id="chk02" type="checkbox" data-onstyle="success" data-toggle="toggle">
the html page contains also the following script.
<script>
/* AJAX request to checker */
function check(){
$.ajax({
type: 'POST',
url: 'checker.php',
dataType: 'json',
data: {
counter:$('#message-list').data('counter')
}
}).done(function( response ) {
/* check if with response we got a new update */
if(response.update==true){
var j = response.news;
$('#message-list').html(response.news);
sayHello(j);
}
});
};
//Every 1/2 sec check if there is new update
setInterval(check,500);
</script>
<script>
function sayHello(j){
var json=$.parseJSON(j);
var techname = "";
var techname1 = "";
var c;
var w;
$(json).each(function(i,val){
$.each(val,function(k,v){
if (k=="tech_name")
{
techname = "#" + v;
techname1 = v;
}
else
{
console.log("Mon nom est " + techname + " et ma valeur est " + v);
c=document.getElementById(techname1);
if (c.checked)
{
w = 1;
}
else
{
w = 0;
}
console.log(w);
console.log("techname : " + techname1);
if (v != w)
{
console.log ("Pas identique");
if (v==0)
{
// false
uncheckBox(techname);
}
else
{
// true
checkBox(techname);
}
}
else
{
console.log ("Identique");
}
}
});
});
}
function checkBox(pCtrl)
{
toggleOn(pCtrl);
}
function uncheckBox(pCtrl)
{
toggleOff(pCtrl);
}
</script>
Now for my question: where and how should I specify that I would like to run the function 'edit_record' stored in the 'db.php' file with the two parameters ($id and $value).
Contents of 'checker.php' :
<?php require('common.php');
//get current counter
$data['current'] = (int)$db->check_changes();
//set initial value of update to false
$data['update'] = false;
//check if it's ajax call with POST containing current (for user) counter;
//and check if that counter is diffrent from the one in database
//if(isset($_POST) && !empty($_POST['counter']) && (int)$_POST['counter']!=$data['current']){
if(isset($_POST)){
$data['news'] = $db->get_news2();
$data['update'] = true;
}
//just echo as JSON
echo json_encode($data);
/* End of file checker.php */
Thanks a lot for your valuable inputs. Sorry if the question sounds silly (I'm a newbie in php/ajax/jquery programming).
In modern web apps with rich interface You should go for REST API and create controller which should be in You case in checker.php. Example ( checker.php ):
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
//update code
edit_record($_POST['id'],$_POST['counter]);
}
if ($_SERVER['REQUEST_METHOD'] == 'GET'){
//get code
}
ps. i do not see passing id in ajax, you send only counter, so you should add id like:
...
data: {
id:yourId //here your id
counter:$('#message-list').data('counter')
}
Next thing remove from js:
setInterval(check,500);
and create bind:
$("yourcheckboxselector").on("click",function(e){
check($(this).prop("checked") ) //here you have it was checked or not as boolean
});

AJAX is not correctly sending POST variables

I'm writing a basic application in AJAX that need to send some data over POST to a php page.
The problem I'm getting here is that the php page is not correctly receiving data in the $_POST: if I try to print its content I get an empty array.
Can you help me point out the problem?
// global variables
var sendReq = getXmlHttpRequestObject();
// get the browser dependent XMLHttpRequest object
function getXmlHttpRequestObject() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
}
else if(window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
}
else {
document.getElementById('status').innerHTML =
'Status: Error while creating XmlHttpRequest Object.';
}
}
// send a new message to the server
function sendMessage() {
if ( receiveReq.readyState == 0 || receiveReq.readyState == 4 ) {
sendReq.open("POST", 'chatServer.php', true);
sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
// bind function call when state change
sendReq.onreadystatechange = messageSent;
var param = "message=ciao";
sendReq.send(param);
// reset the content of input
document.getElementById("message").value = "";
}
}
chatServer.php
<?php session_start();
// send headers to prevent caching
header("Expires: Mon, 1 Jul 2000 08:00:00 GMT" );
header("Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . "GMT" );
header("Cache-Control: no-cache, must-revalidate" );
header("Pragma: no-cache" );
// open database
$file_db = new PDO('sqlite:chatdb.sqlite') or die("cannot open database");
if ($file_db) {
print_r($_POST); // this prints an empty array!!!
// check if a message was sent to the server
if (isset($_POST["message"]) && $_POST["message"] != '') {
$message = $_POST["message"];
// do stuff
}
}
?>
EDIT:
Updated function, still not working
function sendMessage() {
if( sendReq ){
/* set the listener now for the response */
sendReq.onreadystatechange=function(){
/* Check for the request Object's status */
if( sendReq.readyState==4 ) {
if( sendReq.status==200 ){
/* Process response here */
clearInterval(timer);
getUnreadMessages();
}
}
};
/* Open & send request, outwith the listener */
sendReq.open( "POST", 'chatServer.php', true );
sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
var param = 'message=ciao';
sendReq.send( param );
document.getElementById("message").value = "";
// relocate to php page for debugging purposes
window.location.replace("chatServer.php");
}
}
Your sendMessage function is not quite right - have a look at this to see if it helps.
In the original the function checked for the status of receiveReq which does not refer to the instantiated XMLHttpRequest Object sendReq - also, the request would never get sent even if it had used sendReq because the open and send call was within the code block that checked the response...
var sendReq = getXmlHttpRequestObject();
function messageSent( response ){
console.info(response);
}
function getXmlHttpRequestObject() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if(window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
} else {
document.getElementById('status').innerHTML = 'Status: Error while creating XmlHttpRequest Object.';
}
}
/*
Set the `param` as a parameter to the function, can reuse it more easily.
*/
function sendMessage( param ) {
if( sendReq ){
/* set the listener now for the response */
sendReq.onreadystatechange=function(){
/* Check for the request Object's status */
if( sendReq.readyState==4 ) {
if( sendReq.status==200 ){
/* Process response here */
messageSent.call( this, sendReq.response );
} else {
/* there was an error */
}
}
};
/* Open & send request, outwith the listener */
sendReq.open( "POST", 'chatServer.php', true );
sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
sendReq.send( param );
document.getElementById("message").value = "";
}
}
/* send some messages */
sendMessage('message=ciao');
sendMessage('message=ajax...sent via POST');
Originally missed the param var declaration so corrected that.
update
chatserver.php (example)
------------------------
<?php
/*
demo_chatserver.php
*/
session_start();
if( $_SERVER['REQUEST_METHOD']=='POST' ){
/*
include your db connection
set your headers
*/
if( isset( $_POST['message'] ) && !empty( $_POST['message'] ) ){
#ob_clean();
/* Create the db conn && test that it is OK */
/* for the purposes of the tests only */
$_POST['date']=date( DATE_COOKIE );
echo json_encode( $_POST, JSON_FORCE_OBJECT );
exit();
}
}
?>
html / php page
---------------
<!doctype html>
<html>
<head>
<title>ajax tests</title>
<script type='text/javascript'>
var sendReq = getXmlHttpRequestObject();
function messageSent( response ){
console.info( 'This is the response from your PHP script: %s',response );
if( document.getElementById("message") ) document.getElementById("message").innerHTML=response;
}
function getXmlHttpRequestObject() {
if ( window.XMLHttpRequest ) {
return new XMLHttpRequest();
} else if( window.ActiveXObject ) {
return new ActiveXObject("Microsoft.XMLHTTP");
} else {
document.getElementById('status').innerHTML = 'Status: Error while creating XmlHttpRequest Object.';
}
}
/*
Set the `param` as a parameter to the function, can reuse it more easily.
*/
function sendMessage( param ) {
if( sendReq ){
/* set the listener now for the response */
sendReq.onreadystatechange=function(){
/* Check for the request Object's status */
if( sendReq.readyState==4 ) {
if( sendReq.status==200 ){
/* Process response here */
messageSent.call( this, sendReq.response );
} else {
/* there was an error */
}
}
};
/* Open & send request, outwith the listener */
/*NOTE: I have this in a folder called `test`, hence the path below!! */
sendReq.open( "POST", '/test/demo_chatserver.php', true );
sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
sendReq.send( param );
if( document.getElementById("message") ) document.getElementById("message").innerHTML = "";
}
}
/* send some data - including original 'message=ciao' but other junk too */
window.onload=function(event){
sendMessage('message=ciao&id=23&banana=yellow&php=fun&method=post&evt='+event);
}
</script>
</head>
<body>
<output id='message' style='display:block;width:80%;float:none;margin:5rem auto;padding:1rem;box-sizing:content-box;border:1px solid black;'>
<!--
Expect to see content appear here....
-->
</output>
</body>
</html>
Should output something like:-
------------------------------
{"message":"ciao","id":"23","banana":"yellow","php":"fun","method":"post","evt":"[object Event]","time":1446730182,"date":"Thursday, 05-Nov-15 13:29:42 GMT"}
Here I will show how I send/receive Ajax requests for basic CRUD (Create, Read, Delete, Update) applications and you can implement it in your code.
First of all simple form with input elements in HTML
<form action="controller.php" method="POST">
<input type="text" class="form-control" name="userName"/>
<input type="text" class="form-control" name="password"/>
<input type="Submit" value="Log In" onclick="logIn(); return false;"/>
</form>
After that we write JavaScript function that uses formData object and with AJax technique sends request:
function logIn()
{
//Creating formData object
var formData = new FormData();
//Getting input elements by their classNames
var formElements = document.getElementsByClassName("form-control");
//Append form elements to formData object
for(var i = 0; i < formElements.length; i++)
formData.append(formElements[i].name, formElements[i].value)
//Creating XMLHttpRequest Object
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
{
alert(xmlHttp.responseText);
}
}
xmlHttp.open("POST", "controller.php");
xmlHttp.send(formData);
}

AJAX not responding correctly

I have made an AJAX code for an on-line food store but when i am running it, it is not showing the correct output i.e. a pop up saying something went wrong always pops up. I want to know what is the problem in my code, is it something to do with the connection handlers or the JS script
Here is my index.php code
<!DOCTYPE html>
<HTML>
<HEAD>
<TITLE>AJAX</TITLE>
<SCRIPT type = "text/javascript" src = "JS/store.js"></SCRIPT>
</HEAD>
<BODY onload = "process()">
<H3>Foodstore</H3>
Enter the food you would like to order:
<INPUT type = "text" id = "user_input" placeholder = "Food Item" />
<DIV id = "output_area" />
</BODY>
</HTML>
Here is my JS code that I am using
var XML_HTTP = create_XML_HTTP_request_object();
function create_XML_HTTP_request_object() {
var XML_HTTP;
if(window.ActiveXObject) {
try {
XML_HTTP = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
XML_HTTP = false;
}
} else {
try {
XML_HTTP = new XMLHttpRequest();
} catch(e) {
XML_HTTP = false;
}
}
if (! XML_HTTP) {
alert('Cant create the object!!');
} else {
return XML_HTTP;
}
}
function process() {
if((XML_HTTP.readyState == 0) || (XML_HTTP.readyState == 4)) {
food = encodeURIComponent(document.getElementById("user_input").value);
url = "process.php?food=" + food;
XML_HTTP.open("GET", url, true);
XML_HTTP.onreadystatechange = handle_server_response;
XML_HTTP.send(null);
} else {
setTimeout('process()', 1000) ;
}
}
function handle_server_response() {
if(XML_HTTP.readyState == 4) {
if(XML_HTTP.status == 200) {
XML_response = XML_HTTP.responseXML;
XML_document_element = XML_response.documentElement;
message = XML_document_element.firstChild.data;
document.getElementById("output_area").innerHTML = '<SPAN style = "color:blue">' + message + '</SPAN>';
} else {
alert('Something went wrong!!');
}
}
}
Here is my PHP code that i am using
<?php
header('Content-Type: text/xml');
echo '<?XML version = "1.0" encoding = "UTF-8" standalone = "yes" ?>';
echo '<response>';
$food = $_GET['food'];
$food_array = array('tuna' , 'bacon' , 'loaf' , 'cheese' , 'pizza') ;
if(in_array($food , $food_array)) {
echo 'We do have ' . $food . ' !!';
} elseif($food == '') {
echo 'Enter a food item';
} else {
echo 'Sorry we don\'t sell ' . $food . ' !!';
}
echo '</response>';
?>
Firefox at least does NOT like the Processing Instruction
<?XML ... ?>
issues error not well-formed ... works fine with
<?xml ... ?>
However, while your code wont work, it WONT result in the alert ... the fact that your getting the alert suggests your browser can't find process.php (it should be in the same folder as your HTML file)
and an added note ... Edge doesn't like upper case HTML tags, it doesn't break, but it has a sook about them
As an alternative to the ajax functions you posted, consider the following:
function _ajax( url, options ){
var factories=[
function() { return new XMLHttpRequest(); },
function() { return new ActiveXObject('Msxml2.XMLHTTP'); },
function() { return new ActiveXObject('MSXML2.XMLHTTP.3.0'); },
function() { return new ActiveXObject('MSXML2.XMLHTTP.4.0'); },
function() { return new ActiveXObject('MSXML2.XMLHTTP.5.0'); },
function() { return new ActiveXObject('MSXML2.XMLHTTP.6.0'); },
function() { return new ActiveXObject('Microsoft.XMLHTTP'); }
];
/* Try each factory until we havea winner */
for( var i=0; i < factories.length; i++ ) {
try { var req = factories[ i ](); if( req!=null ) { break; } }
catch( err ) { continue; }
};
var method=options.hasOwnProperty('method') ? options.method.toUpperCase() : 'POST';
var callback=options.hasOwnProperty('callback') ? options.callback :false;
if( !callback ){
alert( 'No callback function assigned' );
return false;
}
var headers={
'Accept': "text/html, application/xml, application/json, text/javascript, "+"*"+"/"+"*"+"; charset=utf-8",
'Content-type': 'application/x-www-form-urlencoded',
'X-Requested-With': 'XMLHttpRequest'
};
/* The main parameters of the request */
var params=[];
if( options.hasOwnProperty('params') && typeof( options.params )=='object' ){
for( var n in options.params ) params.push( n + '=' + options.params[n] );
}
/* Additional arguments that can be passed to the callback function */
var args=options.hasOwnProperty('args') ? options.args : {};
/* Assign callback to handle response */
req.onreadystatechange=function(){
if( req.readyState ) {
if( req.status==200 ) options.callback.call( this, req.response, args );
else console.warn( 'Error: '+req.status+' status code returned' );
}
}
/* Execute the request according to desired method */
switch( method ){
case 'POST':
req.open( method, url, true );
for( header in headers ) req.setRequestHeader( header, headers[ header ] );
req.send( params.join('&') );
break;
case 'GET':
req.open( method, url+'?'+params.join('&'), true );
for( header in headers ) req.setRequestHeader( header, headers[ header ] );
req.send( null );
break;
}
}
You could then use it like this:
function process(){
call _ajax( this, 'process.php', { 'method':'get', 'callback':handle_server_response, params:{ 'food':food } } );
}
function handle_server_response(response){
try{/* this is not tested! */
var XML_document_element = response.documentElement ;
var message = XML_document_element.firstChild.data ;
document.getElementById("output_area").innerHTML = '<SPAN style = "color:blue">' + message + '</SPAN>' ;
}catch(err){
console.warn('oops, an error occurred: %s',err);
}
}
For future ajax requests you would only have to supply different arguments to the _ajax function rather than rewrite each time. Also, rather than popup a warning message that the user might not understand the errors get logged to the console.
Personally however I'd recommend using JSON rather than XML if there is no specific need to use XML. It's much easier to read and write programatically, requires fewer bytes to transmit and is less prone to anomolies with odd characters.

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++;
}
}

Categories