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.5k8 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

6,0022 gold badges24 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

jquery allows for success failure and error responses. How can i return a failure or error manually along with a string that describes the failuer or error?

asked Aug 25, 2010 at 20:23

John's user avatar

It has become somewhat of a convention to utilize a simple JSON envelope to report failures that occurred on the server side (that are not HTTP errors).

The flickr api provides a typical packaging example:

look at the bottom of this page for success and failure examples

So in the case of an Ajax call to the flickr API, in your success callback you would check the returning data for success/failure

$.ajax({   
  //...   
  success:   function(data) {
    if(data.stat == 'fail') {
       //data.code + data.message contain details that could be used here
    }
    else {
      //do success stuff here
    }
  }
});

answered Aug 25, 2010 at 20:50

Andrew Wirick's user avatar

The success and error callbacks that jQuery provides are for the XMLHTTPRequest object. The only way you would be able to use it is if your server returns an error code in the header of the HTTP response, which isn’t very common, so I wouldn’t recommend it. In short, the jQuery error function is for fatal errors, like the URL does not exist, or authentication required.

Any other errors that come up should either be handled on the server-side or the success function of the jQuery ajax call.

answered Aug 25, 2010 at 20:28

Sandro's user avatar

SandroSandro

4,7611 gold badge34 silver badges41 bronze badges

Привет!

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

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

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

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

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

Пример
Ajax

$("form").submit(function(e) {
            e.preventDefault();
                $.ajax({
                    type: "POST",
                    url: "send.php",
                    data: $(this).serialize()
                }).done(function() {
                    // если успешная отправка
                }).fail(function () {
                    // если ошибка отправки
                });
                return false;
            });

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

// Если такой логин есть, значит ошибка
if ( R::count('users', "login = ?", array($_POST['login'])) > 0)
{
// ХОТЯ И ВОЗНИКАЕТ ОШИБКА, AJAX ОТМЕЧАЕТ УСПЕШНУЮ ОТПРАВКУ. 
// КАК ЕЕ ОТПРАВИТЬ НА ТЕКУЩУЮ СТРАНИЦУ ?
$errors = 'Пользователь с таким Логином уже существует!';
} else
{
// Если логин уникальный - регистрируем юзера
$user = R::dispense('users');
$user->login = $_POST['login'];
$user->password = $_POST['password'];
R::store($user);
}

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

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

    $query = "SELECT email FROM login WHERE email = '". mysqli_real_escape_string($conn,$email) ."' AND password = '". mysqli_real_escape_string($conn,$pass) ."'" ;

    $result = mysqli_query($conn,$query);
    $row=mysqli_fetch_row($result);

    $row_cnt = mysqli_num_rows($result);
    $s_email = $row[0];

    if ($row_cnt == 1) {
        $response="success";
    } else {
    $response = "Invalid Credentials";
    }

    $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'){  //the value echoed from php can be stored in the data variable of ajax
                window.location.assign('upload.php');
            }
            else{
                alert(data);
            }
          },
          error: function ( xhr ) {
            alert("error");
        }
    });

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

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

    echo $response.#;
    echo $email.#;
    echo $password.#;
    echo "Hello".#;
    echo "World";

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

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

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

Содержание

  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.

Форма с помощью 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); } }); 

Возможно, вам также будет интересно:

  • Ajax error вывод ошибок
  • Aitecs 2016 ошибка sp04
  • Aitecs 2016 ошибка sp02
  • Aisuite3 ошибка при выполнении приложения сервера progid aahm acpihmdata2
  • Aisuite3 exe ошибка приложения

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

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