3

At the moment when I hover over any word a black box is always showing. If the PHP code returns text it is displayed in the black box (which it should). However I want it to return an error function if the text is not returned so I can then later change the CSS for the black box so that it has a width of 0px instead of 400px.

var x = ($(this).text());
$.ajax({
    type: 'POST',
    url: 'process.php',
    data: { text1: x },
    success: function(response){
        $('#tooltip').text(response);
    }
});
try 
{
    $db = new PDO('sqlite:ordbas.db');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);  
} catch(PDOException $err)
{
    echo "PDO fel $err";
}

if (isset($_POST['text1'])) {
    $text1 = $_POST['text1'];
    $results = $db->prepare("SELECT forord FROM words WHERE sokord='$text1'");
    $results->execute();
    $row = $results->fetch();
    echo $row[0];
}       

As you might have figured out there is some non-important code that I left out. I hope someone can understand and help me! Thanks!

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Aplex
  • 162
  • 2
  • 3
  • 11
  • 3
    **Danger**: You are **vulnerable to [SQL injection attacks](http://bobby-tables.com/)** that you need to [defend](http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php) yourself from. – Quentin May 17 '16 at 11:59
  • I am aware, but at this point I just want this section of code to be fixed, thanks! – Aplex May 17 '16 at 12:01

7 Answers7

15

Here is exactly how you can do it :

The Very Easy Way :

IN YOUR PHP FILE :

if ($query) {
    echo "success"; //anything on success
} else {
    die(header("HTTP/1.0 404 Not Found")); //Throw an error on failure
}

AT YOUR jQuery AJAX SIDE :

var x = $(this).text();
$.ajax({
    type: 'POST',
    url: 'process.php',
    data: { text1: x },
    success:function(data) {
        alert(data); //=== Show Success Message==
    },
    error:function(data){
        alert("error occured"); //===Show Error Message====
    }
});
Umair Shah
  • 2,305
  • 2
  • 25
  • 50
  • @Aplex : No Problem..Glad I could help..! :D – Umair Shah May 17 '16 at 13:37
  • Good start. Wondering if we can specify some string or code of some sort to pass on details about the error. We can echo the errors in PHP, but how to pass that message to AJAX while still triggering error, and not 'success'? – CodeFinity Apr 27 '17 at 23:00
  • @VisWebsoft : I think that simply that would not be possible but still might be possible with some complex method (I am not sure) but for easiness you can take a look at the following question as : http://stackoverflow.com/questions/14442265/jquery-ajax-custom-error-handler – Umair Shah Apr 28 '17 at 12:55
  • @UmairShahYousafzai Yeah, got it figured out enough, at least. I just needed to put error code 4xx or 5xx in header.response, and then check that on Ajax side with something like: response.responseText, which is the 'echo' statement generated on PHP side in case of error code. – CodeFinity Apr 29 '17 at 17:34
4

First, you need to let know javascript there was an error on server side

try 
{
    $db = new PDO('sqlite:ordbas.db');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);  
} catch(PDOException $err)
{
    // Set http header error
    header('HTTP/1.0 500 Internal Server Error');
    // Return error message
    die(json_encode(array('error' => 'PDO fel '.$err->getMessage())));
}

Second, you need to handle error while loading json

var x = ($(this).text());
$.ajax({
   type: 'POST',
   url: 'process.php',
   data: { text1: x }
})

// This will be called on success 
.done(function(response){
   $('#tooltip').text(response);
})

// This will be called on error
.fail(function(response){
  // Error catched, do stuff
  alert(response);
});
Buksy
  • 11,571
  • 9
  • 62
  • 69
3

The fail callback within $.ajax is used for capturing any failing results.

show/hide the error div based on success/failure returned from server script.

HTML CODE:

     <div class="error"><div>

CSS:

 .error {
      color: red;
 }

JS CODE:

//hide error before ajax call
$('.error').hide(); 
$.ajax(...)
  .done:function(){
       ...
  }
  .fail: function(jqXHR, textStatus, errorThrown){
     $('.error').text(errorThrown); 
     $('.error').show();
  }

Note: .success() & .error() methods are deprecated from jquery 1.8 so avoid using them.

Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

dreamweiver
  • 6,002
  • 2
  • 24
  • 39
2

In your catch you could put

header('Content-type: application/json');
echo json_encode(array('Error' => 'PDO fel "$err"'));
Rob B
  • 31
  • 2
  • 5
1
$.ajax({
    url: "file_name.php",
    method: "POST",
    data: $("#form_id").serialize(),
    success: function () {
        alert("success"); //do something
    },
    error: function () {
        alert("doh!"); // do something else
    }
});

This is an example for POST requests dealing with sensitive form data (or data that you'll bind to a UPDATE or INSERT query, for example). I included the serialize() function in order to handle the name fields from the form on your back end. I also removed passing the data through the success function. You don't want to do that when dealing with sensitive data or data you don't plan on displaying. Figured I would post this here since this thread came up when I searched how to do a POST with AJAX that returns an error.

Speaking of returning an error, you'll want to do this instead now that PHP has updated again. I also recommend reading through 5.4+ docs.

http_response_code(404);
die();

I threw in a die() function to make sure nothing else happens after you request your 404.

0

Try with the following snippet instead:

var x = ($(this).text());
$.ajax({
    type: 'POST',
    url: 'process.php',
    data: { text1: x },
    success: function(response){
        $('#tooltip').text(response);
    },
    error: function(error) {
        console.log(error);
    }
});
Azenis
  • 77
  • 1
0

Use the PHP function json_encode on an array. The array will then be presented to javascript as a JSON object (the 'response' argument/parameter).

In other words:

PHP:

// important to tell your browser what we will be sending
header('Content-type: application/json; charset=utf-8');

... bla bla code ...

// Check if this has gone right
$success = $results->execute();
$row = $results->fetch();
$html = $row[0];

$result = [
    'success' => $success,
    'html' => $html,
];

print json_encode($result);

JavaScript:

// You may now use the shorthand
$.post('process.php', { text1: x }, function(response) {
    if (response.success) {
        $('#tooltip').text(response.html);
    } else {
        ... show error ...
    }
});
Raphioly-San
  • 403
  • 3
  • 10