jquery - Print exception in Ajax thrown from PHP -


I am trying to request a post using ajax URL. My JS / JQuery code looks like this

  var params = {'username': 'eddard.stark@got.com', 'name': 'Edward Stark'}; $ .post ("/ user / add", parameter, function (data) {// no error user user = eval ('(' + + data + ')); $ ("# spanId"). Html (" User ID "+ user.id); // here- http://stackoverflow.com/questions/16472116/ajax-error-cannot-catch-thrown-exception-from-php // It is saying that it handled it here Can be / error 5xx: server side errors (such as DB failure) $ ("#"). (Error: status) (error, status) {// error 4xx: client side errors (such as controller / action does not exist) / Error 5xx: SpanId ") .html (" erro R "+ err;;}) always (function () {$ (elm) .hide (); $ ('# spanId'). Show ();});   

< Code> / user / add php code for action

  add function () {$ username = null; $ Name = null; if (isset ($ _ POST ['name ']) {$ Name (empty ($ _ POST)} {ifet ($ _ POST [' username ']) {$ username = $ _POST [' username '];} = $ _POST [' name '];}} If (is_null ($ username) || is_null ($ name)] {throw a new exception ('invalid request');} $ user = $ this- & gt; User- & gt; Search ($ username); If (isset ($ user)) {new exception ('user is not available');} // ... more code ...}   

I have them in Ajax How can I print exceptions?


Edit :
There is another way to handle it. One exception

  header ("HTTP / 1.1 400 users not available"); // exception   

then failed handler can print it with my Ajax code

  $ ("# spanId") . Html ("Error:" + err.statusText)   

But I do not want to do this. I want to print it in the success handler.

Here's a small demonstration of my comment.

Your AJAX

  .done (function) (if ((response.exception) === "noExp") {Warning ("Success !!!" ); // is no exception;} {// handle it}}   

php

  add function () {$ username = null; $ Name = null; $ Exception = "noExp"; if (isset ($ _ POST ['name']) {$ name (empty ($ _ POST)) {ifet ($ _ POST ['username']) {$ Username = $ _POST ['username'];} = $ _POST ['name'];}} if (is_null ($ user name) || is_null ($ name)) // {new exception throw ('invalid request') ; $ Exception = "Invalid request";} $ user = $ this-> user- & gt; search ($ username); if (Isset ($ user)) {// new exception ('user not available'); $ exception = "user not available"} // more code ... $ result = array ("exception" = & Gt; $ exception, // other returns) echo json_encode ($ result);}    

Comments

Popular posts from this blog

ios - Adding an SKSpriteNode to SKScene from a child SKSpriteNode -

Matlab transpose a table vector -

c# - Textbox not clickable but editable -