Check with jquery if the result / echo from PHP starts with "abc"

I use jquery and ajax to submit forms without reloading the page, and then depending on the result (whether it is success or error). I am printing a message in two different divs. Since success and error in ajax only checks the client / server connection, I repeat some things from PHP when the request completes successfully, and depending on what I determine what to do with the message. The jquery / ajax part looks like this (usually I use two different divs, but I will use warnings to simplify the example):

success: function (result) { if (result == 'success') { alert("Success!"); } else { alert("There was an error."); } }, 

This works fine, but I would like to improve its usability.

Now the question arises: can I use something like str.match in the if (result == part? For example, if I had some problems running the request, I would echo in php echo "Error: >error description here<"; Could Am I somehow using str.match(/^Error/) in my if condition and echo the whole message?

+6
source share
3 answers

Do not use string matching for this task. Use HTTP Response Codes - What You Need! The http_response_code function in PHP is for this purpose:

 <?php if ( /* error condition */ ) { http_response_code(400); // "Bad request" response code echo 'Invalid parameters'; } else { echo 'Success'; // response code is 200 (OK) by default } 

Then you can use jQuery done and fail callbacks to handle two cases separately:

 $.ajax(url, params) .done(function(response) { alert('all good: ' + response); }) .fail(function(response) { alert('error: ' + response); }) 
+19
source

To check if message starts with Error: you can use indexOf :

 if (result.indexOf('Error:') === 0) { // Starts with `Error:` } 

indexOf will return index starting at 0 , where Error: is on the line result .

Link: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf

The indexOf() method returns the index in the String calling object of the first occurrence of the specified value, starting the search from fromIndex. Returns -1 if the value is not found.

+8
source

to answer the β€œimprove” part of your question, I would do some JSON.

PHP:

// Your code is here and create an associative array as follows:

 if($errors){ $data( 'results'=>'errors', 'message'=>'it failed' ); }else{ $data( 'results'=>'success', 'message'=>'it worked' ); } echo json_encode($data); 

and then your js will be something like this:

 success: function (result) { if (result.results == 'success') { alert(result.message); } else if (result.results == 'errors' { alert(result.message); } }, 

linked: http://www.dyn-web.com/tutorials/php-js/json/array.php#assoc

+2
source

Source: https://habr.com/ru/post/989110/


All Articles