나는 비슷한 질문을 많이 찾고 있지만 내 문제를 해결하기위한 답을 찾지 못했다.
나는 $ .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
});
});
코드가 잘못되었습니다. 나는
가 특정되어있는 버튼을 클릭 메소드가 호출되는 것을? – steinmas
그래, 아약스가 각 변수의 데이터를 검색했다는 경고를 받는다. – Pathros