0

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;
   }
}
crinkledMap
  • 1,192
  • 1
  • 8
  • 8
  • 1
    your php script doesn't tell js that there is an error. – Jeff Jun 13 '18 at 22:26
  • ajax would encounter an error with a header sent other than 200 (basicly). But til now php sends nothing else but a status code 200 (by default, if no real error occurres). Look at [header](http://php.net/manual/en/function.header.php) and here: https://stackoverflow.com/questions/3258634/php-how-to-send-http-response-code?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – Jeff Jun 13 '18 at 22:28
  • Possible duplicate of [PHP: How to send HTTP response code?](https://stackoverflow.com/questions/3258634/php-how-to-send-http-response-code) – William Perron Jun 13 '18 at 22:57
  • You should send back a 400 as response code as `bad request` so that frontend can identify that an error has occured. – Yousaf Hassan Jun 13 '18 at 22:57

1 Answers1

2

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...
Jeff
  • 6,895
  • 1
  • 15
  • 33