Ajax-PhP通信

时间:2016-04-23 22:08:31

标签: javascript php jquery html ajax

我正在编程的脚本有问题。我是AJAX的新手,无法弄清楚我做错了什么让它无法工作。任何帮助将受到高度赞赏。我在页面上有多个表单,当我分离表单时,Ajax和php之间的通信工作正常。但当我把所有东西放在一起时,它就会停止工作。我确实相信它可能是一个通信问题,也可能是一些冲突的脚本或只是一些不好的编码。

这是php代码:

@session_start();
 if(isset($_SESSION["username"])){
   header("location: home.php");
exit();
}else{
    $usertitle = $_POST['ut'];
    $userfname = $_POST['uf'];
    $userlname = $_POST['ul'];
    $useremail = $_POST['ue'];
    $userloc = $_POST['uloc'];
    $user_est_typ = $_POST['utp'];
    $userfname = preg_replace("/[^A-Za-z0-9?![:space:]]/","",$userfname);
    $userlname = preg_replace("/[^A-Za-z0-9?![:space:]]/","",$userlname);
    if($usertitle == "Title...."){
        echo '<font color="red">Error: Please select a title.';
        exit();
    }else if($userfname == NULL){
        exit('<font color="red">Error:  You need a first name to proceed. </font>');
    }else if( strlen($userfname) <= 2){
        exit('<font color="red">Error: First name should be three (3) or more letters.</font>');
    } else if($userlname == ""){
        exit('<font color="red">Error: Giving a Surname would be nice.</font>');
    }else if( strlen($userlname) <= 2){
        exit('<font color="red">Error: Surname should be three (3) or more Letters.</font>');
    }else if(!strpos($useremail, "@") || !strpos($useremail, "." || !filter_var($useremail, FILTER_VALIDATE_EMAIL) === true)){
        exit('<font color="red">Email Address not valid</font>');
    }else if($user_est_typ == "Select..."){
        exit('<font color="red">Error: You must select an estimate type to proceed.</font>');
    }else if($userloc == ""){
        exit('<font color="red">Error: A location would be required so as to get the radiation data for the estimates</font>');
    }else {
        include("../../scripts/dbconect.php");
        $queryuseremail = mysql_query("SELECT id FROM userdata WHERE userEmail='$useremail' LIMIT 1"); 
        $useremail_check = mysql_num_rows($queryuseremail);
        if ($useremail_check > 0){ 
         echo "The email address ".$useremail." is already registered in ur database";
        exit();
        }
        // More Validation and mysql insert

        exit('<font color="red">signup_success</font>');
    }
}

这是我的AJAX代码:

  function _(x){
         return document.getElementById(x);
   }

   function show(id){
        var divelement = _(id);
        if(divelement.style.display == 'none')
           divelement.style.display = 'block';
           else
   divelement.style.display == 'none';
   }


   function hide(id){
      var divelement = _(id);
      if(divelement.style.display == 'block')
        divelement.style.display = 'none';
      else
        divelement.style.display == 'block';
   }

 function emptyElement(id){
    _(id).innerHTML = "";
 }

 function estimatetypeimg(){
      var estType = _('estimatetype').value;
       if (estType == 'solarpv'){
           show('estimate_pv'); 
           hide('estimate_thermal');
         }
          else if(estType == 'solarthermal'){
            hide('estimate_pv'); 
            show('estimate_thermal');
        }
       else{
         hide('estimate_pv'); 
         hide('estimate_thermal');
       }
     }

  function newUsers() {
     var title = _("salutation").value;
     var fname = _("fname").value;
     var lname = _("lname").value;
     var email = _("email").value;
     var loc = _("location").value;
     var tp = _("estimatetype").value;
     var url = "ajax.php";
     var vars = "ut="+title+"uf="+fname+"&ul="+lname+"&ue="+email+"&uloc="+loc+"&utp="+tp;

     var xhttp = new XMLHttpRequest();
     xhttp.onreadystatechange = function() {
     if (xhttp.readyState == 4 && xhttp.status == 200) {
        _("statuscheck").innerHTML = xhttp.responseText;
      }
    };
    xhttp.open("POST", url, true);
    xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhttp.send(vars);
  }

这是我的HTML代码:

<div id="startbuts" style="display:none">
    <form class="pure-form" name="startbutsform" id="startbutsform" onsubmit="return false;">
        <button type="submit" id="newusersbtn" onclick="show('newusers'); hide('existingusers'); hide('existingusersbtn');"class="pure-button pure-button-primary">New Estimate</button>
        <button type="submit" id="existingusersbtn" onclick="show('existingusers'); hide('newusers'); hide('newusersbtn');" class="button-secondary pure-button">Load Previous Estimate</button>
    </form>

    <div id="existingusers" style="display:none">
        <form class="pure-form" name="signupex" id="signupex" onsubmit="return false;">
            <fieldset>
                <legend>Existing users: login with your email and Data ID.</legend>
                    <input type="email" id="dataemail" placeholder="Email" >
                        <input type="text" id="dataid" placeholder="DataId"><br/>
                            <button id="signupexbtn" type="submit" onclick="signinold()" class="pure-button pure-button-primary">Sign in</button>
                 </fieldset>
                 </form>
               </div>
              <div id="newusers" style="display:none">
             <form class="pure-form" name="signupnew" id="signupnew" onsubmit="return false;">
             <fieldset>
                    <legend>New users start here.</legend>
                      <div class="pure-control-group">
                      <label for="salutation">Title: </label>
                      <select id="salutation" name="salutation">
                      <option>Title....</option>
                      <option>Prof. Dr.</option>
                      <option>Prof.</option>
                      <option>Dr.</option>
                      <option>Mr.</option>
                      <option>Mrs.</option>
                      <option>Miss.</option>
               </select>
            </div>
           <div class="pure-control-group">
        <label for="fname">First name:</label>
        <input id="fname" name="fname" type="text" placeholder="First Name">
    </div>
    <div class="pure-control-group">
        <label for="lname">Last name:</label>
        <input id="lname" name="lname" onfocus="emptyElement('errorcheck')" type="text" placeholder="Last Name">
    </div>

    <div class="pure-control-group">
        <label for="email">Email Address:</label>
        <input id="email" name="email" type="email" onfocus="emptyElement('errorcheck')" placeholder="Email Address">
    </div>

    <div class="pure-control-group">
        <label for="location">Project Location: </label>
        <input id="location" name="location" type="text" onfocus="emptyElement('errorcheck')" placeholder="Enter City ex Buea...">
    </div>

    <div class="pure-control-group">
        <label for="estimatetype">Type of Estimate: </label>

        <select id="estimatetype" name="estimatetype" onchange="estimatetypeimg()">
            <option value="Select">Select...</option>
            <option value="solarpv">Solar PV</option>
            <option value="solarthermal">Solar Thermal</option>
        </select>
    </div>

    <div id="estimate_pv" style="display:none" >
        <img id="solarpvimg" src="images/solarpv.png" width="250" height="109" alt="Solar PV" /> 
    </div>
    <div id="estimate_thermal" style="display:none">
        <img  id="solarthermalimg" src="images/solarthermal.png" width="250" height="109" alt="Solar PV" /> 
    </div>
    <hr/>
        <button id="signupnewbtn" type="button" class="pure-button pure-button-primary" onclick="newUsers()" >Start Calculator</button>
        <button onclick="emptyElement('errorcheck'); hide('estimate_pv'); hide(estimate_thermal);" class="pure-button pure-button-primary" type="reset">Reset </button>
       </fieldset>
         </form>
        </div>
       </div>

1 个答案:

答案 0 :(得分:0)

谢谢David Lavieri,尤其是Sher Kahn。你的回答让我思考,我终于找到了为什么我没有从我的PhP脚本得到任何回应。正如汗也提到的,我只是一个爱好编码器,你绝对正确我的代码不是很干净。我清理了JSLint上的代码并意识到我有太多糟糕的编码习惯。 :)。还要感谢您使用malsup查询插件。它们非常方便,并且会有很多帮助。

最后我遇到的问题。实际问题是php文件的链接。网址定义不明确,这使得ajax和php文件之间的通信无法进行。我使用Dreamweaver,当我使用浏览工具时,它给了我一个文件的链接,但由于我的javascript是外部的,链接只是相对于Javascript文件,而不是主html文件。此外,当我仔细检查我的数据变量时,我错过了“&amp;”对于我在“uf”之前的字符串中的第二个变量

var url = "ajax.php";// i changed the path file to scripts/ajax.php and it worked like magic.
var vars = "ut="+title+"uf="+fname+"&ul="+lname+"&ue="+email+"&uloc="+loc+"&utp="+tp;// before
 var vars = "ut="+title+"&uf="+fname+"&ul="+lname+"&ue="+email+"&uloc="+loc+"&utp="+tp;// After

希望这对其他人有帮助。

尊敬并感谢大卫和汗。