2014-01-22 5 views
0

나는 form.php 파일을 가지고 있습니다.이 파일은 성과 이름으로 데이터베이스를 검색하기위한 작은 양식을 가지고 있습니다. 양식은 JavaScript 함수를 사용하여 AJAX를 통해 search_name.php에 변수를 전송하고 mydatabase에서 쿼리 된 정보를 양식의 값으로 보냅니다.AJAX 양식을 사용하여 데이터베이스 업데이트

#result 요소의 양식에있는 정보를 검색 결과로 업데이트 할 수 있기를 원합니다.

AJAX를 통해 반환 된 양식이없는 작은 예제를 시도했지만 작동했지만 어떤 이유로 더 큰 프로젝트에서 수행 할 수 없습니다.

아무도 도와 줄 수 있습니까? 예제와 정보를 찾았지만 AJAX와 PHP를 처음 접했고 왜 이런 일이 일어나고 있는지 알 수 없습니다.

var vars = "firstname="+fn+"&lastname="+ln; 

"제출"을 포함하지 않는 당신의 PHP 스크립트 -이 :

search_name.php

<?php $form_profile = '<form method="POST" action=""><table width="450px"><tr><td><label for="firstname" >First Name: </label></td><td><input type="text" id="first_name" name="first_name" maxlength="50" size="30" value="'.$first_name.'"/></td></tr><tr><td><label for="lastname" >Last Name: </label></td><td><input type="text" id="last_name" name="last_name" maxlength="50" size="30" value="'.$last_name.'"/></td></tr><tr><td><label for="headline">Headline</label></td><td><input type="text" id= "headline" name="headline" maxlength="50" size="30" value="'.$profile_headline.'"/></td></tr></table><input type="submit" id="submit" name="submit" value="Save and Update"></form>'; ?> 

<?php 
//check if form has been submitted 
if(isset($_POST['submit'])){ 

    $first_name= $_POST['first_name']; 
    $last_name= $_POST['last_name']; 
    $headline= $_POST['headline']; 
    $summary= $_POST['summary']; 


    $title_array= $_POST['title']; 
    $company_array= $_POST['company']; 
    $start_month_array= $_POST['start_month']; 
    $start_year_array= $_POST['start_year']; 
    $end_month_array= $_POST['end_month']; 
    $end_year_array= $_POST['end_year']; 

    if($first_name && $last_name){ 
     //connect to server 
     $link = mysql_connect("localhost", "root", "########"); 

     if($link){ 
      mysql_select_db("mydatabase",$link); 
     } 


     //check if person exists 
     $exists = mysql_query("SELECT * FROM profile WHERE firstname = '$first_name' AND lastname = '$last_name'") or die ("The query could not be complete."); 
      if(mysql_num_rows($exists) != 0){ 
       //update 
       mysql_query("UPDATE profile SET headline='$headline' WHERE firstname = '$first_name' AND lastname = '$last_name'") or die("Update could not be applied"); 
       echo "Success!!"; 

}else echo "That alumni is not in the database"; 
}else echo "You must provide a first and last name."; 


} 

?> 
+0

위험 ** ** [** 기존 ** 데이터베이스 API] (http://stackoverflow.com/q/12859942/19068)를 사용하고 있으며 [최신 대체] (http : //)를 사용해야합니다. php.net/manual/en/mysqlinfo.api.choosing.php). 또한 [SQL 주입 공격] (http : // bobby-tables)에 취약합니다.co.kr /) ** 현대 API를 사용하면 [방어] (http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php)를 쉽게 할 수 있습니다. – Quentin

답변

0
여기

자바 스크립트

<script language="JavaScript" type="text/javascript"> 
    function ajax_post(){ 
     var fn = document.getElementById("first_name").value; 
     var ln = document.getElementById("last_name").value; 
     var errorMsg =""; 
     if (fn==null || fn==""){ 
      errorMsg +="Enter First Name \n"; 
      document.getElementById("first_name").focus(); 
     }  
     if (ln==null || ln==""){ 
      errorMsg +="Enter Last Name \n"; 
      document.getElementById("last_name").focus(); 
     }  
     if(errorMsg != ""){ 
      alert(errorMsg); 
      document.getElementById("first_name").focus(); 
      return false;  
     }else{ 
      // Create our XMLHttpRequest object 
      var hr = new XMLHttpRequest(); 
      // Create some variables we need to send to our PHP file 
      var url = "search_name.php";   
      var vars = "firstname="+fn+"&lastname="+ln; 
      hr.open("POST", url, true); 
      // Set content type header information for sending url encoded variables in the request 
      hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
      // Access the onreadystatechange event for the XMLHttpRequest object 
      hr.onreadystatechange = function() { 
       if(hr.readyState == 4 && hr.status == 200) { 
        var return_data = hr.responseText; 
        document.getElementById("result").innerHTML = return_data; 
       } 
      } 
      // Send the data to PHP now... and wait for response to update the status div 
      hr.send(vars); // Actually execute the request 
      document.getElementById("result").innerHTML = "processing...";   
     } 
    } 
</script> 
</head> 
<body> 
    <div class="left" id="search"> 
     First Name: <input id="first_name" name="first_name" type="text" /> 
     <br /><br /> 
     Last Name: <input id="last_name" name="last_name" type="text" /> 
     <br /><br /> 
     <input name="myBtn" type="submit" value="Search" onClick="javascript:ajax_post();return"> 
     <br /><br /> 
    </div> 
    <div id="result"></div> 

form.php 데이터 검색이 필요하다. 여기에서 기본은 : - 당신은 당신의 바르 변수의 끝에 +"&submit=true"를 추가하는 경우

if(isset($_POST['submit'])){ 

그래서, 주어진 문제를 해결해야한다.

var vars = "firstname="+fn+"&lastname="+ln+"&submit=true"; 

물론, 당신이 어떤 도움이다) = 당신의 PHP 스크립트로

희망을 정의되지 않은 인덱스 경고를 많이 처음에 전송되지 않은 다른 많은 변수를 찾습니다 볼 것이다!

+0

감사합니다. 많은 변수가 있지만 도움이되었습니다. 나는이 방법을 사용하지 않기로 결정했다. – user2687915

1

Timmy는 게시 된 값이 없습니다 (해당 게시물이 양식을 통해 실행 된 경우에만 자동으로 발생 함). 또한, 'firstname'을 보낼 때 $ _POST [ 'first_name']을 얻으려고합니다 (last_name과 lastname에 동일하게 적용됩니다).

JavaScript/AJAX로 작업 할 때 일종의 개발자 도구를 사용하는 것이 중요합니다. 개인적으로 Chrome 개발자 도구를 사용합니다 (Chrome에서 F12 키 누름 https://developers.google.com/chrome-developer-tools/). 이렇게하면 요청/응답이 실제로 어떻게 보이는지 표시되어 문제가 무엇인지 파악할 수 있습니다.

<?php 
//check if form has been submitted 
if(isset($_POST['firstname']) || isset($_POST['lastname'])){ 

    $first_name= $_POST['firstname']; 
    $last_name= $_POST['lastname']; 

    /* 
    $headline= $_POST['headline']; 
    $summary= $_POST['summary']; 
    $title_array= $_POST['title']; 
    $company_array= $_POST['company']; 
    $start_month_array= $_POST['start_month']; 
    $start_year_array= $_POST['start_year']; 
    $end_month_array= $_POST['end_month']; 
    $end_year_array= $_POST['end_year']; 
    */ 


    //connect to server 
    $link = mysql_connect("localhost", "root", "########"); 

    if($link){ 
     mysql_select_db("mydatabase",$link); 
    } 


    //check if person exists 
    $exists = mysql_query("SELECT * FROM profile WHERE firstname LIKE $first_name.'%' AND lastname LIKE $last_name.'%'") or die ("The query could not be completed."); 
    if(mysql_num_rows($exists) != 0){ 
     //update 
     //mysql_query("UPDATE profile SET headline='$headline' WHERE firstname = '$first_name' AND lastname = '$last_name'") or die("Update could not be applied"); 

     echo "Success!!"; 

    } else { 
     echo "That alumni is not in the database"; 
    } 
} else { 
    echo "You must provide a first and last name."; 
} 

?> 

내가 나쁜 변수 이름을 고정 순간에 보냈되지 않는 사람을 주석 : 프런트는이 일을 끝낼 것을 바탕으로, 나는 빨리 당신이 게시하는 PHP 스크립트를 다시 썼다. 검색을 위해 훨씬 더 나은 LIKE 문자열 비교 함수를 사용하도록 MySQL 쿼리를 업데이트했습니다. 누군가가 성을 알지 못하거나 부분 만 알면이 방법으로 조회를 마칠 수 있습니다. 문자열 비교 함수에 대한 자세한 내용은 http://dev.mysql.com/doc/refman/5.0/en/string-comparison-functions.html입니다. 코드를 복사하여 붙여 넣으면 문제가 해결 될 것입니다.

관련 문제