AJAX returns "success" function instead of "error" function

crinkledMap Source

When I run this script, instead of the error inserting HTML in the page, it returns an alert like the success function - but with the error message instead.

AJAX

$(function() {
 $('form').submit(function() {
    $page_title =  $('input[name="page_title"]').val();

    $.ajax({
        method: 'GET',
        url: 'test-script.php',
        datatype: 'jsonp',
        jsonp: 'jsonp_callback',
        data: {
            page_title: ($page_title),
        },
        success: function(result){
            alert(result);
        },

        error: function(result) {
            $('#error').html('result');
        }
    });
});

});

PHP

<?php
   if(isset($_GET)) {
      if (! empty($_GET['page_title'])) {
      $title = $_GET['page_title'];
      print $title;
   } else {
      $error = ('Name required');
      print $error;
   }
}
phpajax

Answers

answered 1 week ago Jeff #1

add a http_response_code(); to your php to tell js, that there was an error. Also you better should send back a json encoded error string, that can be understood by javascript.

<?php
   if(isset($_GET)) {
      if (! empty($_GET['page_title'])) {
      $title = $_GET['page_title'];
      echo $title;
   } else {
      http_response_code(400);
      $error = ["message"=>"Name required"];
      echo json_encode($error);
   }
}

See the list of appropriate response codes

EDIT:
Response to your comment "the HTML is inserted... then disappears"_: You need to prevent the form from beeing submitted. To do that add event.preventDefault() to your onSubmit handler:

 $('form').submit(function( event ) {
     event.preventDefault();
     // rest of your code...

comments powered by Disqus