2011-10-31 2 views
3

내 웹 사이트에 설명 애플리케이션을 만들려고합니다. 데이터가 AJAX javaScript 파일에 "게시"되어도 제대로 삽입되지 않습니다. http://micromedia.vaniercollege.qc.ca/home/nortonb/php/mySQL PHP AJAX 데이터가 AJAX js 파일에서 삽입되지 않음

작품 : [email protected] 통과 :

당신은 이미 등록 된 사용자가 사용하여 댓글을 삽입 할 수 있습니다 다음은 메인 페이지입니다 SN (참고 : 경고 JS /은 ajax.js에서이다) 스루 comment_ins.php하는 정보를 전달

  • 은 JS /은 ajax.js 제출에
  • 을 파일에 포함 의견을 표시/comments.php을 dB로 메인 페이지에 포함 jax.js는

    <input name="submit" type="button" class="indent" value="add your comment" onclick="loadXMLDoc('db/comments_ins.php')">

가 작동하지 않습니다 파일 :

사용자의 이메일이 이름 및 성 입력을 가진 다른 양식을 표시 comment_ins.php DB를, 존재하지 않는 경우.

이것은 동일한 ajax.js 파일을 사용하지만 db/comments_add_user.php를 사용하여 새 사용자를 삽입 한 다음 관련 테이블에 주석을 삽입합니다.

(참고 : 매개 변수는은 ajax.js 파일에 전달되고 있지만 정보가 데이터베이스에 제출되지 않음)

나는 시도했다 : -hard dB/comments_add_user.php 작품의 데이터를 코딩

일반 양식에서 정보를 -passing하지만 여전히 사용 JS /은 ajax.js 사전에

http://micromedia.vaniercollege.qc.ca/home/nortonb/php/c_test.htm

감사를 작동합니다. 브루스 여기

내 index.php 파일의 배짱이다

<h4>Comments</h4> 
    <article id="comms"> 

    <form name="intro" action="" method="post"> 
     <fieldset> 
      <legend>Add your comment</legend> 
      <label for="comment"> 
       Comments:<br /><textarea name="comment" id="comment" cols="30" rows="5" class="indent"></textarea><br /> 
      </label> 
      <label for="email"> 
       Email:<br /><input name="email" id="email" type="text" size="32" class="indent"/> 
       <span id="emailMessage"></span> 
      </label><br /> 

      <label for="password"> 
       Password:<br /><input name="password" id="password" type="password" size="32" class="indent"/> 
       <span id="passwordMessage"></span> 
      </label><br /> 

       <input name="submit" type="button" class="indent" value="add your comment" onclick="loadXMLDoc('db/comments_ins.php')"> 

     </fieldset> 
    </form> 
    <?php include("db/comments.php"); ?> 

    </article> 

을 그리고 여기에 JS /은 ajax.js 파일입니다

여기
// JavaScript Document 
function loadXMLDoc(xmlDoc){ 
    var xmlhttp; 
    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("comms").innerHTML=xmlhttp.responseText; 
     } 
    } 


    var commentValue=encodeURIComponent(document.getElementById("comment").value); 
    var emailValue=encodeURIComponent(document.getElementById("email").value); 
    var passwordValue=encodeURIComponent(document.getElementById("password").value); 

    var parameters="comment="+commentValue+"&email="+emailValue+"&password="+passwordValue; 
    //if a new user then add these things 
    if(document.getElementById("firstName")){ 
     var firstNameValue=encodeURIComponent(document.getElementById("firstName").value); 
     var lastNameValue=encodeURIComponent(document.getElementById("lastName").value); 
     //parameters are formatted in name=value pairs 
     var parameters="firstName="+firstNameValue+"&lastName="+lastNameValue+"&comment="+commentValue+"&email="+emailValue+"&password="+passwordValue; 

    } 
    alert(xmlDoc + " parameters: "+parameters); 
    xmlhttp.open("POST", xmlDoc, true);//true = asynchronous 
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
    xmlhttp.send(parameters); 

} 

는 dB/comments_ins.php입니다 (괜찮아 보이는군요)

<?php 
    //comments_ins.php adds new comments to the database 
    //if the user has already registered, the comment is displayed 
    //else a form is displayed for new users keeping the comment and email from the original comment form 

    //to do list: 
    // ??? should I combine this into comments.php? 
    // ??? should I separate the forms into a separate .php file with a conditional for new users? 
    //fix scrolling issue? 
    //jQuery? AJAX? 
    include 'includes/mysqli_connect.php'; 
    //get the posted info 
    echo("comments_ins.php<br />"); 
    if(isset($_POST["comment"])){ 
     $password = trim($_POST["password"]); 
     $hashedPassword = hash(sha256,$password); 
     $email = trim($_POST["email"]); 
     $comment = trim($_POST["comment"]); 
     //see if user exists 
     $query = "select * from users where email = '$email' and password = '$hashedPassword' limit 1";//adding limit 1 speeds up the query on big tables 
     $result = mysqli_query($link, $query); 
     //get response from database  
     if($result = mysqli_query($link, $query)){ 
      $numrows = $result->num_rows; 
      //echo ('found '.$numrows.' user: <br>'. $firstName.'<br>'); 
      while ($row = $result->fetch_object()) {  
       $userArray[] = array('userID'=>$row->userID, 
        'firstName'=>$row->firstName, 
        'lastName'=>$row->lastName, 
        'email'=>$row->email 
       );//line breaks for readability 
      } 
      $verifiedUserID = $userArray[0]['userID'];//get userID for insert below 
      //echo("\$verifiedUserID: ".$verifiedUserID); 
     }else{ 
      // This means the query failed 
      echo("errr..."); 
      echo $mysqli->error; 
     } 

     //if the user already exists... 
     if($numrows > 0){//should add something if numrows > 1 i.e. for duplicate users!! 
      //echo("user is registered <br />"); 
      $commentQuery="INSERT INTO comments (comment, userID) VALUES ('$comment', '$verifiedUserID')"; 
      $commentResult = mysqli_query($link, $commentQuery); 
      //get response from database 
      $commentNum = mysqli_affected_rows($link); 
      echo(mysqli_error()); 
      //echo ('<br />inserted '.$commentNum.' record: <br />'. $comment.'<br />'); 
      include("comments.php"); 
     }else{//if the user does not exist 
      echo("Please register to display your comment: <br />"); 
      ?> 
      <form name="intro" action="" method="post"> 
       <fieldset> 
        <legend>Register to share your comment:</legend> 
         <label for="firstName"> 
         First Name: <br /> 
         <input name="firstName" id="firstName" type="text" class="indent" size="32" /> 
         <span id="firstMessage"></span> 
         </label> 
         <br /> 
         <label for="lastName"> 
         Last Name:<br /> 
         <input name="lastName" id="lastName" type="text" class="indent" size="32" /> 
         <span id="lastMessage"></span> 
         </label> 
         <br /> 
         <label for="email"> 
         Email:<br /> 
         <input name="email" id="email" type="text" size="32" class="indent" value="<?php echo($email); ?>"/> 
         <span id="emailMessage"></span> 
         </label> 
         <br /> 
         </label> 
         <label for="password"> 
         Password:<br /> 
         <input name="password" id="password" type="password" size="32" class="indent"/> 
         <span id="passwordMessage"></span> 
         </label> 
         <br /> 
         <label for="comment"> 
         Edit your comment?<br /> 
         <textarea name="comment" id="comment" cols="30" rows="5" class="indent"><?php echo($comment); ?></textarea> 
         </label> <br /> 
         <input name="submit" type="submit" class="indent" value="join us" onclick="loadXMLDoc('db/comments_add_user.php')"/> 
        <p class="note">(Of course we will keep your stuff private!!)</p> 
       </fieldset> 
      </form> 
     <?php 
     }//end else($numrows <=0) 

     //close connection 
     mysql_close($link); 
    } 
    ?> 

다음은 comments_add_user.php 파일입니다 (cal JS /은 ajax.js 파일에서 주도하지만 때이 문제가 지금 어디에와 조금 혼란 스러워요

<?php 
    include 'includes/mysqli_connect.php'; 
    //get the posted info 
    echo("hi mom"); 
    $firstName = $_POST["firstName"];//"Two";// 
    $lastName = $_POST["lastName"];//"Two";// 
    $password = $_POST["password"];//"Two";// 
    $hashedPassword = hash(sha256,$password); 
    $email = $_POST["email"];//"Two";// 
    $comment = $_POST["comment"];//"Two";// 
    echo($firstName." from comments_add_user.php<br>"); 

    //since email does not exist, 
     $query="INSERT INTO users (firstName, lastName, password, email) VALUES ('$firstName', '$lastName', '$hashedPassword', '$email')"; 
     $result=mysqli_query($link, $query); 
     //get response from database 
     $num= mysqli_affected_rows($link); 
     echo(mysqli_error()); 
     echo ('inserted '.$num.' record: <br>'. $firstName.'<br>'); 
    //** add error checking ?!? 

    //get the userID for the new user 
     $userQuery = "select userID from users where email = '$email' limit 1";//adding limit 1 speeds up the query on big tables 
     $userResult = mysqli_query($link, $userQuery); 

     //get response from database  
     if($userResult = mysqli_query($link, $userQuery)){ 
      $numrows = $userResult->num_rows; 
      echo ('found '.$numrows.' user: <br>'. $firstName.'<br>'); 
      while ($row = $userResult->fetch_object()) { 
       $userArray[] = array('userID'=>$row->userID);//line breaks for readability 
      } 
      $newUserID = $userArray[0]['userID'];//get userID for insert below 
      //echo("\$verifiedUserID: ".$verifiedUserID); 
     }else{ 
      // This means the query failed 
      echo("errr..."); 
      echo $mysqli->error; 
     } 

    //now insert the comment 
     $commentQuery="INSERT INTO comments (comment, userID) VALUES ('$comment', '$newUserID')"; 
     $commentResult=mysqli_query($link, $commentQuery); 
     //get response from database 
     $commentNum= mysqli_affected_rows($link); 
     echo(mysqli_error()); 
     echo ('inserted '.$commentNum.' record: <br>'. $comment.'<br>'); 


    echo('<br><a href="comments_display.php">display all comments</a><br />'); 
    //close connection 
    mysql_close($link); 

    ?> 
+0

멋진 SQL 삽입 구멍 ... 누군가가 서버를 통해 트럭을 몰고왔다면 수치 스러울 수 있습니다. –

+0

감사의 말 B. 나는 게시하기 전에 그들을 연결해야한다고 생각했다. –

+0

더 이상 트럭이 없습니다. 약간의 깎기 및 스트립을 추가했습니다. 이 작업이 완료되면 준비된 문장을 추가 할 계획을 세웁니다. 감사합니다. Mark B. –

답변

1

에서 호출 않습니다

그래서 내가 도울 수 그래서 나를 위해 일을 요약하자면 당신을해야 할 수도 있습니다 당신..그 외에는

, 난 당신이 <form name="intro" action="" method="post">

난 그냥 당신이이 권리를 가지고 있는지 확인하려면이 나타났습니다, action="" 실제로 index.php를 가리키는 및/comments_ins.php

I DB 정보하지 의미 그게 당신이 정말로하고 싶은 일인지 모르겠다. ...

EDIT : 무슨 일이 일어 났는지, 덧글 추가를 클릭하면, 등록 양식이 나타나고, 우리를 클릭하면 AJAX를 호출하지만 페이지는 다음과 같습니다. <input>submit whi이기 때문에 새로 고침되었습니다. 내가 그 변화를 한 후

<input name="submit" type="button" class="indent" value="join us" onclick="loadXMLDoc('db/comments_add_user.php')"/> 

는, 내가 : 채널은 당신이 그래서 당신의 페이지를 다시로드하게 클릭하면이 당신이 comment_ins.php에서 그 라인을 변경하는 것입니다 필요 ... 양식을 제출 것을 의미한다 추가 사용자 파일의 출력을 얻는 중 ...

+0

Thanks @DanyKhalife 문제는 사용자를 등록하려고 할 때 AJAX가 작동하지 않는다는 것입니다. 전자 메일 (및 암호)이 없거나 일치하지 않는 경우 새 양식이 db/comments_ins.php에 의해 작성됩니다. 올바른지 : action = ""은 index.php (또는이 경우 database.php 파일)을 가리 킵니다. onClick = "loadXMLDoc ('db/comments_ins.php') –

+0

이렇게하면 등록 양식이 나타나지만 사용자가"Join Us "를 클릭하면 아무 일도 일어나지 않습니다. EDIT : 내가 당신을 위해 그것을 디버깅하기 위해 내 서버에로드 할 것입니다 .. –

+0

괜찮아요, 내 대답을 업데이 트하면 그게 당신의 문제를 해결하고 경우에 그것을 투표를 알려주십시오 :) –