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
Related
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
I am updating my website to HTML 5. I had an Ajax script that called a PHP file, but it now doesn't work. The Firefox web developer add-on just throws an empty error containing only the line number. The line number points to the following line:
arequest.open('GET','userrating.php?h=' + h,true);
Here is the full script:
function ajaxRequest(){
var activexmodes = ["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"];
if(window.ActiveXObject){
for(var i = 0; i < activexmodes.length; i++){
try {
return new ActiveXObject(activexmodes[i]);
} catch(e){
//suppress error
}
}
} else if(window.XMLHttpRequest){
return new XMLHttpRequest();
} else {
return false;
}
}
function resetRating(h){
var arequest = new ajaxRequest();
arequest.onreadystatechange = function(){
if(arequest.readyState == 4){
if(arequest.status == 200 && window.location.href.indexOf("http")==-1){
var response = arequest.responseText;
// do something
}
}
}
h = encodeURIComponent(h);
arequest.open('GET','userrating.php?h=' + h,true);
arequest.send(null);
}
I know I am passing the correct value for 'h' and that the userrating.php page works absolutely fine with that value. I have tried a few different Ajax scripts now and they all give the same blank error on the .open line of the script.
Can anyone please give me any pointers?
Thanks in advance, Ian
I have an input field for a concept and when the user fills it out, he has to then check if the concept exists. So I made a check button, which checks a database using ajax and JavaScript to see if the concept exists. My problem is when using ajax and JavaScript I get this exception:
unexpected end of input
JS :
var concept = document.getElementById('acConceptName').value;
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
var isexisted = JSON.parse(xmlhttp.responseText);
if(isexisted[0]==true){
var errorMessage = document.getElementById('acSuggesConcepts');
var p = document.createElement('p');
p.innerHTML="this concept is already existed";
errorMessage.appendChild(p);
errorMessage.style.display="block";
}
}
}
xmlhttp.open("GET","http://localhost/Mar7ba/Ontology/isExistedConcept/"+concept+"/TRUE",true);
xmlhttp.send();
What is the exception and how can I solve it ?
PHP : function to check database and I always return true in it
public function isExistedConcept($concpetName,$Ajax){
if($Ajax==true){
$results=true
$d=array($results);
return json_encode($d);
}
}
Demo: http://jsfiddle.net/Wiliam_Kinaan/s7Srx/2/
After looking at the code for a while, one thing that might be a suspect is your PHP.
Your function in php ends with a return command. What the AJAX call is actually waiting for is some data to be sent back. The return command simply passes that value back to the entity that originally called the function.
Try alter your function to echo the result as opposed to returning it. Save your return value for when you need the result to go into another PHP function, not when you are returning data to the client.
I only put this return command here for readability.
public function isExistedConcept($concpetName,$Ajax){
if($Ajax==true){
$results=true
$d=array($results);
echo json_encode($d);
}
return;
}
Try this:
public function isExistedConcept($concpetName,$Ajax) {
if( $Ajax) return "1";
}
// This is a simplified version of what you're doing, but it returns "1" instead of "[true]"
// Now for the JS:
if( xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var isexisted = xmlhttp.responseText == "1";
if( isexisted) {...}
If that doesn't work, try adding alert(xmlhttp.responseText) and see if you're getting anything other than what should be there.
try this :
var concept = document.getElementById('acConceptName').value;
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","http://localhost/Mar7ba/Ontology/isExistedConcept/"+concept+"/TRUE",true);
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4){
if(xmlhttp.status==200){
var isexisted = JSON.parse(xmlhttp.responseText);
if(isexisted[0]==true){
var errorMessage = document.getElementById('acSuggesConcepts');
var p = document.createElement('p');
p.innerHTML="this concept is already existed";
errorMessage.appendChild(p);
errorMessage.style.display="block";
}
else{
console.log('error');
}
}
}
}
xmlhttp.send(null);
I am currently experiencing this issue, and am wondering why...?
The error message is:
"XMLHttpRequest cannot load http://www.panoramio.com/wapi/data/get_photos?v=1&key=dummykey&tag=test&offset=0&length=20&minx=-30&miny=0&maxx=0&maxy=150&callback=?.
Origin hxxp://foo.bar is not allowed by Access-Control-Allow-Origin.
test_panoramio.html:59Uncaught SyntaxError: Unexpected token )"
"hxxp://foo.bar" refers to the site I am running the script from.
The "test_panoramio.html" on the site contains e.g. the following :
var url = "http://www.panoramio.com/wapi/data/get_photos?
v=1&key=dummykey&tag=test&offset=0&length=20&minx=-
30&miny=0&maxx=0&maxy=150&callback=?";
function myScriptFn()
{
if (window.XMLHttpRequest) {
myAjax = new XMLHttpRequest();
if ( typeof myAjax.overrideMimeType != 'undefined') {
myAjax.overrideMimeType('text/xml');
}
} else if (window.ActiveXObject) {
myAjax = new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert('The browser does not support the AJAX XMLHttpRequest!!!');
}
myAjax.onreadystatechange = function()
{
handleResponse();
}
myAjax.open('GET', url, true);
myAjax.send(null);
}
function handleResponse()
{
if (myAjax.readyState == 4){ // Response is COMPLETE
if ((myAjax.status == 200) || (myAjax.status = 304))
{
// do something with the responseText or responseXML
processResults();
}else{
alert("[handleResponse]: An error has occurred.");
}
}
}
function processResults()
{
myObj = eval( '(' + myAjax.responseText + ')' );
...
doSomething()
...
}
The Panoramio URL works if typed directly to the browser.
Please could you help me with this, I am running out of hope...:(
Thank you in advance,
Yours
Marko
What you're hitting is the same origin policy which prevents cross-domain requests via XMLHttpRequest. There is a work-around if the site support is (and the one you're trying to access doed!), JSONP. This means all you need is a <script> tag with that callback parameter populated, like this:
<script type="text/javascript" src="http://www.panoramio.com/wapi/data/get_photos?v=1&key=dummykey&tag=test&offset=0&length=20&minx=-30&miny=0&maxx=0&maxy=150&callback=myFunction"></script>
And a function with the same name:
function myFunction(data) {
//data is what came back, it's a javascript object
}
You can test out a working example here.
I have a problem with some of my validation code. Here it is.
function isEmailValid(email) {
if( email == "") {
document.getElementById("emailMsg").innerHTML="<font color=red>Email cannot be empty</font>";
}
else {
var emailRegexStr = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if (!emailRegexStr.test(email)) {
document.getElementById("emailMsg").innerHTML="<font color=red>Invalid email</font>";
}
else {
xmlhttp = getHTTPObject();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("emailMsg").innerHTML = xmlhttp.responseText;
if(xmlhttp.responseText == "<font color=green>Correct !</font>" ) {
return true;
}
else {
return false;
}
}
}
xmlhttp.open("GET","includes/register_function.php?email="+email,true);
xmlhttp.send();
}
}
}
The below part of above code is not working properly.
if (xmlhttp.responseText == "<font color=green>Correct !</font>") {
return true;
}
else {
return false;
}
May be a stupid mistake I am newbie in PHP + AJAX.
here is the related PHP code
if (isset($_GET['email'])) {
$email=$_GET['email'];
if (!isUserExistsByEmail($email)) {
echo "<font color=green>Correct !</font>";
} else {
echo "<font color=red>Email already exisits</font>";
}
}
here is gethttpobject function
function getHTTPObject(){
if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
else if (window.XMLHttpRequest) return new XMLHttpRequest();
else {
alert("Browser does not support AJAX.");
return null;
}
}
i need to know how to change the getHTTPObject function for synchronous scenario .
Thanks.
You're relying on string-matching an arbitrary string - This is often error prone. Most likely there' a trailing carriage return in the response
Try doing:
alert('[' + xmlhttp.responseText +']');
in place of your if statement.
If the alerted value is not exactly
[<font color=green>Correct !</font>]
then you've got a problem. I suspect you'll get:
[<font color=green>Correct !</font>
]
or similar - in which case you need to modify your if statement as appropriate.
A better and less fragile approach would be something like this:
if(xmlhttp.responseText.indexof("Correct")>=0) {
return true;
} else {
return true;
}
or even better just do:
return (xmlhttp.responseText.indexof("Correct")>=0);
Are you expecting isEmailValid() to return true or false? Because the way it's written it will return nothing. The nested function defined inside isValidEmail() returns true or false but that will get called asynchronously some time after isValidEmail() has finished executing. And it won't be called by by your code. It gets called by the browser so you'll likely never have a chance to examine the return value to check if it's true or false.
One way to change your code to accomplish the goal of having isValidEmail() return true or false is to make the XMLHttpRequest call synchronous, rather than asynchronous (SJAX instead of AJAX). That way isValidEmail() will block until it receives a response back from the server (or times out). Of course your user will be unable to do anything on the page while they wait for their email address to be validated. This may or may not be acceptable.
Also, as others have pointed out, your regular expressions and string matching may need a little tweaking but judging by the question, that's not specifically what you're asking about.
I would suggest using a better stuffs in both PHP and javascript. Like, the PHP script could output the result in XML or JSON. And the Javascript, on the client side would parse the string according the format.
I suggest you have a look at the following links:
For JSON (I personally prefer JSON to XML, and some ways JSON is much better than XML)
http://www.json.org/example.html
http://www.php.net/manual/en/function.json-encode.php
For XML, simply google, I am sure you will get many results.
Eg:
in PHP:
$obj['result'] = 1;
$obj['color'] = 'green';
echo json_encode($obj);
in Javascript:
try{
var result = JSON.parse(xmlhttp.responseText);
}catch(err){
alert("...");
}