JavaScript AJAX request saves to database but alerts failed

I have a bootstrap modal contact form which uses AJAX and PHP to save the information sent by a user to a database:

        <div class="modal fade" id="contact" role="dialogue">
    <div class="modal-dialog">
        <div class="modal-content">

            <div class="modal-body">
                <form id="myform" role="form">

                    <div class="form-group">

                        <label for="name">Name: </label>
                        <input type="name" name="name" class="form-control" id="name" >

                    </div>

                    <div class="form-group">

                        <label for="email">Email: </label>
                        <input type="email" name="email" class="form-control" id="email">

                    </div>

                    <div class="form-group">

                        <label for="msg">Message: </label>
                        <textarea class="form-control" name="msg" id="msg" rows="10"></textarea>
                    </div>

                    <!-- <a class="btn btn-primary" data-dismiss="modal">Close</a> -->
                    <button id="sub" type="submit" name="submit" class="btn btn-default">Submit</button>

                </form>
            </div>
        </div>
    </div>
</div>

When I submit the form the page alerts that the AJAX request has failed but yet the information still saves to the database!? anybody know where I'm going wrong, I have attached my script.js and send.php file below:

Javascript/Ajax file:

$(document).ready(function(){
$('#myform').submit(function(){

    $.ajax({
        type: 'post',
        url: 'send.php',
        dataType: 'json',
        async: true,
        data: $('#myform').serialize(),
        success: function(msg){
            alert("It was a success");
            return false;

        },
        error: function(jqXHR, textStatus, errorThrown){
            alert("Fail");
            console.log(jqXHR + '-' + textStatus + '-' + errorThrown);
            return false;
        }
    });
});
});

PHP file for processing and saving to DB

<?php

include 'connect.php';

if(isset($_POST['name'])&&($_POST['email'])&&($_POST['msg']))
{
$sql = "INSERT INTO details (name, email, message) VALUES (:Name, :Email, :Msg)";

$stmt = $pdo->prepare($sql);

$stmt->bindParam(':Name', $_POST['name'], PDO::PARAM_STR);
$stmt->bindParam(':Email', $_POST['email'], PDO::PARAM_STR);
$stmt->bindParam(':Msg', $_POST['msg'], PDO::PARAM_STR);

$stmt->execute();

echo "done";

}else{

echo "Nothing posted";

}

?>

P.S No errors are output to the console, just the alert saying failed.

Answer:1

As Luis suggests, try to add proper header to the php file which saves to the database and make the output json object like so:

<?php

include 'connect.php';

//The json header
header('Content-type: application/json');
header("Content-Disposition: inline; filename=ajax.json");

if(isset($_POST['name'])&&($_POST['email'])&&($_POST['msg']))
{
    $sql = "INSERT INTO details (name, email, message) VALUES (:Name, :Email, :Msg)";

    $stmt = $pdo->prepare($sql);
    $stmt->bindParam(':Name', $_POST['name'], PDO::PARAM_STR);
    $stmt->bindParam(':Email', $_POST['email'], PDO::PARAM_STR);
    $stmt->bindParam(':Msg', $_POST['msg'], PDO::PARAM_STR);

    $stmt->execute();

    $result = array('success'=>true, 'message'=>'The data has been saved successfuly');

} else {
    $result = array('success'=>false, 'message'=>'Can\'t save the data');
}

//Also is a good practice to omit the php closing tag in order to prevent empty characters which could break the posted headers

echo json_encode($result);

I would use the following alias instead of $.ajax, but it's a personal preference:

$(document).ready(function(){
   $('#myform').submit(function(e){
       e.preventDefault(); //Prevent form submission, so the page doesn't refresh
       $.post('send.php', $(this).serialize(), function(response){
           console.log(response); //see what is in the response in the dev console
           if(response.success == true){
               //success action
               //...some code here...
           } else {
               //error action, display the message
               alert(response.message);
           }
       });
   });
});

Hope that helps

Answer:2

I learnt to write angular dependencies needed using the array notation, that way: var app = angular.module('MyApp', []); app.controller('MyCtrl', ['$scope', function($scope) { $scope.stuff = '...

I learnt to write angular dependencies needed using the array notation, that way: var app = angular.module('MyApp', []); app.controller('MyCtrl', ['$scope', function($scope) { $scope.stuff = '...

I have a controller with 2 scopes: app.controller('search', function($scope) { $scope.value1 = ''; $scope.value2 = 'Some text' + $scope.value1; } And an input field: <input type="text" ...

I have a controller with 2 scopes: app.controller('search', function($scope) { $scope.value1 = ''; $scope.value2 = 'Some text' + $scope.value1; } And an input field: <input type="text" ...

  1. angular update scope
  2. angular update scope variable
  3. angular update scope after ajax
  4. angular update scope value
  5. update angular scope from jquery
  6. angular refresh scope
  7. angular change scope variable
  8. angular refresh scope value
  9. angular change scope variable in html
  10. angular refresh scope variable
  11. angular change scope
  12. angular change scope variable in directive
  13. angular change scope outside controller
  14. angular change scope from outside
  15. angular change scope variable value
  16. angular change scope value
  17. angular 1 update scope
  18. angular update parent scope from child
  19. angularjs update scope
  20. angular force update scope variable

I am attempting to create a global array in javascript to use in multiple functions. The array does not display when attempting to callback. var iListCount = 0; var arrListItems = new Array; ...

I am attempting to create a global array in javascript to use in multiple functions. The array does not display when attempting to callback. var iListCount = 0; var arrListItems = new Array; ...

I'm currently working on a page that have one iframe and one script adding a menu bar. The iframe have a script which is long to load, and the other script for the menu have to be add dynamically ...

I'm currently working on a page that have one iframe and one script adding a menu bar. The iframe have a script which is long to load, and the other script for the menu have to be add dynamically ...

  1. jquery append script tag
  2. jquery append script to page
  3. jquery append script to div
  4. jquery append script tag to head
  5. jquery append script and execute
  6. jquery append script
  7. jquery append script not working
  8. jquery append script src
  9. jquery append script async
  10. jquery append script tag to div
  11. jquery append script dynamically
  12. jquery append script to iframe
  13. jquery append script file
  14. jquery append script code
  15. jquery append external script
  16. jquery append run script
  17. jquery append html script
  18. jquery append inline script
  19. jquery append js script
  20. jquery dom append script