• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
JQuery AJAX success/error response repeats twice?

I have a simple single text input field that I'm submitting via ajax. Everything seems to be working normal except that it outputs the success or error response twice. I've checked firebug and it looks like it's only sending the response once?

This is the code I'm using when the user submits the form. There are two methods in this controller. The one below which handles the form submission and the index method. Any ideas on why it outputs either the success or failure twice? It outputs the message in the response div located in the view like "Please enter a valid email address.Please enter a valid email address.". Any ideas or help is appreciated.

// save email subscribers
public function email()

// let's make sure this is an ajax request
if ($this->input->is_ajax_request()) {
  // validate the fields
  $this->form_validation->set_rules('email', 'Email', 'trim|required|xss_clean|valid_email');

  // if failed validation reload page and display values
  if ($this->form_validation->run() == FALSE)
   $response['status'] = 'error';
   // passed validation so lets insert the data
   $data = array('subscribe_email' => $this->input->post('email'));
else {
  // I'm not AJAX!
  log_message('error', 'Email Subscribe - Non-ajax request');

This is the jquery.

$(document).ready(function() {
$('#emailoffers input#submit').click(function(e) {

  var email = $("#email").val();

   type: 'post',
   url: 'home/email',
   data: 'email='+email,
   dataType: 'json',
   success: function(results) {
    if(results.status == 'success') {
     $('div#response').hide().html("Success! Thanks for subscribing.").fadeIn(500);
    else if(results.status == 'error') {
     $('div#response').hide().html("Please enter a valid email address.").fadeIn(500);
  }); // end ajax

check your if statments.

Use var_dump and Firebug.

Hmmm. I've been doing that and had done that prior to posting. In firebug the response is {"status":"error"}. The post is also only being sent once. Am I missing something glaringly obvious? Everything seems to work except that it is outputting the error or success message twice. If the email is valid it only inserts to the database once.

On Success it prints
Success! Thanks for subscribing.Success! Thanks for subscribing.

On Error it prints
Please enter a valid email address.Please enter a valid email address.

I'd like for it to only print the statement once.

Arrggg! Of course my error. I had the div where the response gets written in the view twice. I figured it had to be something glaringly obvious. Sorry to waste everyones time.

Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  

  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2021 MyBB Group.