2016-12-16 4 views
1

Я хочу вставить данные из формы в базу данных с помощью ajax. Когда я запускаю его, он отображает только код index.php и ничего не делает. Я не могу узнать об ошибке. Поэтому, пожалуйста, помогите мне запустить этот код.Вставить в базу данных MySql с помощью ajax

index.php

<!doctype html> 
<html> 
<head> 
<meta charset="utf-8"> 
<title>Untitled Document</title> 

</head> 

<body> 
<input type="text" id="name" placeholder="Enter Text"> 
<button id="submit" onClick="js()" type="button"> Submit</button> 

<script> 
function js() { 

var name = document.getElementById("name").value ; 


$.ajax({ 

type:'POST', 
data: name, 
url:"insert.php", 
success:function(result){ 
alert(success); 
} 

}); 
} 

</script> 
</body> 



</html> 

insert.php

<?php 
$connection = mysqli_connect('localhost', 'root', '', 'sample'); 
if($_POST['name']){ 
$name=$_POST['name']; 
$q= "insert into test ('$name')"; 
$query = mysqli_query($connection, $q); 
if($query){ 
echo 'inserted'; 
} 
} 
?> 
+0

Какова структура вашей таблицы для 'test'? Если указано более одного столбца, вам нужно указать имя столбца. Вы также можете выполнить '$ query = mysqli_query ($ connection, $ q) или die (mysqli_error ($ connection));' to debug – Sean

+1

Вам нужно включить 'jquery' в ваш файл' index.php'. Один ресурс может быть [это] (https://developers.google.com/speed/libraries/#jquery) –

ответ

0

Если ваша структура таблицы, как указано ниже:

id int PK (Auto_increment) 
name varchar(30) not null 

Вы должны использовать следующий код:

index.php

<!doctype html> 
<html> 
<head> 
<meta charset="utf-8"> 
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> 
<title>Test</title> 
</head> 
<body> 
<input type="text" id="name" placeholder="Enter Text"> 
<button id="submit" onClick="js()" type="button"> Submit</button> 
<script> 
function js() 
{ 
    if(document.getElementById("name").value!="") 
    { 
     var name = document.getElementById("name").value ; 
     $.post("insert.php",{name:name},function(data){ 
      if(data) 
      { 
       alert(data); 
      } 
      else 
      { 
       alert("Cancel."); 
      } 
     }); 
    } 
    else 
    { 
     alert("Enter name."); 
     document.getElementById("name").focus(); 
    } 
} 
</script> 
</body> 
</html> 

insert.php

<?php 
    $connection = mysqli_connect('localhost', 'root', '', 'test'); 
    if($_POST['name']) 
    { 
     $name=$_POST['name']; 
     $q= "insert into test(name) values ('$name')"; 
     $query = mysqli_query($connection, $q); 
     if($query) 
     { 
      echo 'inserted'; 
     } 
     else 
     { 
      echo 'no inserted'; 
     } 
    } 
?> 

Если у вас есть какие-либо недоразумений, пожалуйста, дайте мне знать.

Благодаря ...

0

Try ниже ... Это может быть полезно для вас ..

<!doctype html> 
<html> 
<head> 
<meta charset="utf-8"> 
<title>Untitled Document</title> 
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> 
</head> 

<body> 
<input type="text" id="name" placeholder="Enter Text"> 
<button id="submit" onClick="js()" type="button"> Submit</button> 

<script> 
function js() { 

var name = $("#name").val(); 

$.ajax({ 

type:'POST', 
data: 'name='+name, 
url:"insert.php", 
success:function(result){ 
alert(success); 
} 

}); 
} 

</script> 
</body> 
</html> 

и PHP скрипт, как показано ниже.

<?php 
$connection = mysqli_connect('localhost', 'root', '', 'sample'); 
if($_POST['name']){ 
$name=$_POST['name']; 
$q= "INSERT INTO test (name) VALUES ('$name')"; 
$query = mysqli_query($connection, $q); 
if($query){ 
echo 'inserted'; 
} 
} 
?> 
Смежные вопросы