Welcome Guest, Not a member yet? Register   Sign In
Throw Exception From AJAX Call
#5

[eluser]attos[/eluser]
What I do is to use jQuery's to display either success or error messages.

The requesting page the Ajax call is:
Code:
$.ajax(
  { url: '<?php echo base_url().'ajax/create_account/'?>'
  , type: 'post'
  , dataType: 'text'
  , data: $('form').serializeArray()
  , success: function (data) { $('#message_div').html(data.responseText).removeClass().addClass(success_class).show(); }
  , error: function (data) { $('#message_div').html(data.responseText).removeClass().addClass(error_class).show(); }
});

Please note that I'm using a text response since I'm only displaying the message and not processing anything from the server. I would use the json or xml dataType if any data needs to be processed. (BTW I like the commas in front of multi-line statements. It is easier for me to add and delete lines and not worry about the last line that does not end with a comma :-))

In the controller:
Code:
try
{
  $this->your_model->create_account();
  $data = 'Your accouont has been created';
  $this->load->view('ajax_text_view', array('data'=>$data));
}
catch (AppException $ex)
{
  $message = 'An error occurred while processing the request: '.$message;
  $this->output->set_status_header('500');
  $this->load->view('ajax_text_view', array('data'=>$message));
}

I'm assuming you're using a model to create the account, which throws an exception in case of an error. Please note that when catching an exception the response status header is set to 500 (http error). This causes to execute the error function in jQuery.

Finally a view sets the http header and the content:
Code:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
  header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
  header("Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . "GMT");
  header("Cache-Control: no-cache, must-revalidate");
  header("Pragma: no-cache");
  header("Content-type: text/plain");
  echo $data;

There are also two CSS class for success_class (green background with a check-mark image) and for the error_class (red background and a stop sign image).


Messages In This Thread
Throw Exception From AJAX Call - by El Forum - 09-25-2009, 12:21 PM
Throw Exception From AJAX Call - by El Forum - 09-25-2009, 12:38 PM
Throw Exception From AJAX Call - by El Forum - 09-25-2009, 02:55 PM
Throw Exception From AJAX Call - by El Forum - 09-25-2009, 03:17 PM
Throw Exception From AJAX Call - by El Forum - 09-28-2009, 07:31 AM



Theme © iAndrew 2016 - Forum software by © MyBB