I have a problem in AJAX - php

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("...");
}

Related

Why is '\n' being pre-pended to my HTTP (AJAX) responseText?

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

ajax with JavaScript exception: unexpected end of input

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);

Javascript - return a value from a function called elsewhere

The title of this question is not very clear but I cannot explain what I am asking without providing some code.
I am making a page which submits reports (which are arrays) using AJAX. I have functions stored in a library which submit the array to the PHP page that look like this:
function saveReport(params)
{
var url="reports/save.php";
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
return false;
}
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("POST",url,true);
//Send the proper header information along with the request
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.send(params);
}
function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
if (xmlHttp.responseText == 'complete')
{
return true;
}
else
{
return false;
}
}
}
(I don't believe the GetXmlHttpObject() function is relevant to the question)
I would like to be able to call the saveReport() from my page like this
success = saveReport(params);
if (success == true)
{
alert('success');
}
else
{
alert('failure');
}
So the function saveReport() needs to return a value which is returned from the function stateChanged() when it is called so that the page that called saveReport() can then decide what to do - which may be a different on different pages. Is there any way of doing this?
I realise that it may be impossible the way I am trying but is there something I can do to the same effect.
Is there a reason why you're rolling your own Ajax helper?
In this situation you're going to need a callback function to be fired when the server has responded so that you can do something with the response, whether it be a success or fail.
Obviously, you can use something like jQuery.ajax but that might be overkill for something this simple.
You could try one of the many micro Ajax libraries at http://microjs.com/#ajax to achieve what you're after.
You won't be able to do it like that because the request doesn't block (it's asynchronous). What you'll have to do is use a callback the same way you have your stateChanged() set as the callback function for xmlHttp.onreadystatechange.
You can make a new function that handles the results and call that from the stateChanged(), passing true or false as its parameter to indicate success.
function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
saveReportFinished(xmlHttp.responseText == 'complete');
}
else{
saveReportFinished(false);
}
}
function saveReportFinished(success) {
if (success == true)
{
alert('success');
}
else
{
alert('failure');
}
}
Technically you could just combine all of this into stateChanged(), but I think it's cleaner this way.
Looks like you have a couple problems here:
1) Async operations cause trouble with function returns, since the function will finish firing before the async response comes back.
2) A function will only return what you tell it to, so to get a function to return the result of another function, you'd need to do something like this: return stateChanged( args )
The solution to 1) is to use a callback, like so:
function saveReport( params, callback ){
...
xmlHttp.onreadystatechange = function(){
stateChanged( callback );
};
Run the callback inside stateChanged()...
function stateChanged( callback ){
...
callback( true );
...
callback( false );
Then pass the callback like so:
saveReport( params, function( boolean ){
if( boolean )
alert('success');
else
alert('failure');
};
Have you tried
success = saveReport(stateChanged());
if (success == true) {
alert('success');
} else {
alert('failure');
}

Strange JavaScript syntax error from an AJAX call to PHP

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

Simple AJAX code not being recognized

I'm trying to begin learning AJAX, and I've already hit a little stump. So I'm starting simple and just trying to get an alert to pop up showing the length of the string the user types into a text field.
The HTML:
<form action="/scripts/addemail_fb.php" method="post">
<input type="text" name="email" value="Enter your email here!" />
<input id="submit" type="submit" name="submit" value="Go!" onClick="check(this.form.email.value);"/>
</form>
The JS:
function check(email) {
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
email=encodeURIComponent(email);
req.open("POST","/scripts/addemail.php");
req.setRequestHeader(
'Content-Type',
'application/x-www-form-urlencoded; charset=UTF-8');
req.send(email);
req.onreadystatechange=function() {
if(req.readyState==4) {
result = req.responseText;
alert("The length of the email is:" + result);
}
}
return false;
}
The PHP (addemail.php):
<?php
function check_email($input) {
return strlen($input);
}
$email = urldecode(implode(file('php://input')));
$result = check_email($email);
echo $result;
?>
And yes, I've included the JS in the section. I got this almost directly from a tutorial so I'm not sure what's going on. My testing browser is Safari, but I've also tried FF. Sorry is this is obvious, as this is my very first AJAX attempt. Thanks!
EDIT: Sorry, the problem is that its just going to the file described in action="addemail_fb" instead of the JS.
-iMaster
Change the onclick handler to onsubmit (on the form), like so:
<form onsubmit="return check(this.email.value);"> ... </form>
Also, set your req.onreadystatechange before calling req.send ()
inline javascript is bad practice. this solution may seem a bit more convoluted but if you implement it into the rest of your scripts then you will find this much more elegant.
JS libraries use similar methods, but if you cant use one then do this instead:
onDomReady(function(){
var oForm = document.getElementById("myform");
addListener(oForm,"submit",function(){
removeListener(oForm,"submit",arguments.callee);
// do stuff here
});
});
// Cross-browser implementation of element.addEventListener()
function addListener(element, type, expression, bubbling)
{
bubbling = bubbling || false;
if(window.addEventListener) { // Standard
element.addEventListener(type, expression, bubbling);
return true;
} else if(window.attachEvent) { // IE
element.attachEvent('on' + type, expression);
return true;
} else return false;
}
// Cross-browser implementation of element.removeEventListener()
function removeListener(element, type, expression, bubbling)
{
bubbling = bubbling || false;
if(window.removeEventListener) { // Standard
element.removeEventListener(type, expression, bubbling);
return true;
} else if(window.detachEvent) { // IE
element.detachEvent('on' + type, expression);
return true;
} else return false;
}
function onDomReady(fn) {
// Mozilla, Opera and webkit nightlies currently support this event
if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", function(){
document.removeEventListener( "DOMContentLoaded", arguments.callee, false );
fn();
}, false );
// If IE event model is used
} else if ( document.attachEvent ) {
// ensure firing before onload,
// maybe late but safe also for iframes
document.attachEvent("onreadystatechange", function(){
if ( document.readyState === "complete" ) {
document.detachEvent( "onreadystatechange", arguments.callee );
fn();
} else {
setTimeout( arguments.callee, 0 );
return;
}
});
} else {
// A fallback to window.onload, that will always work
addListener(window,"load",fn);
}
}
Here is the problem:
You are doing it wrong.
And jQuery is the Answer.
But seriously. Try using jQuery, as it will make you Javascript life easier than cutting into a piece of pumpkin pie.
AJAX is one of the most annoying subjects in Javascript, and jQuery, along with other libraries have gone and made the problem much easier to deal with. Plus, there are many many other great features of jQuery that just make it so much more wonderful to work with Javascript.
In jQuery, the entire code would look like:
$.post("/scripts/addemail.php", {email_address:email}, function(data){
alert("The length of the email is:"+data);
});
Speaking of pumpkin pie.....
Now that I've finished my public server announcement for jQuery, you will want to check the Javascript console (Ctrl + Shift + J in Firefox), and run the page. It will give you any errors that you are bound to have such as syntax errors or various other things that go wrong.
If you can go there and then give us any error messages that pop-up, we will be more likely to be able to solve your problem.

Categories