2016-08-28 2 views
1

나는이 기능을 수행하는 간단한 작업 모델을 얻으려고 애썼다. 나의 실제 사이트는 더 크지 만, 간단하게 (그리고 문제를 해결하기 위해) 스크립팅을 무디게했습니다.Ajax에서 PHP로 삽입하기위한 폼

양식을 보내기 위해 클릭 할 때 "500"오류가 계속 발생하며 잘못된 것을 파악하지 못했습니다. (이 항목을 캡처하는 간단한 데이터베이스를 설정했습니다). (. PHP의 파일을 HTML이있는 같은 디렉토리 내에서 "sample2.php"라는)

내 데이터베이스의 스크린 샷 :

database screenshot

내 HTML 파일 :

<html> 
    <head> 
     <meta charset="utf-8"> 
     <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> 
    </head> 
    <body> 
     <div name="maindiv" id="maindiv"> 
      <span>sample1:</span> <input id="sample1" name="sample1" width="300px" type="text" value="sample1text" /><br /> 
     </div> 

     <input type="button" name="sendit" value="Do it" id="sendit"/> 

     <script language="javascript" type="text/javascript"> 
     $(document).ready(function(){ 

      $("#sendit").on("click", function() { 
       var fieldvalue = []; 

       $('#maindiv input').each(function() { 
        fieldvalue.push([this.id, $(this).val()]); 
       }); 

       console.log(fieldvalue); 

       $.ajax({ 
        url: "sample2.php", 
        type: "POST", 
        dataType: "json", 
        data: JSON.stringify(fieldvalue), 
        success: function() { 
         alert("worked"); 
        } 
       }); 
      });  
     }); 
     </script> 
    </body> 
</html> 

내 PHP 파일 :

,264,617,321 0
+0

는 왜 두 하나씩을 준비해야합니까 : 테스트 pursposes를 들어

는, 나는, JSON을 보내지 않도록 더-쉽게 console.log()에서 PHP의 문제를 해결 할 수있는 방법을 유혹 할 것인가? – Rasclatt

+0

그리고'$ query-> bindValue'는'$ query = $ pdo-> prepare ($ sql);을 실행하기 전에 이루어집니다. ' – Rasclatt

+0

오 사고 였을 것입니다. 고맙습니다! – MekLeN

답변

0

PHP가 섞여있는 것 같습니다. 간단히하기 위해이 작업을 시도해보십시오.

<?php 
$pdo = new PDO("mysql:host=extoleducation.ipagemysql.com;dbname=trialdb","username","password"); 

if(isset($_POST['sample1'])) { 
    $sql = "INSERT INTO `sampletable` (`sampleline`) VALUES (:sample1)"; 
    $query = $pdo->prepare($sql); 
    # I find binding values much easier just doing the array into the execute 
    # If you get it working like this and really want to go back and try 
    # bindValue(), you can 
    $query->execute(array(':sample1'=>$_POST['sample1'])); 
} 

이것은 기본적으로 사용됩니다. 이것이 작동하도록 만들 수 있다면, 당신은 그것의 종류를 만들 수 있습니다. 예기치 않은 SQL 오류 문제를 해결하려면 try/catchPDOException s 일 수 있습니다.

$(document).ready(function(){ 
    $("#sendit").on("click", function() { 
     // If you are not serializing, I would do an object, not array 
     var fieldvalue = {"action":"submit"}; 
     // Loop through and save names and values 
     $('#maindiv input').each(function(k,v) { 
      fieldvalue[$(v).attr('name')] = $(v).val(); 
     }); 

     $.ajax({ 
      url: "sample2.php", 
      type: "POST", 
      // Try just sending object here instead of json string 
      data: fieldvalue, 
      // On the success, add the response so you can see 
      // what you get back from the page 
      success: function(response) { 
       // Do a check to see if you get any errors back 
       console.log(response); 
       // This has minimal value because it is only telling you 
       // that the ajax worked. It's not telling you anything from the 
       // response of the page 
       alert("worked"); 
      } 
     }); 
    });  
}); 
+0

여러 필드/값의 경우 if 문 내에서 'isset'을 중첩 할 수 있습니까? 아니면 같은 isset()으로 쉼표를 사용할 수 있습니까? 아니면 단순히 배열을 모두 전달할 수 있습니까? 라이브 버전에 12 개의 필드가 있습니다. 정말 고마워요! 나는 이걸 줄거야. – MekLeN

+0

정말로 하나의 매개 변수 만 확인해도 충분하지만'execute()'에 전체 값 배열을 전달할 수 있습니다. – Rasclatt

+0

ajax에 대한 업데이트를했습니다. 시도해 볼 수도 있습니다. 만약 그렇다면 PHP에서'print_r ($ _ POST);'만 사용하여 페이지가 예상 한 것을 얻고 있는지 확인하십시오. 그러면 아약스 성공의'console.log'에 나타날 것입니다. – Rasclatt

관련 문제