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.
Related
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.
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.
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.
I am doing something like this, I am passing a variable to a php script via post with AJAX. It is actually getting inside my php and running my echo, however it is not printing anything out when I print the $_POST array.
function ajaxFunction(data){
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("POST", "process.php", true);
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxRequest.setRequestHeader("Content-length", data.length);
ajaxRequest.setRequestHeader("Connection", "close");
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
//var data = array();
//data = document.forms["order_form3"].getElementsByTagName("input");
}
}
ajaxRequest.send(data);
}
I recommend to use a plugin like firebug or even the built in functionalities of Chrome or Firefox to see what has been sent and what has been received in your post request.
The ajax response is not printed somewhere on your screen as you might know it from "normal" http POST requests to a php page. It will be returned as part of your ajaxRequest object and you can fetch it from there to use Javascript to "print" it.
Seems you need to encode your parameters, calling your function does submit your data, however they are unbound to a variable on the other end. I'm not surprised PHP throws your data away.
See here: AJAX XMLHttpRequest POST
i have an application in javascript. I follow some tutorial to do it, but i really don't have experience with the javascript code. The problem is that i need to pass the variables results from javascript to mysql database. I have found some answers in this site and i try to do what i found with no luck. What i found is that i need ajax and php. I never use ajax and because of that i dont understand what i'm doing wrong.
Maybe if i put the code here, someone can help me with a solution.
This is the javascript code:
function ajaxFunction(){
var ajaxRequest;
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.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.myForm.time.value = ajaxRequest.responseText;
}
}
ds = new Date();
e_time = ds.getTime();
var res = new Object();//This are the results variables that i need to pass to my database
res.bytes_transfered =;
res.total_time_seconds = (e_time-s_time)/1000;
res.generatied_in = ;
res.ip = "";
-->
var res1= 'res.bytes_transfered';
var res2= 'res.total_time_seconds';
var res3= 'res.generatied_in';
var res4= 'res.ip';
$.post('insert.php',{res.bytes_transfered:res1,res.total_time_seconds: res2, res.generatied_in: res3, res.ip:res4});
var queryString = "?res.bytes_transfered=" + res.bytes_transfered + "&res.total_time_seconds=" + res.total_time_seconds + "&res.generatied_in =" + res.generatied_in + "&res.ip =" + res.ip;
ajaxRequest.open("POST", "insert.php" + queryString, true);
ajaxRequest.send(null);
new Ajax.Request('insert.php', {
onSuccess : function(xmlHTTP) {
eval(mlHTTP.responseText);
}
});
This is the insert.php:
$fecha= date("Y-m-d H:i:s");
$connnect= mysql_connect("localhost", "root", "xxxxxxxxx");
mysql_select_db("dbname");
$res1= mysql_real_escape_string($_POST['res1']);
$res2= mysql_real_escape_string($_POST['res2']);
$res3= mysql_real_escape_string($_POST['res3']);
$res4= mysql_real_escape_string($_POST['res4']);
$queryreg=mysql_query("INSERT INTO grafico(Cantidad, Tiempo, IP, Bajada, Subida, Fecha) VALUES ('$res1','$res2','$res3','$res4','0','$fecha') ");
if (!$queryreg) {
die('No se ha podido ingresar su registro.');
}
else{
die("Usted se ha registrado exitosamente!");
}
I hope that somebody can help me. I dont know what to do!
It looks like your POST data has the keys and values backwards. In the data passed to $.post the key name needs to come first and the value after the :. So I think it should be:
$.post('insert.php',{res1:res.bytes_transfered,res2:res.total_time_seconds,res3:res.generatied_in, res4: res.ip});
What you need to do is have JavaScript pass your variables to PHP, which in turn will use it in your MySQL statements (most probably via PDO in PHP).
Now, what is AJAX then? Well it is the modern way that will help you send data from JavaScript to PHP and get a response back from PHP to JavaScript WITHOUT the need to refresh or reload the page.
So in conclusion, JavaScript makes an AJAX call, that call will send data to PHP which will do something with MySQL, and then respond back to JavaScript with your results.
You need to comment out a couple of lines so that it won't be interpreted as code
//Opera 8.0+, Firefox, Safari
Your Ajax code only creates the ajax object and sets up an event listener, it never actually makes a request, so of course it cannot work. The request would look something like this
ajaxRequest.open("post", "/myphppage.php", true);
...
ajaxRequest.send("somevariable=" + variable);