mohammad haris
mohammad haris

Reputation: 145

Ajax post is returning error function on callback

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

Answers (1)

epascarello
epascarello

Reputation: 207511

Two things cause status=0

  1. Running on file protocol
  2. Ajax request is cancelled by navigation event

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

Related Questions