0

I have a global variable var emp_error = 0; but when I access emp_error even though it when through else (since the tr's bg color changes), emp_error is still 0. Can someone help me out? So that it won't update the employee ID if it already exists

$.ajax({
     type: "POST",
     url: "<?php echo site_url('c_device/check_empId'); ?>",
     data: dataString,
     dataType: 'json',
     cache: false,
     success: function(data){
              console.log(data);
              if(data.length == 0){
                   emp_error=0;
              }else{
                   $("#error_"+tr_id).html("Emp id exists");    
                   $("#"+tr_id).css("background-color","red");                  
                   emp_error++;
              }                  
     }
});
kraftner
  • 457
  • 2
  • 16
mengmeng
  • 866
  • 2
  • 11
  • 28
  • here is another SO post link to something similar http://stackoverflow.com/questions/15795831/jquery-ajax-local-variable-cant-assign-to-global – HackerKarma Feb 19 '14 at 16:01
  • if your var emp_error is instantiated with the value of 0 why do you have the if statement? wouldn't this be enough? `if(data.length){ $("#error_"+tr_id).html("Emp id exists"); $("#"+tr_id).css("background-color","red"); emp_error+=1; }` – Fabio Antunes Feb 19 '14 at 16:03
  • Oh and avoid using doing this `your_var++;` http://stackoverflow.com/questions/971312/why-avoid-increment-and-decrement-operators-in-javascript – Fabio Antunes Feb 19 '14 at 16:05
  • 5
    Don't listen Fabio. Nothing bad in ++ operator. – Sergey Yarotskiy Feb 19 '14 at 16:20
  • How and when are you testing the value of `emp_error`? – Quentin Feb 19 '14 at 20:42

1 Answers1

0

Assuming you want emp_error to increment on multiple calls, you need to a) not reset to 0 when it fails, and b) define it outside of the function so emp_error++ has something to increment if the first call is not empty.

Define the global outside of the function the contains the ajax call.

Demo: http://jsfiddle.net/5h9pL/

If you won't be making multiple calls and actually just want emp_error to be set when an employee is found, don't mess with globals at all:

      if(data.length == 0){
           emp_error = 0;
      }else{
           $("#error_"+tr_id).html("Emp id exists");    
           $("#"+tr_id).css("background-color","red");                  
           emp_error = 1;
      }
stormdrain
  • 7,910
  • 4
  • 35
  • 74