Karuppiah RK
Karuppiah RK

Reputation: 3964

how do get correct error message using ajax json

Here i'm storing span values into a database. It's working fine. I'm now facing a problem with ajax return error message. For example in my save.php code i changed my database table name sample to simple (i don't have a simple database table). In the mainpage I want to get the error message like "this simple database table name doesn't exists". But it always shows Data saved succesfully.

I've searched on some other sites. Some people say I should use json to get the proper error message. But, I don't how to do that. How do I get the correct error message using json and ajax? I think this is very simple. But, I'm new to ajax.

save.php

<?php
    include('config.php');
    $get = $_POST['content'];
    try
    {
        $stmt = $conn->prepare("INSERT INTO sample (divvalue) VALUES (?)"); 
        $conn->errorInfo();
        $stmt->bindParam('1', $get, PDO::PARAM_STR);
        $stmt->execute();
    }
    catch(PDOException $e)
    {
        'Error : ' .$e->getMessage();
    }
    if($stmt)
    {
        echo 1;
    }
?>

ajax.js

$(document).ready(function() {
  $("#save").click(function (e) {   
    var span_contents = $('#ele').html();
    $.ajax({
        url: 'save.php',
        type: 'POST',
        data: {
            content: span_contents
         },
      success: function(data){
            if(data == '1')
            {
                $('#status')
                .addClass('return')
                .html('Data saved succesfully')
                .fadeIn('fast')
                .delay(3000)
                .fadeOut('slow')
            }
            else
            {
                $('#status')
                .addClass('error')
                .html('Error occured')
                .fadeIn('fast')
                .delay(3000)
                .fadeOut('slow')
            }
        }   
     }); 
   });
});

mainpage.php

<span id="ele" class="ele" contenteditable >element</span>
<input type="button" id="save" value="save" />
<br />
<div id="status"></div>

Upvotes: 0

Views: 693

Answers (6)

Pranav C Balan
Pranav C Balan

Reputation: 115272

You can do it as follows using json data

PHP :

<?php
    include('config.php');
    $get = $_POST['content'];
    try
    {
        $stmt = $conn->prepare("INSERT INTO sample (divvalue) VALUES (?)"); 
        $conn->errorInfo();
        $stmt->bindParam('1', $get, PDO::PARAM_STR);
        $stmt->execute();
        if($stmt)
        {
            echo '{"status":1}';
        }
    }
    catch(PDOException $e)
    {
        echo '{"status":0,"Error" : "' .$e->getMessage().'"}';
    }

?>

JQUERY :

success: function(data){          
     $('#status')
        .addClass('return')
        .html(data.status?'Data saved succesfully':'Error'+data.Error)
        .fadeIn('fast')
        .delay(3000)
        .fadeOut('slow')          
},
dataType:'json'  

Upvotes: 1

Sherin Jose
Sherin Jose

Reputation: 2516

In your code i think every time it returns one. In your catch block you need to return another value like 0.

try
{
    if($stmt){
        echo "1";
    }
}
catch(PDOException $e)
{
    echo 'Error : ' .$e->getMessage();
}

Also you can add an error handler in ajax function like ,

$.ajax({
    success: function(data){
        if(data == '1')
        {
            $('#status')
            .addClass('return')
            .html('Data saved succesfully')
            .fadeIn('fast')
            .delay(3000)
            .fadeOut('slow')
        }
        else
        {
            $('#status')
            .addClass('error')
            .html('Error occured')
            .fadeIn('fast')
            .delay(3000)
            .fadeOut('slow')
        }
    },
    //another handlers and properties
    error:function(error){
        $('#status')
        .addClass('error')
        .html('Error occured')
        .fadeIn('fast')
        .delay(3000)
        .fadeOut('slow')
    }
});

Upvotes: 2

STEEL
STEEL

Reputation: 10107

Please update your code. It was ur PHP, which needs to echo on error too.

<?php
    include('config.php');
    $get = $_POST['content'];
    try
    {
        $stmt = $conn->prepare("INSERT INTO sample (divvalue) VALUES (?)"); 
        $conn->errorInfo();
        $stmt->bindParam('1', $get, PDO::PARAM_STR);
        $stmt->execute();
    }
    catch(PDOException $e)
    {
        echo 'Error : ' .$e->getMessage();
    }
    if($stmt)
    {
        echo 1;
    }
?>

And in your JavaScript too.

$(function() {
  $("#save").click(function (e) {   
    var span_contents = $('#ele').html();
    $.ajax({
        url: 'save.php',
        type: 'POST',
        data: {
            content: span_contents
         },
      error: function(data){//callback option is invoked, if the request fails.
            $('#status')
                .addClass('error')
                .html('Error occured')
                .fadeIn('fast')
                .delay(3000)
                .fadeOut('slow');
      },
      success: function(data){//callback option is invoked, if the request succeeds. 
            $('#status')
                .addClass('return')
                .html('Data saved succesfully')
                .fadeIn('fast')
                .delay(3000)
                .fadeOut('slow');
        }
     }); 
   });
});

Upvotes: 1

nani1216
nani1216

Reputation: 324

A Good standard way is to use JSON as below

catch
{
 echo {"status":"failure","message":"The Error message goes here"};
}
if($stmt)
{
 echo {"status":"success","message":"Data saved successfully"};
}

and in your ajax success function check like this

  dataType:'json',
 success: function(data){
            if(data.status == 'success')
            {
                // do the required
            }
           else{
                // do the required
           }
  }

You can add more variables as required like status and message in the return string

Upvotes: 0

Sai Avinash
Sai Avinash

Reputation: 4753

Please use the following syntax for your ajax call:

$.ajax({
        url: 'save.php',
        type: 'POST',
        data: {
            content: span_contents
         },
      success: function(data){
            if(data == '1')
            {
                $('#status')
                .addClass('return')
                .html('Data saved succesfully')
                .fadeIn('fast')
                .delay(3000)
                .fadeOut('slow')
            },
     error: function(data){
            alert('Your error message here');
        }

       }); 

When ever you get an error, the error callback of the jquery ajax call will be fired

Upvotes: 0

Allende
Allende

Reputation: 1482

I think

if($stmt)
{
    echo 1;
}

Always evalute to true, try (for test) to do echo "2" without modify anything else. Try also adding an echo in the catch block. Also you can check with the devTools in the network tab what does the response return.

Upvotes: 0

Related Questions