XMLHttpRequest status 4 but responseText is empty - php

I am trying to write a google ads like javaScript plugin. I can not use jQuery ajax as it should be working fine for all sites.
Here is my JavaScript code.
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
alert( ajaxRequest.responseText);
console.log('xhr',ajaxRequest)
} else {
//alert(ajaxRequest.readyState);
//alert(ajaxRequest.responseText);
}
}
var project_path = "http://www.domainname.com/"; //for stackoverflow, using right path in live code.
var req_url = project_path + "ads/verifypublisher/";
ajaxRequest.open("GET", req_url, true);
ajaxRequest.send(null);
And here is how my PHP file looks like,
echo("<b>hi:</b> ");
exit();
Yes, thats all i have there. Still responseText is empty. What am i missing here?

alert(req_url) should show wrong url "http://www.domainname.comads/verifypublisher/"

It's better to make sure the status code is 200 before doing anything with the response. Then you can spot problems earlier.

try this in my test it work in most of browser
var responseText=function(e,doing){
if (e.readyState== 4) {
if(doing)doing(e);
return(e.responseText);
};
if (e.readyState == 200) {
if(doing)doing(e);
return(e.responseText);
};
return false;
};
function loadXMLPostDocf(url,method,posData,uploadProgress,uploadComplete,uploadFailed,uploadCanceled,statechange,CallBackOnSend) {
var arrSignatures = ["MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0","MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP","Microsoft.XMLHTTP"];
// branch for native XMLHttpRequest object
if (window.XMLHttpRequest && checkVersion()) {
pos = new XMLHttpRequest();
pos.open(method, url, true);
//pos.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
if(statechange!=''){pos.onreadystatechange = statechange;};
try{
if(uploadProgress!='')if(pos.upload){
pos.upload.addEventListener("progress", uploadProgress, true);
}else{
pos.addEventListener("progress", uploadProgress, true);
}
if(uploadComplete!='')pos.addEventListener("load", uploadComplete, false);
if(uploadFailed!='')pos.addEventListener("error", uploadFailed, false);
if(uploadCanceled!='')pos.addEventListener("abort", uploadCanceled, false);
}catch(e){
}
pos.send(posData);
if(CallBackOnSend)CallBackOnSend(pos);
//console.log(pos.abort());
// branch for IE/Windows ActiveX version
} else if (window.ActiveXObject) {
for (var i=0; i < arrSignatures.length; i++) {
try {
pos = new ActiveXObject(arrSignatures[i]);
} catch (oError) {
//ignore
};
};
if (pos) {
pos.open(method, url, false);
//pos.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
if(!statechange){pos.onreadystatechange = statechange;};
if(!uploadComplete){pos.onreadystatechange = uploadComplete;};
// if(uploadProgress!='')pos.upload.addEventListener("progress", uploadProgress, true);
//if(uploadComplete!='')pos.addEventListener("load", uploadComplete, false);
//if(uploadFailed!='')pos.addEventListener("error", uploadFailed, false);
//if(uploadCanceled!='')pos.addEventListener("abort", uploadCanceled, false);
pos.send(posData);
if(CallBackOnSend)CallBackOnSend(pos);
};
};
return(pos);
};
sample:
var complete=function(e){
var Body=responseText(e.target);
console.log(Body);
};
var uploadProgress=function(evt){
};
var uploadComplete=function(evt){
if(evt.target.status==200 || evt.target.status==304){
var Body=responseText(evt.target);
console.log(Body);
}else{
return false;
};
};
var uploadFailed=function(evt){
};
var uploadCanceled=function(evt){
};
var CallBackOnSend=function(evt){
};
loadXMLPostDocf("http://domain.com/index.php","GET",null,uploadProgress,uploadComplete,uploadFailed,uploadCanceled,complete,CallBackOnSend);

My problem similar to this was solved by checking my html code. I was having an onclick handler in my form submit button to a method. like this : onclick="sendFalconRequestWithHeaders()". This method in turn calls ajax just like yours, and does what I want. But not as expected, my browser was returning nothing.
Learned From someone's hardwork, I have returned false in this handler, and solved.
Let me mention that before arriving to this post, I have spent a whole 3-day weekend and a half day in office writing code implementing CORS filters, jetty config, other jersey and embedded jetty related stuff - just to fix this., revolving all my understanding around cross domain ajax requests and standards stuff. It was ridiculous how simple mistakes in javascript make you dumb.
Now I have to clean my code to submit git patch cleanly. Thanks to that someone.

Related

How can I make an AJAX call that periodically refreshes a part of the page?

I am working in a chat system that relies on a mysql database.
At the beginning of the first loading of the page sending the following query:
SELECT * FROM `Shoutbox` ORDER BY `Shoutbox`.`ID` ASC LIMIT 0 , 30
and then using a while loop mold all messages (with user names and date) in a div.
while($array=mysql_fetch_array($dati)) {
echo "<div class='tag_li $array[ID]'><span class='when'>$array[DateTime]</span><span class='linea mess'><span id='author'><a onclick='ajaxLoadContent(this)' link='profile.php?name=$array[User]'>$array[User]</a></span>: $array[Message]</span></div>";
}
Now I would like to be sent every second query, and then updates the contents of the div with new messages if any.
How can I send a SQL query in a range?
I will assume you are using javascript and want to make an ajax call.
Start with the timer on the client side
window.setInterval("ajaxFunction()",milliseconds);
And the ajax function
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxDisplay.innerHTML + ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "ajax-example.php" , true);
ajaxRequest.send(null);
}
the php part
while($array=mysql_fetch_array($dati)) {
echo "<div class='tag_li $array[ID]'><span class='when'>$array[DateTime]</span><span class='linea mess'><span id='author'><a onclick='ajaxLoadContent(this)' link='profile.php?name=$array[User]'>$array[User]</a></span>: $array[Message]</span></div>";
}
And the html part
<div id="ajaxDiv"></div>
That should give you an idea how it is done.

no response form ajax and responseText is undefined

I've been trying to get ajax to work the whole day and this my last hope, i wrote a simple test to see if i get any response, the xhr.status is 0 instead of 200, and the xhr.responseText is undefinded. I call a simple (php file) which generates a json object, my code is as follows(i tried using $.ajax but it didnt help either):
$(function(){
$('#checkin').click(function(){
var ajaxRequest;
var connection = ajaxFunction();
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.open("GET", "places.php", true);
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
alert(console.error(ajaxRequest.status));
}
}
ajaxRequest.send(null);
}
});
})
and my php file is as follows:
<?php
header('Content-type: application/json');
require "SQLquery.php";
$places = new SQLquery;
$places->db_query("SELECT * FROM places");
echo json_encode($places->results);
?>
any help will be much appreciated. Thanx
Here is a simple implementation using jQuery's $.ajax() and json.
Javascript:
function sendAjax() {
// The data you want to pass to places.php
var params = {
'checkin' : true
};
// Construct the call
ajax = $.ajax({
url: '/places.php',
type: 'GET',
data: params,
dataType: 'json'
});
// Send it and say which function you'll
// use to handle the response
ajax.done(sendAjaxDone);
}
// Handle the response
function sendAjaxDone(response) {
console.log(response);
}
places.php
header('Content-type: application/json');
require "SQLquery.php";
if ($_GET['checkin']) {
$places = new SQLquery;
$places->db_query("SELECT * FROM places");
echo json_encode($places->results);
}

Json call JSON.parse: unexpected end of data

I've been looking around stackoverflow for the answer to my problem but I can't seem to find why this is happening.
I've created a webserver which returns a JSON object:
http://213.125.101.19/api.php?function=test
After that i created an HTML file with the following javascript to call the JSON using Ajax
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxCall(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var response = ajaxRequest.responseText;
obj = JSON.parse(response);
console.log(obj);
if(response.indexOf("Fatal error")>=0){
alert('Error, Try again.');
}else{
document.getElementById("response").value = response;
}
}
}
ajaxRequest.open("GET", "http://213.125.101.19/api.php?function=test", true);
ajaxRequest.send(null);
}
</script>
When I run this code, my Firebug returns
"SyntaxError: JSON.parse: unexpected end of data
obj = JSON.parse(response);"
If I run my JSON trough a validator, everything seems to be fine.
Any ideas how to fix this?
Kind Regards,
Luuk
JSON looks simple enough. I guess there's something wrong with the call or the return value.
Check status and responseType as well
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
console.log('status=' + ajaxRequest.status +
', statusText=' + ajaxRequest.statusText +
', responseType=' + ajaxRequest.responseType +
', responseText=' + ajaxRequest.responseText);
...
}
The problem for this issue was that my HTML request was being send to my webserver from another pc.
#Olaf Dietsche said it was a good idea to check the ajaxrequest status. This gave a 0 which is not a successfull response.
After copying the html request file to the webserver the problem was solved.
Thanks everybody for helping me out with this.

Adding more parameters in ajax

I am using AJAX function. I am passing 3 variables to the next page using AJAX. When I add the 4th variable the function doesn't get called.
Code:
<script language="javascript" type="text/javascript">
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var count = document.getElementById('count').value;
var type = document.getElementById('type').value;
var sem = document.getElementById('sem').value;
var rid = document.getElementById('room').value;
ajaxRequest.open("GET", "add_requi_ajax.php?count=" + count+"&type="+ type+"&sem="+sem+"&rid="+rid, true);
ajaxRequest.send(null);
};
</script>
Your code is syntactically and logically correct, which means that the problem is likely one of your input IDs is wrong (typo? Should room be rid?), or you call the function before the inputs are rendered on the page (use window.onload).
Verify each of your input IDs. If they all look correct, then comment them out and hard code the values to rule out your inputs as a problem. Watch the error console for any error messages. If an uncaught error is encountered, it can appear that the function isn't being called.
You probably need to urlencode your values.

while retreving the data using ajax getting an error message

I posting my value through ajax and using the response the details will be displayed.I am getting the problem while retreiving the data.But i dono where i have mistaked,then this is the error getiing displayed frequently
"There was a problem while using XMLHTTP:\n";
in all browsers mainly in the chrome,could any one help me...
this is my code,
var xmlHttp;
try {
// Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
} catch (e) {
// Internet Explorer 6+
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
// Internet Eplorer 5
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("Your browser does not support AJAX. Download a newer browser to view this page.");
return false;
}
}
}
// insert server response into HTML element
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
MM_check_session(xmlHttp.responseText);
var b_gc = document.getElementById(insert).value;
document.getElementById(insert).value = xmlHttp.responseText;
var shippingid = getCheckedValue('checkout_form', 'shippingid');
closeMessage();
MM_calc_shipping(shippingid);
if (b_gc == xmlHttp.responseText) {
MM_register();
} else {
error = 1;
document.getElementById('payment_error').innerHTML = xmlHttp.responseText;
document.getElementById(insert).value = '';
}
} else {
closeMessage();
alert("We can't process your request.Please refresh(reload) the page to proceed further:\n"
+ xmlHttp.statusText);
}
}
}
displayStaticMessage(
'<img src=' + config_MM_loader_image_path + ' alt=\'loading...Please wait\'>',
false);
xmlHttp.open("POST", serverScript, true);
xmlHttp.setRequestHeader('Content-type',
'application/x-www-form-urlencoded');
xmlHttp.setRequestHeader('Content-length', parameters.length);
xmlHttp.setRequestHeader('Connection', 'close');
xmlHttp.send(parameters);
any help
You seem to be incorrectly tagged as php. Also have you considered jQuery for the ease of ajax whilst using it.
as for your question could you post the code on the page where the ajax request is going to as the code here looks fine..
Edit:
Where is serverScript set?
change serverScript for the ajax page you are calling?
http://msdn.microsoft.com/en-us/library/windows/desktop/ms757849%28v=vs.85%29.aspx

Categories