This particular AJAX call is returning "\n" in front of the value returned by responseText.
It was previously not doing that and now when I test for a valid returned code with if (request.responseText == 100) it fails because it now equals "\n100".
I know I could strip off the "\n", but that would be a workaround and I would prefer to find the cause and fix it.
Here's my client-side code:
function AJAX(){
var xmlHttp;
try{
xmlHttp=new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari
return xmlHttp;
}
catch (e){
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
return xmlHttp;
}
catch (e){
try{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
return xmlHttp;
}
catch (e){
alert("Your browser does not support AJAX!");
return false;
}
}
}
}
function logDetails() {
var request,
Result = document.getElementById('Result'),
message = document.getElementById('message'),
url = 'ajax/login.user.php?',
us = document.getElementById('username').value,
pa = document.getElementById('password').value;
Result.innerHTML = 'Logging in...';
if (document.getElementById) {
request = AJAX();
}
if (request) {
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
var r = request.responseText;
//var r = 100;
if (r == '100') {
Result.innerHTML = 'You are now logged in.';
window.location.href = "prebooks.php";
}
else if (r == '101' || r == '102') {
Result.innerHTML = 'Your login attempt failed.';
resetDetails();
}
else if (r == '103') {
Result.innerHTML = 'Sorry, you have no books subscription.';
}
else if (r == '999') {
Result.innerHTML = 'You have no more attempts!';
message.innerHTML = 'Please call us on (02) XXXXXXX so that we can assist you.';
} else {
alert(r);
}
}
};
}
// add my vars to url
url += "arg1="+us+"&arg2="+pa;
request.open("GET", url, true);
request.send(null);
}
Here's my server-side code:
<?= 100 ?>
Ok, I simplified it, but I've tried just echoing '100' directly and the issue remains.
UPDATE
I was mistaken that echoing '100' directly didn't solve the problem. It does. Sorry about that and thanks for pointing me in the right direction.
However, this does leave me with trying to find how the output is being polluted on the server-side.
On the server-side I have a class which handles the authentication and returns a value (100) to be echoed. This is the line:
echo $L->doLogin($pkg);
The lines relating to the return in the doLogin() method are:
$pkg[status]=100;
return $pkg[status];
And to be sure that a newline isn't leaking in some place, if I replace echo $L->doLogin($pkg); with echo 100; it works.
UPDATE 2 - SOLVED
It turns out that the problem was in an included class file which is included within the doLogin() method, which had recently been updated to include a single line-break at the top of the file, before the opening <?.
Many thanks to everyone for your input (I'd still be fumbling around in client-side code without it)!
I had the same problem and discovered (by adding dataFilter option to Ajax with an alert show the stringified JSON returned) that it was really the PHP script which was having syntax problem. PHP server was then pre-pending an HTML mini-document to signal the error. But then, when back to AJAX, as dataType was 'json', the whole returned PHP response was json parsed first, thus stripping off all the HTML prepended and leaving only newlines. These newlines in front of valid JSON returned data was causing the JSON data to be considered syntax error, and that was it ! With dataFilter option sending the raw data in an alert, I was able to see the PHP script initial error and once corrected, no more newlines pre-pended!
i had the same problem and i understood I hit Inter several times in end of page that i incloude to my page and when i delete it my responseText show without \n. :)
example:
_enter
_enter
_enter
Related
I'm trying to get a page with AJAX, but when I get that page and it includes Javascript code - it doesn't execute it.
Why?
Simple code in my ajax page:
<script type="text/javascript">
alert("Hello");
</script>
...and it doesn't execute it. I'm trying to use Google Maps API and add markers with AJAX, so whenever I add one I execute a AJAX page that gets the new marker, stores it in a database and should add the marker "dynamically" to the map.
But since I can't execute a single javascript function this way, what do I do?
Is my functions that I've defined on the page beforehand protected or private?
** UPDATED WITH AJAX FUNCTION **
function ajaxExecute(id, link, query)
{
if (query != null)
{
query = query.replace("amp;", "");
}
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)
{
if (id != null)
{
document.getElementById(id).innerHTML=xmlhttp.responseText;
}
}
}
if (query == null)
{
xmlhttp.open("GET",link,true);
}
else
{
if (query.substr(0, 1) != "?")
{
xmlhttp.open("GET",link+"?"+query,true);
}
else
{
xmlhttp.open("GET",link+query,true);
}
}
xmlhttp.send();
}
** Solution by Deukalion **
var content = xmlhttp.responseText;
if (id != null)
{
document.getElementById(id).innerHTML=content;
var script = content.match("<script[^>]*>[^<]*</script>");
if (script != null)
{
script = script.toString().replace('<script type="text/javascript">', '');
script = script.replace('</script>', '');
eval(script);
}
}
and on certain events, I had to within the script addevent listeners instead of just making a "select onchange='executeFunctionNotIncludedInAjaxFile();'" I had to addEventListener("change", functionName, false) for this. In the script that is being evaluated.
When you update your page by doing something like setting a container's innerHTML to some updated content, the browser simply will not run the scripts in it. You can locate the <script> tags, get their innerHTML (IE may prefer innerTEXT), and then eval() the scripts yourself (which is pretty much what jQuery does, though it finds the scripts with a regex before updating the DOM).
Use this function:
function parseScript(_source) {
var source = _source;
var scripts = new Array();
// Strip out tags
while(source.indexOf("<script") > -1 || source.indexOf("</script") > -1) {
var s = source.indexOf("<script");
var s_e = source.indexOf(">", s);
var e = source.indexOf("</script", s);
var e_e = source.indexOf(">", e);
// Add to scripts array
scripts.push(source.substring(s_e+1, e));
// Strip from source
source = source.substring(0, s) + source.substring(e_e+1);
}
// Loop through every script collected and eval it
for(var i=0; i<scripts.length; i++) {
try {
eval(scripts[i]);
}
catch(ex) {
// do what you want here when a script fails
}
}
// Return the cleaned source
return source;
}
then do parseScript(xmlhttp.responseText); when you're replacing/adding content.
In case some other people stumble upon this old thread, there is one issue with the accepted answer by Deukalion, there is one issue that may have been overlooked: as written, the script only looks for the first script tag. If multiple script tags exist, all others are overlooked.
A few minor tweaks would resolve the issue. Change one line from:
var script = content.match("<script[^>]*>[^<]*</script>");
To:
var script = content.match(/<script[^>]*>[^<]*<\/script>/g);
And another from:
script = script.toString().replace('<script type="text/javascript">', '');
To:
script = script.join("").replace(/<script type="text\/javascript">/g, '');
Now it will gather all the <script> code and execute them in the order found on the page. Otherwise it was an excellent solution.
After the AJAX request, you can make an "on success" function which can take the returned html and do something with it. Then something will be executed.
If there was a code example, then I could provide a code solution to the situation. But using just standard xmlhttprequest, the following could be done:
xhr = new XMLHttpRequest();
xhr.open("GET","ajax_info.txt",true);
xhr.onreadystatechange=function()
{
if (xhr.readyState==4 && xhr.status==200)
{
document.getElementById("myDiv").innerHTML = xhr.responseText;
}
}
xhr.send();
Good day to all. I have the flowing problem.
I have 2 domains. On one domain I send an ajax post to the other and expect some results. The problem is that the response is always empty. If I inspect the net tab the request looks alright (the post data is fine), it doesn't receive any error, it ends (I put an alert on the handle response function to check what the response is). I tried sending a request to random domains (like example.com) to see if I get anything. The response is the same... none.
Here is the script I use:
function sendReqPost(url) {
http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
// set type accordingly to anticipated content type
//http_request.overrideMimeType('text/xml');
http_request.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
alert('Cannot create XMLHTTP instance');
return false;
}
//http_request.onreadystatechange = handleResponseAccept;
http_request.open('POST', url, true);
http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http_request.setRequestHeader("Content-length", parameters.length);
http_request.setRequestHeader("Connection", "close");
//parameters is a global variable with the post data.
http_request.send(parameters);
}
I double checked everything in the script... I also inserted echos in the requested php page to see if I get anything. Whatever I do the response is empty.
P.S. On another domain the ajax script worked fine. Exactly the same.
I have 2 domains. On one domain I send an ajax post to the other and expect some results.
There's your problem. This is because of the Same Origin Policy in JavaScript. And thats why...
...on another domain the ajax script worked fine.
There are some workarounds though, called Cross Domain Ajax.
For your needs, since you apparently want HTML and not JSON, I would suggest a small PHP script to get the content from the other domain and forward it to your client side. This would be called Ajax proxy.
See this question
I don't see your http_request.responseText, it returns what is echo'ed in the request URL.
So try add this:
http_request.onreadystatechange = function () {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
alert(http_request.responseText);
} else {
alert("An error occurred: "+ http_request.statusText);
}
}
};
Before:
//parameters is a global variable with the post data.
See if it works.
I'm new to AJAX, and trying to use it to speed up the display of results for a PHP full-text file search. I have about 1700 files to search, so instead of waiting for the server to process everything I want to send just the first 100 to the script and display the results, then the next 100 etc., so users get instant gratification.
To do this, I call a function callftsearch with the names of all the files in a string and some other information needed for the PHP function on the other side to run the search. callftsearch creates arrays of each 100 files, joins them in strings and sends that to ftsearch.php through the javascript function ftsearch. The PHP runs the search and formats the results for display, and sends the HTML string with the table back. addresults() just appends that table onto an existing div on the page.
Here's the javascript:
function GetXmlHttpObject()
{
var xmlHttp=null;
try { xmlHttp=new XMLHttpRequest(); }
catch (e) { try { xmlHttp=new ActiveXObject('Msxml2.XMLHTTP'); }
catch (e) { xmlHttp=new ActiveXObject('Microsoft.XMLHTTP'); } }
return xmlHttp;
}
function callftsearch(allfiles, count, phpfilenames, keywordscore, keywordsboolean, ascii) {
var split_files = allfiles.split("|");
var current_files = new Array();
var i;
for (i = 1; i<=count; i++) {
file = split_files.shift();
current_files.push(file);
if (i%100 == 0 || i == count) {
file_batch = current_files.join('|');
ftsearch(file_batch, phpfilenames, keywordscore, keywordsboolean, ascii);
current_files.length = 0;
}
}
}
function ftsearch(file_batch, phpfilenames, keywordscore, keywordsboolean, ascii)
{
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null) { return; }
// If our 'socket' has changed, send the response to addresults()
xmlHttp.onreadystatechange=addresults;
xmlHttp.open('POST','ftsearch.php', true);
var content_type = 'application/x-www-form-urlencoded';
xmlHttp.setRequestHeader('Content-Type', content_type);
xmlHttp.send('f='+file_batch+'&pfn='+phpfilenames+'&kw='+keywordscore+'&kwb='+keywordsboolean+'&a='+ascii);
}
function addresults()
{
var displayarray = new Array();
if (xmlHttp.readyState==4)
{
var ftsearchresults = xmlHttp.responseText;
$('#result_tables').append(ftsearchresults);
}
}
The problem: the page displays the exact same table repeatedly, with only the first few results. When I add alert(file_batch) to callftsearch it shows that it's sending the correct packets of files in succession. But when I alert(ftsearchresults) in addresults() it shows that it's receiving the same string over and over. I even added a timestamp at one point and it was the same for all of the printed tables.
Why would this happen?
A few things here.
First: it looks like you are already using jQuery since you have the line,
$('#result_tables')
If thsts the case, then why not use jQuerys built in ajax functionality? You could just do something like this,
$.ajax({
type: "POST",
url: "ftsearch.php",
data: 'f='+file_batch+'&pfn='+phpfilenames+'&kw='+keywordscore+'&kwb='+keywordsboolean+'&a='+ascii,
success: function(response){
$('#result_tables').append(response);
}
});
Second: If the output continues to be the same first few items each time, have you tried outputting the information that the ajax page is receiving? If it is receiving the correct information, then that meens there is something wrong with your PHP logic, which you do not have posted.
Long time reader, first time poster. Any help is greatly appreciated.
I have crafted an AJAX query using JavaScript. The script works correctly, and the interface does what I want, but Firefox is giving me an error message related to the PHP file being hit. It's strange, because it seems to suggest there's a syntax error in the PHP, but that doesn't make any sense. This is the error:
Error: syntax error
Source File: http://www.mysite.com/includes/ajax.php?action=checkpsudo&value=fd
Line: 1, Column: 1
Source Code:
yes
And the Javascript is below. Can anybody help me out? Thanks.
var ajaxobject = createajaxobjectObject();
function createajaxobjectObject() {
if (window.XMLHttpRequest) { // Mozilla, Safari,...
ajaxobject = new XMLHttpRequest();
if (ajaxobject.overrideMimeType) {
// set type accordingly to anticipated content type
ajaxobject.overrideMimeType('text/xml');
}
} else if (window.ActiveXObject) { // IE
try {
ajaxobject = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajaxobject = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!ajaxobject) {
alrt('Cannot create XMLHTTP instance');
return false;
}
return ajaxobject;
}
function checkpsudo(value) {
if (value == "") {
document.getElementById('feedback').innerHTML = "Please select a psudonym";
document.getElementById('feedback').className = "fail";
document.getElementById('done').disabled=true;
} else {
ajaxobject.onreadystatechange = function() { check(); };
ajaxobject.open('GET', '/includes/ajax.php?action=checkpsudo&value='+value, true);
ajaxobject.send(null);
}
}
function check() {
if (ajaxobject.readyState == 4) {
//IF WE GOT OUR CHAT XML BACK CORRECTLY
if (ajaxobject.status == 200) {
var response = ajaxobject.responseText;
var value = document.getElementById('psudoentry').value;
if(response=='no') {
document.getElementById('feedback').innerHTML = "'" + value + "' is already being used";
document.getElementById('feedback').className = "fail";
document.getElementById('done').disabled=true;
} else {
document.getElementById('feedback').innerHTML = "'" + value + "' is available";
document.getElementById('feedback').className = "success";
document.getElementById('done').disabled=false;
}
} else {
alert('There was a problem with the request.');
}
}
}
My first instinct is that this is not a problem with your JS but with the XML being output by the PHP script.
It sorta looks like your PHP may be generating a notice or a warning - then the first thing in the generated XML isn't an XML element, but the string "Notice: etc. etc.", which causes the browser to complain that what it's getting doesn't match the format it expects. In my experience, sometimes this breaks everything and sometimes there isn't any obvious effect. I'd turn off notices and warnings on your server - and if that clears up the problem, then you know where to start tracking it down.
Why shouldn't that make sense? If the php file has a syntax issue than the ajax call will get back the error page your server spits out and that will show up in the FF error-console while FF tries to parse the response
Lets say I have an array of javascript objects, and I am trying to pass those objects to a php page to save them into a database. I have no problems passing a variable to the php and using $_POST["entries"] on that variable but I can't figure out how to pass an entire array of objects, so I can access my objects.entryId and .mediaType values on the php page.
Oh and before anyone asks, yes the reason I need to do it this way is because I have a flash uploader, that you guessed it.. uploads into a CDN server (remote) and the remote server only replies back with such js objects.
Thanks for any help anyone can provide.
Here is my JS functions:
function test() {
entriesObj1 = new Object();
entriesObj1.entryId = "abc";
entriesObj1.mediaType = 2;
entriesObj2 = new Object();
entriesObj2.entryId = "def";
entriesObj2.mediaType = 1;
var entries = new Array();
entries[0] = entriesObj1;
entries[1] = entriesObj2;
var parameterString;
for(var i = 0; i < entries.length; i++) {
parameterString += (i > 0 ? "&" : "")
+ "test" + "="
+ encodeURI(entries[i].entryId);
}
xmlhttp.open("POST","ajax_entries.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", parameterString.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.onreadystatechange = handleServerResponseTest;
xmlhttp.send(parameterString);
}
function handleServerResponseTest() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
else {
alert("Error during AJAX call. Please try again");
}
}
}
maybe you need to take a look at json and jQuery ajax methods:
.- http://blog.reindel.com/2007/10/02/parse-json-with-jquery-and-javascript/
.- http://us.php.net/json_decode
The turorial is maybe a little outdated because jQuery last version is 1.3.x but you will get an idea on that and about the PHP json functions... if your server does not have the json extension enabled you can use some php classes:
.- http://google.com.co/search?rlz=1C1GPEA_enVE314VE314&sourceid=chrome&ie=UTF-8&q=php+json+class
good luck!
I too had the same trouble. But googling dint help.
I tried myself to tweak and test. And I got it. I am using POST method though. Please try the idea with GET method. Here is the idea:
Append the array index value within square brackets to the Post/Get variable name for array. Do this for each array element.
The part var parameters="&Name[0]="+namevalue1+"&Name[1]="+namevalue2; of the following script would give you a hint.
This is the test JS, I used (Again this uses POST method not GET):
var xmlAJAXObject;
function test() {
xmlAJAXObject=GetxmlAJAXObject();
if (xmlAJAXObject==null) {
alert ("Oops!! Browser does not support HTTP Request.");
return false;
}
var namevalue1=encodeURIComponent("Element 1");
var namevalue2=encodeURIComponent("Element 1");
var parameters="&Name[0]="+namevalue1+"&Name[1]="+namevalue2;
xmlAJAXObject.open("POST", "test.php", true);
xmlAJAXObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlAJAXObject.setRequestHeader("Content-length", parameters.length);
xmlAJAXObject.onreadystatechange=stateChanged;
xmlAJAXObject.send(parameters);
}
function stateChanged() {
if (xmlAJAXObject.readyState ==4) {
if (xmlAJAXObject.status == 200) {
alert('Good Request is back');
document.getElementById("show").innerHTML=xmlAJAXObject.responseText;
}
}
}
function GetxmlAJAXObject() {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject) {
// code for IE6, IE5
return new ActiveXObject("Microsoft.Microsoft.XMLHTTP");
}
return null;
}
This worked for me. Sorry for the formatting and incomplete code. I meant to give a direction. Google reault websites couldn't give a solution. Hope you find this useful.