I have made the following code which is working fine but it is not changing the background colour of the field when retdata is not empty, can anyone help fix the code ?
Another possibility would be to store a reference to $(this) outside the success callback. This would have the additional advantage that you don’t have to create (and almost immediately discard) 2 jQuery objects but only one:
var $this = $(this)
var keynum = $this.val()
// And later in the AJAX callback:
$this.addClass('red')
BTW, the 2nd parameter of .each() (you called it data) is also a reference to the current DOM element – the same as this is. However unlike this it doesn’t change with the execution context and could be directly used in the success callback as well.
Now I have another issue, i am trying to prevent the form submission if the red class is set for any field. But its not working. Though the class is changed but form is also submitted. How to stop ?
I also tried to set err = 0 and change err = 1 and also did if (err == 1) { e.preventDefault(); } but its not working and form still gets submitted.
That’s because when you’re checking if you should call event.preventDefault(), the AJAX responses have not arrived yet. Now you might manually .submit() the form from within the success callback when all checks are completed… but actually, if you’re doing the server side validation via AJAX anyway you might just as well send the whole form data in one go, and display the relevant response data right on the same page – otherwise you’d be sending a lot of data twice to the server.