开发者

AJAX vs PHP submit of form

开发者 https://www.devze.com 2023-02-19 08:29 出处:网络
I originally had a form set up as such (CSS styles have been removed) <form name=\"LoginForm\" action=\"login.php\" method=\"post\">

I originally had a form set up as such (CSS styles have been removed)

<form name="LoginForm" action="login.php" method="post">

<input name="email" id="email" typ开发者_运维知识库e="text"></input>

<input name="password" id="password" type="password"></input>

<input name="login" id="login" type="submit" value="Login"></input>
</form>

and it worked fine, and login.php would validate the user creditionals. However, that approach required a page redirect. I am trying to migrate the code to AJAX so I can query the login details and stay within the page. [edit] here is the AJAX object I use

function Ajax(){
    this.xmlhttp=null;  //code below will assign correct request object
    if (window.XMLHttpRequest){ // code for IE7+, Firefox, Chrome, Opera, Safari
        this.xmlhttp=new XMLHttpRequest();
    }
    else{       // code for IE6, IE5
        this.xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    this.stateChangeFunction=function(){};  //user must reimplement this

    var that=this;
    this.xmlhttp.onreadystatechange=function(){ //executes the appropriate code when the ready state and status are correct
        if (this.readyState==4 && this.status==200){
            that.stateChangeFunction();     
        }
        else{
            dump("Error");
        }
    }
}

then I have a login.js function, which I am not too sure how to incorporate, currently I add it to the onclick event of the submit button:

function login(email,password){
    var ajax=new Ajax();

    //ajax.xmlhttp.open("GET","login.php?LoginEmailField="+email+",LoginPasswordField="+password,true);
    //ajax.xmlhttp.send();
}

You will notice how those last two lines are commented out, I am not too sure how to send arguments at the moment, but the point is that even with the two commented out, the entire site still reloads. What is the correct way to use AJAX in forms.

Thanks


I havent done enough ajax in raw js to give a tutorial here so Im' going to use jquery. However anything i show can be done in raw javascript so maybe someone else will be kind enough to show you a raw implementation.

First of all you should use POST instead of GET for your login. Secondly as i said in my comment you should use the actual URL to the login page as the action. This way users who dont have JS for whatever reason can still login. Its best to do this by binding to the forms onSubmit event.

<form name="LoginForm" action="login.php" method="post">

<input name="email" id="email" type="text"></input>

<input name="password" id="password" type="password"></input>

<input name="login" id="login" type="submit" value="Login"></input>
</form>

And with jquery:

function doLogin(event){
  event.preventDefault(); // stop the form from doing its normal post
  var form = $('form[name=LoginForm]');
  // post via ajax instead
  $.ajax({
    url: form.attr('action'), // grab the value of the action attribute "login.php"
    data: form.serialize(), // converts input fields to a query string
    type: 'post',
    dataType: 'text',
    success: function(data){
      /* callback when status is 200
       * you can redirect here ... data is the response from the server, 
       * send the redirect URL in this response
       */
      window.location.href = data;
    },
    error: function(textStatus){
      alert('ERROR');
    }
  });
}

// bind our function to the onSubmit event of the form
$('form[name=LoginForm]').submit(doLogin); 

Then on the serverside you can check if its an ajax based request:

<?php

 // do your login stuff

 // set $successUrl to the URL you want to redirect to

 // check if its ajax
 if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) 
   && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
 {
   echo $successUrl;
   exit(0);
 }
 else
 {
    // was a non-ajax request - do a normal redirect
    header('Location: '.$successUrl);
 }


Your code only shows HTML. AJAX uses javascript to communicate to PHP script.

So, Only on seeing the js code, Debugging is possible.


To avoid the default event you have to use action='javascript: void(null);' instead of removing it.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号