Reputation: 145
I am posting data using ajax to a page named working.php, data is being stored in database means everything is working fine but on the callback error function is thrown.
Here is the script:
<script>
$(document).ready(function(){
$('#testimonial_add').click(function(){
var nm=$('#name').val();
var message=$('#msg').val();
$.ajax({
type:'post',
url:'working.php',
data:{name:nm, msg:message},
success: function(html){
alert(html);
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
});
});
</script>
Working.php page
<?php
include('../function.php');
$name = $_POST['name'];
$message = $_POST['msg'];
if($name == null || $message == null){
echo 'All fields are required';
}
else{
$query = "INSERT INTO testimonials(testimonial_name,testimonial_text) VALUES ('".$name."','".$message."')";
dml($query);
echo 'Data has been inserted';
}
?>
In error function on alert textstatus is error and errorThorwn is empty alert box
Also can i give php function name in url of ajax
Here is the Dml function being called
function dml($query){
$db=mysqli_connect('localhost','root','','entrepreneurshipdp')
or die('not connected');
mysqli_query($db,$query);
mysqli_close($db);
}
Upvotes: 0
Views: 66
Reputation: 207511
Two things cause status=0
In your case, I doubt it is one. So it leaves the page navigating away. In your case what you are clicking is most likely submitting the form. Since you are not cancelling the default action of the click, the form is submitting and the killing the Ajax request off. So stop the default action from happening.
$('#testimonial_add').click(function(event){
event.preventDefault();
...
});
Or if you are using a submit button, change it to be a regular button and it will no longer submit the form.
Upvotes: 1