Меню

Ajax php как вернуть ошибку

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's user avatar

asked May 17, 2016 at 11:57

Aplex's user avatar

2

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====
    }
});

answered May 17, 2016 at 12:31

Umair Shah Yousafzai's user avatar

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);
});

answered May 17, 2016 at 12:39

Buksy's user avatar

BuksyBuksy

11.2k8 gold badges62 silver badges68 bronze badges

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.

answered May 17, 2016 at 12:12

dreamweiver's user avatar

dreamweiverdreamweiver

5,9842 gold badges27 silver badges39 bronze badges

In your catch you could put

header('Content-type: application/json');
echo json_encode(array('Error' => 'PDO fel "$err"'));

answered May 17, 2016 at 12:05

Rob B's user avatar

Rob BRob B

312 silver badges5 bronze badges

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.

answered Mar 6, 2017 at 21:45

Christopher Northcutt's user avatar

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);
    }
});

answered May 17, 2016 at 12:06

Azenis's user avatar

1

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 ...
    }
});

answered May 17, 2016 at 12:10

Raphioly-San's user avatar

I have a page powered with PHP and AJAX, when a user submits one of my forms I check for errors in the getData.php script.

This example is if the user submits the form with the default value I’m wondering if there is a way to pass back those errors or trigger the AJAX to fire an error if the user commits on or if I need to do error handling before the AJAX call

$('form').on('submit', function (e) {
    e.preventDefault();
    $.ajax({
        type: 'post',
        url: '_ajax/addData.php',
        data: $('form').serialize(),
        success: function () {
            $("input").val('Info Here');
            $("form").hide();
            reloadInfo();
        }
    });
});

PHP

$info = $_POST['info'];

if($info != 'Info Here') {
    $conn = mysqli_connect();
    $query = "INSERT INTO leads VALUES(0, '$companyName', 1, NOW(), 3)";
    $result = mysqli_query($conn, $query) or die ('Error Could Not Query');

    $id = mysqli_insert_id($result);
    header("Location: http://localhost/manage/info.php?id=$id");

    mysqli_close($conn);
} else { 
    echo '<script>alert("Error");/script>'
}

PART 2

asked Jan 5, 2014 at 20:13

user934902's user avatar

user934902user934902

1,1743 gold badges15 silver badges33 bronze badges

Javascript:

success: function (data) {
           if(!data.success) alert(data.errors); // Just for demonstration purposes
            $("input").val(data.errors);
            $("form").hide();
            reloadInfo();
        }

PHP:

header("Content-Type: text/json; charset=utf8");
if($info != 'Info Here') {
    $conn = mysqli_connect();
    $query = "INSERT INTO leads VALUES(0, '$companyName', 1, NOW(), 3)";
    $result = mysqli_query($conn, $query) or die ('Error Could Not Query');

    $id = mysqli_insert_id($result);
    header("Location: http://localhost/manage/info.php?id=$id");

    mysqli_close($conn);
} else { 
    echo json_encode(array("success" => false,"error" => "Some random error happened"));
}

answered Jan 5, 2014 at 20:18

Lorenz's user avatar

LorenzLorenz

2,1613 gold badges18 silver badges18 bronze badges

1

There are several issues with your code:

  • $companyName is not defined anywhere
  • You should use prepared statements instead of throwing data into your SQL query
  • You should put your entire AJAX PHP code inside one try..catch block
  • At the end of your AJAX PHP code, write something some JSON
  • I don’t get why you are trying to redirect an AJAX call, usually you’d tell the client to do the redirect.

For example, I would write your PHP code like so:

try {

    if(!isset($_POST['info']))
        throw new Exception('Post info was not set');

    $info = $_POST['info'];

    if($info == 'Info Here')
        throw new Exception('Invalid value for info');

    $conn = mysqli_connect();
    if(!$conn)
        throw new Exception('Database connection failure');

    $companyName = '?????';

    $query = 'INSERT INTO leads VALUES(0, ?, 1, NOW(), 3)';
    $stmt = mysqli_prepare($query);

    if(!$stmt)
        throw new Exception('Could not query database');

    mysqli_stmt_bind_param($stmt, 's', $companyName);
    mysqli_stmt_close($stmt);

    $id = mysqli_stmt_insert_id($stmt);

    mysqli_close($conn);

    echo json_encode(array(
        'success' => true,
        'new_id'  => $id,
    ));

}catch(Exception $ex){

    echo json_encode(array(
        'success' => false,
        'reason'  => $ex->getMessage(),
    ));

}

answered Jan 5, 2014 at 20:54

Christian's user avatar

ChristianChristian

27.2k16 gold badges108 silver badges153 bronze badges

Alternate Approach

HTML: place this paragraph tag where you want to display an error.

<p id="display_error"></p>

Ajax success call: change your Ajax code bit like…

success: function(response) 
{
      if((response !== "") && ($.isNumeric(response))) {
        {
         //redirect in ajax success
         location.href = "http://localhost/manage/info.php?id="+ response;
        } 
      else {
             //this will display the custom error.
             $("#display_error").html("<p>" + response + "</p>"); //output: something went wrong!
           }
 }

PHP

$info = $_POST['info'];

if($info != 'Info Here') {
    $conn = mysqli_connect();
    $query = "INSERT INTO leads VALUES(0, '$companyName', 1, NOW(), 3)";
    $result = mysqli_query($conn, $query) or die ('Error Could Not Query');

    $id = mysqli_insert_id($result);

    echo $id;

   //header("Location: http://localhost/manage/info.php?id=$id");

    mysqli_close($conn);
} else { 
    echo 'something went wrong!';
}

answered Jun 16, 2020 at 7:12

Ns789's user avatar

Ns789Ns789

5319 silver badges21 bronze badges

I have a page powered with PHP and AJAX, when a user submits one of my forms I check for errors in the getData.php script.

This example is if the user submits the form with the default value I’m wondering if there is a way to pass back those errors or trigger the AJAX to fire an error if the user commits on or if I need to do error handling before the AJAX call

$('form').on('submit', function (e) {
    e.preventDefault();
    $.ajax({
        type: 'post',
        url: '_ajax/addData.php',
        data: $('form').serialize(),
        success: function () {
            $("input").val('Info Here');
            $("form").hide();
            reloadInfo();
        }
    });
});

PHP

$info = $_POST['info'];

if($info != 'Info Here') {
    $conn = mysqli_connect();
    $query = "INSERT INTO leads VALUES(0, '$companyName', 1, NOW(), 3)";
    $result = mysqli_query($conn, $query) or die ('Error Could Not Query');

    $id = mysqli_insert_id($result);
    header("Location: http://localhost/manage/info.php?id=$id");

    mysqli_close($conn);
} else { 
    echo '<script>alert("Error");/script>'
}

PART 2

asked Jan 5, 2014 at 20:13

user934902's user avatar

user934902user934902

1,1743 gold badges15 silver badges33 bronze badges

Javascript:

success: function (data) {
           if(!data.success) alert(data.errors); // Just for demonstration purposes
            $("input").val(data.errors);
            $("form").hide();
            reloadInfo();
        }

PHP:

header("Content-Type: text/json; charset=utf8");
if($info != 'Info Here') {
    $conn = mysqli_connect();
    $query = "INSERT INTO leads VALUES(0, '$companyName', 1, NOW(), 3)";
    $result = mysqli_query($conn, $query) or die ('Error Could Not Query');

    $id = mysqli_insert_id($result);
    header("Location: http://localhost/manage/info.php?id=$id");

    mysqli_close($conn);
} else { 
    echo json_encode(array("success" => false,"error" => "Some random error happened"));
}

answered Jan 5, 2014 at 20:18

Lorenz's user avatar

LorenzLorenz

2,1613 gold badges18 silver badges18 bronze badges

1

There are several issues with your code:

  • $companyName is not defined anywhere
  • You should use prepared statements instead of throwing data into your SQL query
  • You should put your entire AJAX PHP code inside one try..catch block
  • At the end of your AJAX PHP code, write something some JSON
  • I don’t get why you are trying to redirect an AJAX call, usually you’d tell the client to do the redirect.

For example, I would write your PHP code like so:

try {

    if(!isset($_POST['info']))
        throw new Exception('Post info was not set');

    $info = $_POST['info'];

    if($info == 'Info Here')
        throw new Exception('Invalid value for info');

    $conn = mysqli_connect();
    if(!$conn)
        throw new Exception('Database connection failure');

    $companyName = '?????';

    $query = 'INSERT INTO leads VALUES(0, ?, 1, NOW(), 3)';
    $stmt = mysqli_prepare($query);

    if(!$stmt)
        throw new Exception('Could not query database');

    mysqli_stmt_bind_param($stmt, 's', $companyName);
    mysqli_stmt_close($stmt);

    $id = mysqli_stmt_insert_id($stmt);

    mysqli_close($conn);

    echo json_encode(array(
        'success' => true,
        'new_id'  => $id,
    ));

}catch(Exception $ex){

    echo json_encode(array(
        'success' => false,
        'reason'  => $ex->getMessage(),
    ));

}

answered Jan 5, 2014 at 20:54

Christian's user avatar

ChristianChristian

27.2k16 gold badges108 silver badges153 bronze badges

Alternate Approach

HTML: place this paragraph tag where you want to display an error.

<p id="display_error"></p>

Ajax success call: change your Ajax code bit like…

success: function(response) 
{
      if((response !== "") && ($.isNumeric(response))) {
        {
         //redirect in ajax success
         location.href = "http://localhost/manage/info.php?id="+ response;
        } 
      else {
             //this will display the custom error.
             $("#display_error").html("<p>" + response + "</p>"); //output: something went wrong!
           }
 }

PHP

$info = $_POST['info'];

if($info != 'Info Here') {
    $conn = mysqli_connect();
    $query = "INSERT INTO leads VALUES(0, '$companyName', 1, NOW(), 3)";
    $result = mysqli_query($conn, $query) or die ('Error Could Not Query');

    $id = mysqli_insert_id($result);

    echo $id;

   //header("Location: http://localhost/manage/info.php?id=$id");

    mysqli_close($conn);
} else { 
    echo 'something went wrong!';
}

answered Jun 16, 2020 at 7:12

Ns789's user avatar

Ns789Ns789

5319 silver badges21 bronze badges

Содержание

  1. Как на php вернуть конкретную ошибку при оправке формы Ajax?
  2. Вернуть ошибки из PHP через. AJAX?
  3. 4 ответа
  4. ajax, как вернуть сообщение об ошибке из файла PHP
  5. Очень простой способ:
  6. AJAX Request Handler with PHP
  7. Sending the Ajax Request
  8. Create the PHP Handler
  9. Include Necessary Files
  10. Handling Errors
  11. Complete the Front-End
  12. Finally.

Как на php вернуть конкретную ошибку при оправке формы Ajax?

Форма с помощью Ajax отправляет данные в send.php обработчик и он уже взаимодействует с БазойДанных.

Можно ли прямо в обработчике send.php указывать ошибки типа «Неверный логин» или «Неверный пароль» или сразу обе ошибки и отправлять их на текущую страницу с формой?
Чтобы с помощью JavaScript далее оформлять эти ошибки для пользователя.

Если да, то покажете пример?

Нашел только технологию — передача ошибки в заголовок, но таким образом можно передать только 1 ошибку, да и строго определенные ошибки, да и не безопасно это от инъекций.

Не могу понять, как вообще делают такое.
Неужели можно только ограничиваться обработчиком на текущей странице, где форма отправки данных там и обработчик.

Send.php (RedBean.php регистрация пользователя)

  • Вопрос задан более трёх лет назад
  • 1099 просмотров

Простой 8 комментариев

Вроде нашел, передача json в заголовок?

А как прочитать этот json с помощью js на странице с формой ?

И безопасна ли такая передача данных?

Это не совсем простая отправка формы Ajax + PHP

Код может выглядеть вот так:

И кстати как инструмент для просмотра запросов к серверу и ответов от сервера, можно использовать вкладку Network в DevTools браузер Google Chrome, ну и в других браузерах тоже есть такая вкладка

Сергей Хлопов, на экран не получается, только в консоль
пробывал document.write(response.messages_error);
document.writeln(response.messages_error);
alert(response.messages_error);

Сергей Хлопов, я создал в html пустой див и сделал так:

Высвечивается undefined почему-то

AJIEKC_10, Значит в response.messages_error нет сообщения. Попробуйте посмотреть что в этой переменной через console.log. Т.е:

  1. Написать в функции которая выполняется после успешной отправки ajax запроса: console.log(response);
  2. Выполнить действие в браузере что бы ajax запрос отправился;
  3. И затем смотрим что у нас вывелось на вкладке Console

Функция ajaxSend это я так понял какая-то пользовательская ? И внутри неё происходит ajax запрос верно ?

Сергей Хлопов, мы в обработчике делали encode_json;
когда я попробовал вывести response полностью своим последним методом у меня вышло отобразить этот json массив. Однако взять с него текст ошибки не получается. Через индексирование выходит брать лишь по букве)
а если так:

то отображается [object Object]

когда я попробовал вывести response полностью своим последним методом у меня вышло отобразить этот json массив. Однако взять с него текст ошибки не получается.

Предполагаю из-за того что в response ответ в формате строки. Т.е. не преобразовался в объект JavaScript, а по хорошему должен преобразоваться и далее нужно работали с объектом так все делают.
Что бы получился объект есть два способа:

  1. В настройках ajax запроса указать тип данных который ожидаете получить от сервера, к примеру в jQuery это dataType: ‘json’; (в ответ выше есть пример) см. документацию jQuery.ajax
  2. Либо уже после ajax запроса использовать метод JSON.parse(), что бы получить объект (как в коде который вы скинули выше)

Лучше конечно первый вариант, но я не знаю с помощью какой библиотеки вы отправляете ajax запрос.
Если второй вариант то можно сделать так:

Если используйте php код из моего ответа, то там могут быть возможно уязвимости какие нибудь, просто обращаю на это внимание, сам пока не силён в этом поэтому точно сказать не могу что и как

В общем я вчера смог-таки вывести это сообщение вот таким образом

Хоть и был исчерпан лимит бесполезных комментариев надеюсь они не будут таковыми и это кому-то пригодится)
Сергей Хлопов, спасибо за отклик и участие!

Источник

Вернуть ошибки из PHP через. AJAX?

Есть ли способ заставить PHP возвращать код ошибки AJAX, если PHP скрипт не удается? Я следил за учебником и набрал это для своего PHP:

И все было хорошо, пока я не понял, что это данные JSON. Есть ли способ вернуть ошибки с использованием стандартных $_POST и возвращенных данных HTML (как в случае запуска события jQuery AJAX error: ?

4 ответа

Я не знаю о jQuery, но если он различает успешные и неудачные (HTTP 200 OK vs. HTTP!= 200) запросы Ajax, вы можете захотеть, чтобы ваш PHP script ответил HTTP-кодом, не равным 200

попробуйте это. Надеюсь, поможет.

Для простой передачи данных с PHP на AJAX не всегда нужны коды кодирования Json или пары ключей. Его можно просто выполнить с помощью обработки строк.

Ниже приведен пример кода, объясняющего эту функциональность.

Этот код показывает, как ответ «успех» отправляется обратно в ajax, вызывающий php-код. Далее в ajax можно было бы сделать следующее, чтобы получить ответ.

Вышеупомянутая концепция может быть расширена, чтобы вернуть МНОГОЯЗЫЧНЫЕ ЦЕННОСТИ. Этот метод позволяет простой перенос данных с PHP на AJAX в строковый формат.

Мы должны следовать простому шагу, чтобы повторить все, что нам нужно отправить в ответ от php на ajax, разделенный уникальным разделителем.

Затем переменные данные в ajax могут быть просто извлечены, как в приведенном выше примере, и простую функцию типа

являясь переменной внутри ajax. Затем массив res может использоваться в js для любой цели.

Источник

ajax, как вернуть сообщение об ошибке из файла PHP

В тот момент, когда я наводил курсор на любое слово, всегда отображается черный ящик. Если PHP-код возвращает текст, он отображается в черном поле (которое должно быть). Однако я хочу, чтобы он возвращал функцию ошибки, если текст не возвращен, поэтому я могу позже изменить CSS для черного ящика, чтобы он имел ширину 0px вместо 400px .

Как вы могли подумать, есть какой-то неважный код, который я забыл. Надеюсь, кто-то может понять и помочь мне! Благодаря!

Вот как вы можете это сделать:

Очень простой способ:

В ВАШЕМ ФАЙЛЕ PHP:

В ВАШЕЙ jQuery AJAX SIDE:

$.ajax fail в $.ajax используется для сбора любых неудачных результатов.

показать / скрыть ошибку div на основе успеха / отказа, возвращенного из сценария сервера.

HTML-код:

CSS:

JS CODE:

Примечание. .success() & .error() устарели из jquery 1.8, поэтому не используйте их.

Уведомление об изнашивании: обратные вызовы jqXHR.success (), jqXHR.error () и jqXHR.complete () устаревают с jQuery 1.8. Чтобы подготовить код для их возможного удаления, вместо этого используйте jqXHR.done (), jqXHR.fail () и jqXHR.always ().

В вашем улове вы можете положить

Используйте функцию PHP json_encode для массива. Затем массив будет представлен javascript как объект JSON (аргумент / параметр ответа).

Во-первых , вам нужно сообщить javascript, что на стороне сервера произошла ошибка

Во-вторых , вам нужно обрабатывать ошибки при загрузке json

Это пример запросов POST, касающихся чувствительных данных формы (или данных, которые вы будете связывать с запросом UPDATE или INSERT, например). Я включил функцию serialize () для обработки полей имени из формы на вашем конце. Я также удалил передачу данных через функцию успеха. Вы не хотите этого делать, когда имеете дело с конфиденциальными данными или данными, которые вы не планируете отображать. Фигурированный, я бы опубликовал это здесь, так как этот поток появился, когда я искал, как делать POST с AJAX, который возвращает ошибку.

Говоря о возврате ошибки, вы захотите сделать это вместо этого, когда PHP снова обновится. Я также рекомендую читать через документы 5.4+.

Я бросил функцию die (), чтобы убедиться, что ничего не произойдет после запроса вашего 404.

Попробуйте вместо этого следующий фрагмент:

Источник

AJAX Request Handler with PHP

AJAX is a Web Technology to create asynchronous Web applications. AJAX allows web pages to communicate with the server behind the scenes. The web page can be updated dynamically without reloading.

In this tutorial, we will be discussing about how to write a PHP script to handle an ajax request and send a response back to the client. There are some tasks that handler should do.

  • Read input variables correctly
  • Handle errors
  • Do the process without any error
  • Send an appropriate response

This tutorial covers all of above steps with examples. I have separated the tutorial into subtopics for your ease.

  • Sending the Ajax Request
  • Create the PHP Handler
  • Include Necessary Files
  • Handling Errors
  • Complete the Front-end

Sending the Ajax Request

To perform an Ajax request, some javascript code must be implemented in the web page. But, I do not explain AJAX in Javascript deeply here. I assume that you have a basic knowledge on json too.

First, I’ve created a new page, index.html. I have written JS code in it to send an Ajax request to the server with some data. I have used pure javascript in the following example. If you like, you can use your desired JS library.

  • In first line of Javascript, I have initiated the XMLHttpRequest, which is the basis of Ajax.
  • Then I have declared the data variable to save the data that will be sent to the handler. Here I have set data variable to a URL string. If you use a library like jQuery, you can easily reach the target by just declaring an object.
  • Then, I have set the onreadystatechange method of XHR object.
  • Finally, I have opened the connection and sent the request to the server with data.

Later, I will explain more about how to handle the response and how to parse it as JSON.

Create the PHP Handler

Next, I have created the PHP handler, handler.php to handle the Ajax request. It will look like following.

Haha, it’s just a blank file. Jump to the next step!

Include Necessary Files

Now, I have included two files that I need in handler.php. First one is the autoload file to autoload class files. (If you are interested, you can follow our autoloading tutorial to learn more). The second one is the database connection file. You can include files according to your needs. I just included these files to show that you can include any php file that you need to execute. So, I won’t be using these files anymore hereafter in this tutorial.

Important!

When Ajax was introduced it was used with XML. But in the present, 99% of developers use JSON because it is lightweight and simple than XML. So, I’ll be working with JSON objects hereafter. There are two PHP functions to use to handle JSON objects: json_encode and json_decode . There’s no problem even you haven’t heard of those functions because it’s easy to understand.

There’s another problem! When the server sends a response in JSON format, server has to tell the browser that the response is in JSON format. So, it’s compulsory to add following code into every PHP script that handles Ajax requests.

However, It isn’t a good idea to add above code in each script. So, including is a great trick. Therefore, I have created ajax.inc.php to save that code as well as to include other files.

Then, I just have to include ajax.inc.php in my Ajax handlers. Let’s focus on handler.php again. It would be like following

Handling Errors

Handling errors is the most important part in the Ajax Handler. There are many ways to implement error handling. But, try-catch model is the best and the most efficient approach according to my personal experience. It’s pretty simple to use. I can send an error message to the client (or the browser) just with throwing an error in PHP after implementing this model. Let’s see how to implement it and response to error PHP catches in runtime.

  • First, I have included the files.
  • Then, wrapped all the code with a try block
  • PHP process goes inside the try block. You can throw a Exception in runtime with a message and an error code. (error code is optional). The catch block will catch any Exception, even it is thrown by a method inside a class.
  • I have used throw new Exception statement to throw errors. First parameter is the error message and the second one is the error code
  • After catching the thrown error, I have echoed a string that is encoded in JSON which is originally a PHP Array. I have separated the code into parts below to make it easier to understand.
  • First, I have created a key-value array which has 3 keys. First two are really important to show an error to the user in the browser and to browser to detect that the Ajax process wasn’t successful. I have set status to false, which will be used later in this tutorial in the front-end (Javascript). $e -> getMessage() returns the string that was defined in the throw statement. It will return an empty string if the string isn’t defined in the statement. Error code is optional to send to the browser, but you can make your application more organized by sending error codes. $e -> getCode returns the error code defined in the throw statement. The default value is 0.
  • Next, I have encoded the array in JSON format with json_encode function. That function returns a json encoded string that you don’t need to take care of. PHP makes it easy to encode and it’s really easy to decode it in Javascript too.
  • Next, I have echoed the json encoded string.
  • Finally, I have exited the script. You can add any code to do some task before you exit the script.

I know it’s a long tutorial, Let’s take a break! I have a question for you. Why do you exit the script just after finding an error on processing? Let me know your opinion by commenting below.

Okay. Next I’ll show you some examples on error handling in Ajax scripts. These are some common places that you might want to throw errors and exit the script.

1. On a Database Query Error2. On Invalid Input

You can use throw statement whenever you need to stop the process and send an error message to the browser.

So, I am going to finish my handler.php. It will throw an error if the request is a GET request.

Complete the Front-End

Let’s consider about our JS code again. The final code in index.html will be like following.

  • Mind that jsonParse() is not a native function. I have created it to parse JSON because Javascript engine throws errors if the string is not in the correct form. It has a in-built error handler. It returns the parsed object on success, otherwise false.
  • Then I have updated the onreadystatechange function to handle the response from the server.
  • I have assigned the variable json to save the return value of jsonParse function.
  • Next, It checks whether json variable is false. If it’s true, it checks whether the status sent by the server isn’t true. If any of those conditions are true, it will log an error to the console. You can even show the error to the user using DOM, if needed.
  • If json is true and status property of json is true process continues. Browser will alert the text in the code.

Finally.

Ajax is the best and most popular way to create a dynamic website. It is a must to have knowledge on how to create a PHP handler for Ajax requests, if you are a PHP developer. We have discussed about creating a PHP handler with examples. If you have any question to ask, feel free to comment below.

Источник

Для простой передачи данных из PHP в AJAX кодировка Json или пары ключ-значение не всегда необходимы. Это можно просто сделать, используя обработку строк.

Ниже приведен пример кода, объясняющий эту функцию.

    $ query = "ВЫБРАТЬ адрес электронной почты ИЗ логина WHERE email = '". mysqli_real_escape_string ($ conn, $ email). «'И пароль ='». mysqli_real_escape_string ($ conn, $ pass). "'"; $ result = mysqli_query ($ conn, $ query); $ row = mysqli_fetch_row ($ результат); $ row_cnt = mysqli_num_rows ($ результат); $ s_email = $ row [0]; если ($ row_cnt == 1) {$ response = "успех"; } else {$ response = "Недействительные учетные данные"; } $ conn-> close (); $ _SESSION ["email"] = $ s_email; echo $ response;

Этот код показывает, как ответ «успех» отправляется обратно в ajax, вызывая php-код. Далее в ajax для получения ответа можно сделать следующее.

    $ .ajax ({type: 'POST', data: {email: $ ('# email'). val (), password: $ ('# pass'). val ()}, url: 'login.php' , success: function (data) {if (data == 'success') {// значение, полученное с помощью php, может быть сохранено в переменной данных ajax window.location.assign ('upload.php');} else { предупреждение (данные);}}, ошибка: функция (xhr) {предупреждение ("ошибка");}});

Вышеупомянутая концепция может быть расширена для возврата НЕСКОЛЬКИХ ЗНАЧЕНИЙ. Этот метод позволяет просто передавать данные из PHP в AJAX в строковом формате.

Мы должны выполнить простой шаг — повторить все, что нам нужно отправить в качестве ответа от php на ajax, разделенное уникальным разделителем.

    echo $ response. #; echo $ email. #; echo $ password. #; echo "Привет". #; эхо "Мир";

Затем данные переменных в ajax можно было бы просто получить, как в приведенном выше примере, и простую функцию, например,

    var res = data.split ("#");

data, являясь переменной в ajax. Затем массив res можно использовать в js для любых целей.

В тот момент, когда я наводил курсор на любое слово, всегда отображается черный ящик. Если PHP-код возвращает текст, он отображается в черном поле (которое должно быть). Однако я хочу, чтобы он возвращал функцию ошибки, если текст не возвращен, поэтому я могу позже изменить CSS для черного ящика, чтобы он имел ширину 0px вместо 400px .

Как вы могли подумать, есть какой-то неважный код, который я забыл. Надеюсь, кто-то может понять и помочь мне! Благодаря!

Вот как вы можете это сделать:

Очень простой способ:

В ВАШЕМ ФАЙЛЕ PHP:

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

В ВАШЕЙ 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==== } }); 

$.ajax fail в $.ajax используется для сбора любых неудачных результатов.

показать / скрыть ошибку div на основе успеха / отказа, возвращенного из сценария сервера.

HTML-код:

  <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(); } 

Примечание. .success() & .error() устарели из jquery 1.8, поэтому не используйте их.

Уведомление об изнашивании: обратные вызовы jqXHR.success (), jqXHR.error () и jqXHR.complete () устаревают с jQuery 1.8. Чтобы подготовить код для их возможного удаления, вместо этого используйте jqXHR.done (), jqXHR.fail () и jqXHR.always ().

В вашем улове вы можете положить

 header('Content-type: application/json'); echo json_encode(array('Error' => 'PDO fel "$err"')); 

Используйте функцию PHP json_encode для массива. Затем массив будет представлен javascript как объект JSON (аргумент / параметр ответа).

Другими словами:

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 ... } }); 

Во-первых , вам нужно сообщить javascript, что на стороне сервера произошла ошибка

 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()))); } 

Во-вторых , вам нужно обрабатывать ошибки при загрузке 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); }); 
 $.ajax({ url: "file_name.php", method: "POST", data: $("#form_id").serialize(), success: function () { alert("success"); //do something }, error: function () { alert("doh!"); // do something else } }); 

Это пример запросов POST, касающихся чувствительных данных формы (или данных, которые вы будете связывать с запросом UPDATE или INSERT, например). Я включил функцию serialize () для обработки полей имени из формы на вашем конце. Я также удалил передачу данных через функцию успеха. Вы не хотите этого делать, когда имеете дело с конфиденциальными данными или данными, которые вы не планируете отображать. Фигурированный, я бы опубликовал это здесь, так как этот поток появился, когда я искал, как делать POST с AJAX, который возвращает ошибку.

Говоря о возврате ошибки, вы захотите сделать это вместо этого, когда PHP снова обновится. Я также рекомендую читать через документы 5.4+.

 http_response_code(404); die(); 

Я бросил функцию die (), чтобы убедиться, что ничего не произойдет после запроса вашего 404.

Попробуйте вместо этого следующий фрагмент:

 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); } }); 

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Aitecs 2016 ошибка sp02
  • Aisuite3 ошибка при выполнении приложения сервера progid aahm acpihmdata2