dsw7547 2016-04-23 22:08
浏览 29

Ajax-PhP通信

I am having a problem with a script i am programming. I am very new to AJAX, and can't figure out what i am doing wrong that makes it not to work. Any help would be highly appreciated. I have multiple forms on the page and when i separate the forms the communication between the Ajax and php works just fine. But when i put everything together, it stops working. I do believe its either a communication problem or maybe some conflicting scripts or just some bad coding.

Here is the php code:

@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>');
    }
}

Here is my AJAX codes:

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

And here is my html code:

<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条回答 默认 最新

  • douxian4888 2016-04-24 18:48
    关注

    Thank you David Lavieri and especially Sher Kahn. Your responses got me thinking and i finally figured out why I was not getting any response from my PhP script. As Khan also mention, I am just a hobby coder and you are absolutely right my code is not very clean. I cleaned the code on JSLint and realised i had too many bad coding habits. :). Thanks also for giving me a heads up with malsup query plugins. they are very handy and will help a lot.

    So finally to the problem I had. The actual problem was the link to the php file. The url was poorly defined which made it impossible for the communication between the ajax and the php file. I use Dreamweaver and when i used the browse tool it gave me a link to the file, but because my javascript was external, the link was only relative to the Javascript file, and not the main html file. Also when i double checked my data vars, i missed and "&" for my second variable in the string before "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
    

    Hope this can be of help to someone else.

    regards and thanks David and Khan.

    评论

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀