I have a simple Ajax function:
insertInto = function(){
console.log("Hello ");
var power = $("#power").val();
var vehicle = $("#vehicle").val();
var sendData = { "power": power, "vehicle": vehicle };
$.ajax({
type: "POST",
contentType: "application/json",
dataType: "json",
url: "http://192.168.15.42//Test/www/insert.php",
data: sendData,
success: function(data) {
if(data){
alert("Successfully added!")
} else {
alert ("else!")
}
},
error: function(data) {
alert("error")
}
});
}
In insert.php
if I do:
<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
$data = ['status'=>'Ok'];
return json_encode($data);
?>
I get success and I get the Response {Status => Ok}
If I do:
<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
include('connect.php');
$power=$_POST["power"];
$vehicle=$_POST["vehicle"];
$sql = "INSERT INTO practicetbl (power,vehicle) VALUES ('$power' , '$vehicle')";
return json_encode($sql);
?>
I get the response but I get the error function.(the data is inserted).
And If I do:
<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
include('connect.php');
$data = ['status'=>'Ok'];
$power=$_POST["power"];
$vehicle=$_POST["vehicle"];
$sql = "INSERT INTO practicetbl (power,vehicle) VALUES ('$power' , '$vehicle')";
if ($conn->query($sql) === TRUE) {
$success = "New record created successfully";
echo json_encode($success);
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
return json_encode($sql);
?>
The data is inserted, but I don't get the response and my insert.php script is being cancelled in the console...
I Image the problem Is with JSON. But why is this happening if I am returning the JSON values?
Try this:
success: function(data) {
foobar(data);
},
//Place outside insertInto
function foobar(data) {
if(data){
alert("Successfully added!")
} else {
alert ("else!")
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.