Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 7 of 7
  1. #1
    b10
    b10 is offline
    New to the CF scene
    Join Date
    Jun 2011
    Posts
    4
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Problems sending and receiving with XMLHttpRequest

    Hi all,

    I'm having some problems both sending information to the backend (PHP) using POST, as well as successfully getting a response (if and when sending works).

    I should preface everything by specifying that I'm working entirely in a local environment (using MAMP), which my research thus far indicates could be a contributing factor (?). Should also mention, along those lines, that I've modified my response script to accept status 0 as well as 200 (the former being an acceptable response when running in a local environment).

    I've gotten to the point where I get the appropriate readyState and status responses, but there are issues in actually communicating with the PHP it seems.

    First of all, here are my JS functions:

    Code:
    function getXMLHTTPRequest() {
    
    	var req = false;
    	
    	try {
    	
    		/* for Firefox */
    		req = new XMLHttpRequest();
    	} catch (err) {
    	
    		try {
    		
    			/* some IE versions*/
    			req = new ActiveXObject("Msxm12.XMLHTTP");
    		} catch (err) {
    		
    			try {
    			
    				/* for some other versions of IE */
    				req = new ActiveXObject("Microsoft.XMLHTTP");
    			} catch (err) {
    			
    				req = false;
    			}
    		}
    	}
    	
    	return req;
    }
    
    
    function validateLogin() {
    
        var email=document.forms["signIn"]["email"].value;
    	var pass=document.forms["signIn"]["password"].value;
    	
    	//alert(email + pass);
    	if (email==null || email=="" || pass==null || pass=="") {
    
    		$("#invalid").addClass("hidden");
    		$("#emptyField").removeClass("hidden");
    		return false;
    	}
    	
    	var params = "email="+encodeURI(email)+"&pass="+encodeURI(sha1(pass));
    	var url = "validate_user.php";
    	//alert(params);
    	var req = getXMLHTTPRequest();
    		
    	req.open("POST", url, true);
    	req.onreadystatechange = function() {
    		checkResponse(req);
    	};
    	req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    	req.setRequestHeader("Content-length",params.length);
    	req.setRequestHeader("Connection", "close");
    	req.send(params);
    }
    
    
    function checkResponse(req) {
    	
    	if (req.readyState == 4) {
    
    		if (req.status == 200 || req.status == 0) {
    
    			//var result = req.responseText;
    			alert("Server says: "+ req.responseText);
    	
    		} else {
    
    			alert("There was a problem with the request: " + req.status + req.statusText);
    		}
    	}
    }
    Instead of the "validate_user.php" destination indicated above, I first tried a simpler "hello_ajax.php" test:

    Code:
    <?php 
    
    require_once('fns.php');
    $conn = db_connect();
    
    $new_id = rand();
    $pass = mysql_real_escape_string($_POST['pass']);
    
    $result = $conn->query("insert into test values
         						('".$pass."', '".$new_id."')");
    
    echo "Hello Ajax caller!"; 
    
    ?>
    With this, I was able to check that entries were successfully added to the "test" table. Also, the "pass" value being passed in was correct (from my html form that calls the ajax).

    However, the echo'd message was not successfully received back in the "checkResponse" JS function - the alert was simply "Server says: " with no response text. That illustrated the receiving problem.

    Now, consider "validate_user.php" instead of the hello_ajax function before:

    Code:
    <?php
    
    // include function files for this application
    require_once('fns.php');
    session_start();
         						
    //create short variable names
    $email = mysql_real_escape_string($_POST['email']);
    $pass = mysql_real_escape_string($_POST['pass']);
    
    
    $conn = db_connect();
      
      	$result2 = $conn->query("insert into test values
         						('".$email."', '".111."')");
    
    if(login2($email, $pass, 'USER')) {
        // if they are in the database register the user id
        $_SESSION['valid_user'] = $email;    
        
        echo "true";
        //return true;
    } else {
    
        echo "false";
        //return false;
    }
    With this, the database query at the start of the function is simply so I can check that we make it to that point - but we don't. In this case, it seems like we're not even getting into the PHP. I tried comparing this with the hello_ajax example but can't see any differences that would lead to this apparent breakdown in communication.

    If anyone could help me out with any or all of these issues, I would appreciate it immensely!

  • #2
    Senior Coder
    Join Date
    Jan 2011
    Location
    Missouri
    Posts
    4,166
    Thanks
    23
    Thanked 600 Times in 599 Posts
    I changed this line:
    var params = "email="+encodeURI(email)+"&pass="+encodeURI(sha1(pass));

    to this:
    var params = "email=joke";

    and it works. And it works with a simple if($_POST[joke] == '') added

  • #3
    b10
    b10 is offline
    New to the CF scene
    Join Date
    Jun 2011
    Posts
    4
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Thanks for the response but (forgive my ignorance!) what exactly are you getting at here? i tried modifying params as described but no change in behaviour. And what are you suggesting to do with that if statement?

  • #4
    Senior Coder
    Join Date
    Jan 2011
    Location
    Missouri
    Posts
    4,166
    Thanks
    23
    Thanked 600 Times in 599 Posts
    Ok Bad or non-existent explaination. So here is the through slow going one.

    As I said your code is fine. We check it by commenting out your parameters and adding a simple one. Perameters are needed because we're useing the POST method.
    Code:
    /*    var email=document.forms["signIn"]["email"].value;
    	var pass=document.forms["signIn"]["password"].value;
    	alert(email + pass);
    	if (email==null || email=="" || pass==null || pass=="") {
    
    		$("#invalid").addClass("hidden");
    		$("#emptyField").removeClass("hidden");
    		return false;
    	}*/
    	//var params = "email="+encodeURI(email)+"&pass="+encodeURI(sha1(pass));
    	var params = "email="+joke;
    Next we make a change in the server php script, It is now one line
    Code:
    <?php
    echo "Hello Ajax caller!";
    ?>
    In the <body> I added this button

    <input type="button" onclick="validateLogin();" />

    So I could control the program. Now, run the html and click button. The alert with

    Server says: Hello Ajax caller!

    On it appears. Things are now working and we have proof.

    Next check, Add this to the php
    Code:
    <?php
    if($_POST['email'] == 'joke'){
    	echo "Hello Ajax caller!";
    }else{
    	echo "It didn't work";
    }
    ?>
    run html - OK!

    next change in html
    var params = "email=joke";
    to
    var params = "email=jim";

    You should get the It didn't work message.

    At this point we KNOW the html code is working and the php also works.

    So we make this change.

    var joke = 'me';
    var params = "email="+joke;

    and php to

    <?php
    if($_POST['email'] == 'me'){
    echo "Hello Ajax caller!";
    }else{
    echo $_POST['email'];
    }
    ?>

    Things should still work. and you should see what your sending to server. You can use this spot to add the params you want and check them.

    I do hope this helps. It is the way I make sure I have a good setup and that things I add don't break things. I always leave one line at the end of my php file until I have everything working the way i want it to.

    echo 'CHECK EVERYTHING';

    This should appear someplace on my calling page or something is wrong. I remove it when coding is done.

  • Users who have thanked sunfighter for this post:

    b10 (06-14-2011)

  • #5
    b10
    b10 is offline
    New to the CF scene
    Join Date
    Jun 2011
    Posts
    4
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Thanks so much for the step by step explanation! I followed it word for word and got everything working as you said it should.

    However: once I tried to switch the html input over from the simple button you suggested to the html form I originally had (ignoring input fields, just using the submit to trigger the response) I had the problem I was seeing before: "Server says: " and no response text.

    So I guess this means that somehow the issue lies in the html? I've attached the code below (with the js validateLogin function as you recommended). Any ideas?

    Code:
    <!doctype html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>Sign-in validation test</title>
    	<link href="sivalidtest.css" type="text/css" rel="stylesheet" />
    	<script src="jquery-1.6.1.js"></script>
    	<script src="ajax_fns.js" type="text/javascript"></script>
    	
    	
    </head>
    
    <body>
    	<h1>Sign-in:</h1>
    	
    	<form name="signIn" id="signIn" onsubmit="return validateLogin()" method="post">
    		<table>
    			<tr>
    				<td><label for="email">Email: </label></td>
    				<td><input type="text" name="email" id="email" /></td>
    			</tr>
    			<tr>		
    				<td><label for="password">Password: </label></td>
    				<td><input type="password" name="password" id="password" /></td>
    			</tr>
    		</table>
    		<p id="emptyField" class="warning hidden">Both fields must be filled out.</p>
    		<p id="invalid" class="warning hidden">Not a valid Email/password combination.</p>
    		<p><input type="submit" value="Submit" /> </p>
    	</form>
    
    </body>
    
    </html>
    Again, thanks so much!

  • #6
    b10
    b10 is offline
    New to the CF scene
    Join Date
    Jun 2011
    Posts
    4
    Thanks
    1
    Thanked 0 Times in 0 Posts
    I think I got it! Added a 'return false;' at the very bottom of the validateLogin() function and response from the PHP is coming through.

    One last annoying issue: I'm echoing 'true' or 'false' from the backend, but when I print the response in the js function there seems to be a newline in front of the 'true' or 'false' that's coming out of nowhere. Is there some encoding/text related thing between js and php that I'm missing?

  • #7
    Senior Coder
    Join Date
    Jan 2011
    Location
    Missouri
    Posts
    4,166
    Thanks
    23
    Thanked 600 Times in 599 Posts
    No. That newline just seems to always be there. Been on this site before and I don't think an answer was ever found.

    Glad you got things working.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •