www.webdeveloper.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 24

Thread: Running Javscript held inside my ajax response text

  1. #1
    Join Date
    Dec 2010
    Posts
    232

    Running Javscript held inside my ajax response text

    Judging by the amount of threads on this and very little success people are having it seems it is really hard but can anyone please help me figure this out.

    I have the following code in my index.php file:-

    HTML Code:
    <script type="text/javascript" src="js/show_main_page.js"></script>
    
    <script type="text/javascript">
    function login(email, password)
    {
    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)
        {
        document.getElementById("user_login_area").innerHTML=xmlhttp.responseText;
        }
      }
    xmlhttp.open("GET", "login_script.php?email="+email+"&password="+password,true);
    xmlhttp.send();
    }
    
    </script>
    
    <form name="login_form" method="post" action="">
                        Email: <input name="email" type="text"/>
                        Password: <input name="password" type="password"/>
                                    
                        <input onclick="login(login_form.email.value,login_form.password.value); return false;" value="Log In" type="submit"/>
    </form>
    
    <div id="content_section">
    </div>
    And here's my login_script.php which that points to:-

    HTML Code:
    <?php
    
    $con = mysql_connect('localhost', '*****', '*******');
    if (!$con)
      {
      die('Could not connect: ' . mysql_error());
      }
    
    mysql_select_db("users_db", $con);
    
    
    
    if (isset($_GET['email'])){$email = $_GET['email'];}else{$email = "";};
    if (isset($_GET['password'])){$password = $_GET['password'];}else{$password = "";};
    	
    $login = 0;
    	
    if (isset($_GET['attempt'])){$attempt = 1;}else{$attempt = 0;};
    	
    if ($email !== "" && $password !== ""){
    	 
    	$result = mysql_query("SELECT users.user_id, users.first_name, users.surname FROM users WHERE email = '$email' AND password = '$password'");
    	$row = mysql_fetch_assoc($result);
    	$loginnumrows = mysql_num_rows($result);
    		
    	if($loginnumrows > 0){
    		$login = 1;
    		$_SESSION['logged_in_userid'] = $row['user_id'];			
    	}
    	
    }else if(($email == "" && $password == "") || ( !isset($email) && !isset($password) )){
    	$login=0;
    }
    
    ?>
    
        <?php if($login == 0):?>
            <form name="login_form" method="post" action="">
                Email: <input name="email" type="text" value="<?php echo $email;?>"/>
                Password: <input name="password" type="password" value="<?php echo $password;?>"/>                               
                <input onclick="login(login_form.email.value,login_form.password.value); return false;" value="Log In" type="submit"/>
            </form>
                    
            <p>Incorrect email or password</p>
                
        <?php endif;?>
                
        <?php if($login == 1):?>
                            
        	<div id="user_display_div">
                  
            	<p><?php echo $row['first_name']." ".$row['surname'];?>"</p>
                        
            </div>
            
            <script>
    		
    			showMainPage(<?php echo $row['user_id'] ;?>, 'profile');
    		
    		</script>
                     
        <?php endif;?>            
    
    <?php
    mysql_close($con);
    ?>
    
    The javscript in that script block simply will not run at all. The show main page function is supposed to show the logged in user's profile by loading it into the content_section div in index.php. Here is the js file code for that function:-

    HTML Code:
    function showMainPage(userid, page)
    {
    if (page=="")
      {
      document.getElementById("content_section").innerHTML="";
      return;
      } 
    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)
        {
        document.getElementById("content_section").innerHTML=xmlhttp.responseText;
        }
      }
    xmlhttp.open("GET", page+".php?userid="+userid,true);
    xmlhttp.send();
    }
    Can anybody please help me out.
    Last edited by jimmyoneshot; 03-28-2011 at 07:07 PM.

  2. #2
    Join Date
    Dec 2010
    Posts
    232
    Help???

  3. #3
    Join Date
    Jan 2007
    Location
    Wisconsin
    Posts
    2,120
    Haven't really trudged through your code in its entirety, but this jumps out at me pretty quickly:

    PHP Code:
            <script>
            
                showMainPage(<?php echo $row['user_id'] ;?>, 'profile');
            
            </script>
    Note the missing script type!

    If you need further assistance, I'm afraid I cannot in good conscious help you until you've one-way encrypted and salted your passwords!

  4. #4
    Join Date
    Dec 2010
    Posts
    232
    Ye sorry. The script type is in there in my version but I didn't copy and paste it over correctly.

    I can encrypt my passwords anytime but for now I just need to figure out how to get javascript within an ajax response text working correctly but if you can't help no worries.

  5. #5
    Join Date
    Jan 2007
    Location
    Wisconsin
    Posts
    2,120
    Salt and encrypt your passwords with SHA() at the very minimum. And if you're using PHP, SHA2 is well within reach: see the hash function!

    I cannot stress enough how important this is to do -- particularly considering how easy it is to do!!!

    Now ... assuming you will do the right thing in regards to password hashing, try this:

    1. Download Chrome if you don't already have it
    2. Open Chrome
    3. Open a new tab
    4. Open the Developer Tools / Inspector
    5. Navigate to your web page
    6. Attempt to log in
    7. Verify that the correct request/response has occurred (in the Network tab)
    8. Verify that the DOM has been updated (in the elements tab) appropriately
    9. Check for javascript errors (in the console tab)


    Let us know what you find. And please show us your new, updated, password encrypting authentication code!

  6. #6
    Join Date
    Jan 2007
    Location
    Wisconsin
    Posts
    2,120
    Oh -- you may also be interested in trying to do this with "JSONP" instead. Rather than write HTML, including a script tag back, just write the script to a new script element:

    On the page, triggered by the form "submit" ...
    HTML Code:
    var d = new Date();
    var t = document.createElement('script');
    t.src = 'login_script.php?user=' + username + '&pass=' + pass + '&ts=' + d.getTime();
    t.type = 'text/javascript';
    document.appendChild(t);
    In login_script.php ...
    PHP Code:
    // -- snip --
    if (isset($_SESSION['authenticated_user']) && $_SESSION['authenticated_user']) {
      print 
    "showMainPage({$_SESSION['authenticated_user']['user_id']}, 'profile');";
    } else {
      print 
    "showLoginError('Invalid credentials');";

    Define a showLoginError() method, of course ...

    ... and salt and sha2 your passwords!

  7. #7
    Join Date
    Dec 2010
    Posts
    232
    OK I'm basically a novice at javascript so that's all quite confusing for me but I've changed my login.js code to this:-

    Code:
    function login(email, password)
    {
    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)
        {
        document.getElementById("user_login_area").innerHTML=xmlhttp.responseText;
        }
      }
      
    var d = new Date();
    var t = document.createElement('script');
    t.src = 'login_script.php?email=' + email + '&password=' + password + '&ts=' + d.getTime();
    t.type = 'text/javascript';
    document.appendChild(t);  
    xmlhttp.open("GET", "login_script.php?email="+email+"&password="+password,true);
    xmlhttp.send();
    }
    and my login_script.php code to this:-

    Code:
    <?php
    
    $con = mysql_connect('localhost', '*****', '*******');
    if (!$con)
      {
      die('Could not connect: ' . mysql_error());
      }
    
    mysql_select_db("users_db", $con);
    
    
    
    if (isset($_GET['email'])){$email = $_GET['email'];}else{$email = "";};
    if (isset($_GET['password'])){$password = $_GET['password'];}else{$password = "";};
    	
    $login = 0;
    	
    if (isset($_GET['attempt'])){$attempt = 1;}else{$attempt = 0;};
    	
    if ($email !== "" && $password !== ""){
    	 
    	$result = mysql_query("SELECT users.user_id, users.first_name, users.surname FROM users WHERE email = '$email' AND password = '$password'");
    	$row = mysql_fetch_assoc($result);
    	$loginnumrows = mysql_num_rows($result);
    		
    	if($loginnumrows > 0){
    		$login = 1;
    		$_SESSION['logged_in_userid'] = $row['user_id'];			
    	}
    	
    }else if(($email == "" && $password == "") || ( !isset($email) && !isset($password) )){
    	$login=0;
    }
    
    ?>
    
        <?php if($login == 0):?>
            <form name="login_form" method="post" action="">
                Email: <input name="email" type="text" value="<?php echo $email;?>"/>
                Password: <input name="password" type="password" value="<?php echo $password;?>"/>                               
                <input onclick="login(login_form.email.value,login_form.password.value); return false;" value="Log In" type="submit"/>
            </form>
                    
            <p>Incorrect email or password</p>
                
        <?php endif;?>
                
        <?php if($login == 1):?>
                            
        	<div id="user_display_div">
                  
            	<p><?php echo $row['first_name']." ".$row['surname'];?>"</p>
                        
            </div>
            
    <?php
    
    if (isset($_SESSION['logged_in_userid']) && $_SESSION['logged_in_userid']) {
      print "showMainPage({$_SESSION['logged_in_userid']}, 'profile');";
    } else {
      print "showLoginError('Invalid credentials');";
    } 
    
    ?>
                     
        <?php endif;?>            
    
    <?php
    mysql_close($con);
    ?>
    Which doesn't work.

  8. #8
    Join Date
    Jan 2007
    Location
    Wisconsin
    Posts
    2,120
    Yeah ... the JSONP thing is meant to be in place of your existing method body. login_script.php should be returning a single line of javascript -- no HTML.

    See: http://en.wikipedia.org/wiki/JSONP

  9. #9
    Join Date
    Dec 2010
    Posts
    232
    Yep I've put the json code you provided into my login() function as shown in my last post, so do you mean I also need to query the database within that function before I pass everything on to login_script.php?

  10. #10
    Join Date
    Jan 2007
    Location
    Wisconsin
    Posts
    2,120
    No. You're missing the concept. This code creates a script tag:

    EDITED: originally had some of your original AJAX in this snippet -- removed it!
    HTML Code:
    var d = new Date();
    var t = document.createElement('script');
    t.src = 'login_script.php?email=' + email + '&password=' + password + '&ts=' + d.getTime();
    t.type = 'text/javascript';
    document.appendChild(t);  
    It's meant to replace your existing AJAX call -- not add to it. The new script tag will reference an external script to be generated by login_script.php. Thus, login_script.php should be printing/echoing ONLY JavaScript, what would be found in a normal external JavaScript -- NO HTML WHATSOEVER!

    So, you need to replace all existing output in login_script.php with JavaScript output. If you were to put all of your actual authentication code in another script, for example, call it auth.inc, and write an authenticate() function that takes in a user and password and modifies the session accordingly, your login_script.php would look like this, in its entirety:
    PHP Code:
    <?php

    require_once("auth.inc");

    // try to authenticate the user -- trust that the authenticate() function
    // is doing all of the necessary data sanitization
    authenticate($_GET['user'], $_GET['pass']);

    // see whether a user_id has been set in the session and call the appropriate
    // client-side method
    if (isset($_SESSION['logged_in_userid']) && $_SESSION['logged_in_userid']) {
      print 
    "showMainPage({$_SESSION['logged_in_userid']}, 'profile');";
    } else {
      print 
    "showLoginError('Invalid credentials');";


    ?>
    From the browser's perspective, it sees one of the following:

    login_script.php?user=username&pass=invalidpass&ts=3234234:
    Code:
    showLoginError('Invalid credentials');
    login_script.php?user=username&pass=correctpass&ts=3234456:
    Code:
    showMainPage(23422, 'profile');
    You just need to ensure that both showMainPage() and showLoginError() are defined to display the correct thing to the user. To start with, I would suggest having each of them simply alert() their first parameter to ensure they're even getting called.

    Make sense?

    Oh, and How's that password hashing coming along?

  11. #11
    Join Date
    Jan 2009
    Posts
    3,346
    Another thing to note is that once you get the call-response working it might make more sense to use POST rather than GET along with a single use token to prevent CSRF.

  12. #12
    Join Date
    Jan 2007
    Location
    Wisconsin
    Posts
    2,120
    Single-use tokens are generally a good idea -- yes. POST requests are not an option with JSONP though. Not something I would be terribly worried about though. If someone can snag your token, they can just as easily forge a POST request. And even in that case, the worst they can do is authenticate!

    If you're worried about someone brute-forcing your users database, the best solution is usually just to implement some kind of rate-limiting. You would probably want some combination of limits on failed requests by IP, session, and intended user.

  13. #13
    Join Date
    Jan 2009
    Posts
    3,346
    Quote Originally Posted by svidgen View Post
    Single-use tokens are generally a good idea -- yes. POST requests are not an option with JSONP though. Not something I would be terribly worried about though. If someone can snag your token, they can just as easily forge a POST request. And even in that case, the worst they can do is authenticate!

    If you're worried about someone brute-forcing your users database, the best solution is usually just to implement some kind of rate-limiting. You would probably want some combination of limits on failed requests by IP, session, and intended user.
    I was meaning to POST the results (through AJAX) and receive the single use token with which to call the JSONP as a JSON object. This would allow you to use the more secure POST along with the ease of use of JSONP.

  14. #14
    Join Date
    Jan 2007
    Location
    Wisconsin
    Posts
    2,120
    This is a little off-topic ... would you mind sending me a PM to explain it further. Perhaps I'm having a brain-fart, but I'm struggling to see why what you're proposing is more secure.

  15. #15
    Join Date
    Dec 2010
    Posts
    232
    Thanks for sticking by me and giving me all this help but I'm confused you see if I directly replace this:-

    Code:
    function login(email, password)
    {
    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)
        {
        document.getElementById("user_login_area").innerHTML=xmlhttp.responseText;
        }
      }
      
    var d = new Date();
    var t = document.createElement('script');
    t.src = 'login_script.php?email=' + email + '&password=' + password + '&ts=' + d.getTime();
    t.type = 'text/javascript';
    document.appendChild(t);  
    xmlhttp.open("GET", "login_script.php?email="+email+"&password="+password,true);
    xmlhttp.send();
    }
    with this:-

    Code:
    var d = new Date();
    var t = document.createElement('script');
    t.src = 'login_script.php?email=' + email + '&password=' + password + '&ts=' + d.getTime();
    t.type = 'text/javascript';
    document.appendChild(t);
    then I now have no function to pass the email and password to.

    Remember here's the line for the submit button in my login form on my index.php page:-

    Code:
    <input onclick="login(login_form.email.value,login_form.password.value); return false;" value="Log In" type="submit"/>
    Hence I don't want the email and password to be submitted which is why I used the return false in the onclick property. I only want them to be passed to a javascript function and dealt with from there i.e. no page refresh. I'm not sure how this could work with the code you provided.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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



Recent Articles