2014-02-12 5 views
0

나는 비슷한 질문을 많이 찾고 있지만 내 문제를 해결하기위한 답을 찾지 못했다.

나는 $ .ajax 함수를 사용하여 MySQL 데이터베이스에 데이터를 삽입하려고합니다.

양식 (form.php), 데이터 삽입 스크립트 (insert.php) 및 스크립트 update.js를 사용하여 데이터 삽입을위한 아약스 호출 (insert.js ...이어야 함)을 사용합니다. 하지만 신경 쓰지 ...) 여기

내 form.php입니다 :

<?php //form.php 
//script con un formulario 
//conexion a la BD: 
include_once 'connect.php'; 
?> 
<!DOCTYPE html> 
<html lang="es"> 
<head> 
<?php 
    header('Content-Type: text/html; charset=UTF-8'); 
?> 
<script type="" src="jquery-1.11.0.min.js"></script> 
<script type="" src="jquery-1.10.2.js"></script> 
<script type="" src="update.js"></script> 
</head> 
<body> 
    <header> 
     <h3>Ejemplo de forma para actualizar datos con ajax</h3> 
    </header> 
    <nav> 
     <h3>This is the nav area</h3> 
    </nav> 
    <section> 
     <form action="insert.php" name="myform" id="myform"> 
      <fieldset> 
      <legend> Insert new data:</legend> 
      <label for="name"> Name: <input type="text" id="name" name="name"> </label> <br> 
      <label for="age"> Age: <input type="number" id="age" name="age"> </label> <br> 
      <label for="company"> Company: <input type="text" id="company" name="company"></label> <br> 
      <label for="submit"><input type="submit" value="save" id="submitButton" name="submitButton"></label> 
      </fieldset> 
     </form> 
     <div id="msg"></div> 
    </section> 
</body> 
</html> 

그리고 여기 insert.php입니다 :

<?php //insert.php 
//script to insert data (sent via ajax) into database 
//conexion a la BD: 
include_once 'connect.php'; 
if(isset($_POST) && !empty($_POST)){ 
    //process data 
    $name=$_POST['name']; 
    $age=$_POST['age']; 
    $company=$_POST['company']; 
    if(mysql_query("INSERT INTO people (name,age,company) VALUES('$name',$age,'$company')")){ 
     echo '<p style="color: green;">Data inserted successfully!</p>'; 
    } else{ 
     echo '<p style="color: red;">There has been an error: <b>'.mysql_error().'</b></p>'; 
     die(mysql_error()); 
    } 
} else{ 
    echo '<p style="color: red;">No data received :(</p>'; 
} 
?> 

그리고 마지막으로 여기 내의 .js 코드를 업데이 트입니다 .js :

$(document).ready(function(){ 
    $('#submitButton').on('click', function(){ 
     //retrieving the data submitted: 
     var name = $('#name').val(); 
     var age = $('#age').val(); 
     var company = $('#company').val(); 
     alert('The following data is about to be sent: 1) Name: '+ name + '. 2)Age: '+ age + '. 3)Company: '+ company); 
     $.ajax({ 
      url: 'insert.php', 
      type: 'POST', 
      data: { 
       name: name, 
       age : age, 
      company : company 
      }, 
      'beforeSend':function(){ 
       alert('Ya los voy a enviar, eh?'); 
      }, 
      'success': function(result){ 
       $('#myform').hide(); 
       $('#msg').html(result); 
       alert('Success!'); 
      }, 
      'error': function (xhr, ajaxOptions, thrownError) { 
     alert(xhr.status); 
     alert(thrownError); 
      } 
     });//end of ajax 
    }); 
}); 

코드가 잘못되었습니다. 나는

+0

가 특정되어있는 버튼을 클릭 메소드가 호출되는 것을? – steinmas

+0

그래, 아약스가 각 변수의 데이터를 검색했다는 경고를 받는다. – Pathros

답변

0

당신은 귀하의 게시물 데이터 변수의 이름으로, 양식에서 변수의 값을 전송하고 있습니다. 랩 따옴표는해야한다! 그것이 작동하는 :(

이 도와주세요 얻을 수 없다 문제가 해결

 data: { 
      'name' : name, 
      'age' : age, 
      'company' : company 
     }, 
+0

dataType을 잊지 마세요. – aerojun

+0

그것은 작동하지 않았다 :(인용 부호를 시도했지만 여전히 작동하지 않는다. 폼에서, 나는 action = ""(empty) 또는 action = "insert.php"을 남겨 둘지가 중요하다? – Pathros

+0

ajax가 실제 양식 작업을 가로 채기 때문에 아니요. –

0

이 양식이 줄을 추가합니다..

<form action="insert.php" name="myform" id="myform" method="POST"> 

당신은 데이터를 전송하는 양식에 사용되는 방법 당신은 기대 깜빡 POST를 내가 PHP와 GET 인 경우 기본값.

또한 <form>을 사용하는 경우에는 jQuery를 사용할 필요가 없습니다 (내가 볼 수있는 한). form.php :

<!DOCTYPE html> 
<html lang="es"> 
<head> 
<?php 
    header('Content-Type: text/html; charset=UTF-8'); 
?> 
<script type="" src="//code.jquery.com/jquery-1.10.2.min.js"></script> 
<script type="" src="update.js"></script> 
</head> 

<body> 
<header> 
    <h3>Ejemplo de forma para actualizar datos con ajax</h3> 
</header> 
<nav> 
    <h3>This is the nav area</h3> 
</nav> 
<section> 
    <form action="insert.php" name="myform" id="myform" method="POST"> 
     <fieldset> 
     <legend> Insert new data:</legend> 
     <label for="name"> Name: <input type="text" id="name" name="name"> </label> <br> 
     <label for="age"> Age: <input type="number" id="age" name="age"> </label> <br> 
     <label for="company"> Company: <input type="text" id="company" name="company"></label> <br> 
     <label for="submit"><input type="submit" value="save" id="submitButton" name="submitButton"></label> 
     </fieldset> 
    </form> 
    <div id="msg"></div> 
</section> 
</body> 
</html> 

JS :

$(document).ready(function() { 
$('#submitButton').on('click', function() { 
    //retrieving the data submitted: 
    var name1 = $('#name').val(); 
    var age1 = $('#age').val(); 
    var company1 = $('#company').val(); 
    alert('The following data is about to be sent: 1) Name: ' + name1 + '. 2)Age: ' + age1 + '. 3)Company: ' + company1); 
    $.ajax({ 
     url: 'insert.php', 
     type: 'POST', 
     data: { 
      name: name1, 
      age: age1, 
      company: company1 
     }, 
     'beforeSend': function() { 
      alert('Ya los voy a enviar, eh?'); 
     }, 
     'success': function(result) { 
      $('#myform').hide(); 
      $('#msg').html(result); 
      alert('Success!'); 
     }, 
     'error': function(xhr, ajaxOptions, thrownError) { 
      alert(xhr.status); 
      alert(thrownError); 
     } 
    }); //end of ajax 
}); 
}); 
+0

오 그래, 내가 작동 및 메서드를 설정할 때 잘 작동하지만 ... 아약스는 여기에 할 일이 없다 ... 나는 상쾌하게하지 않고 데이터를 삽입하고 싶다 ... 그것이 내가 정말로 원하는 것이다. $ .ajax의 '성공'부분은 절대로로드되지 않습니다. – Pathros

+0

양식을 제거하고 내용을 그대로두고 사용해보십시오. 무슨 일이 일어나는 지 말해봐. – aerojun

관련 문제