tags:

views:

133

answers:

2

Hi, I want to send the username and password values which user types in html input elements to server to check if the username and password is valid or not when user click login button, using post request in $.ajax(options) method in jquery, but I don't know how to send those username and password to server. What option should I write in $.ajax(options) method to get those values from server?

+3  A: 

You can do like:

$.ajax({
  url:'server-file-url.php',
  type:POST,
  data:$('form_id').serialize(), // this will get form fields
  success:function(res){
   alert(res);
  };
});

In the server file, you check the record of user in your db if it exists, you simply send back some response like 1 for success and 0 for failure and use that in the success arguments of the $.ajax function to take the appropriate action.

Sarfraz
Please correct the comment, because the suggested alternative is wrong (missing URL encoding).
Tomalak
+2  A: 

Assuming the username and password are contained in a input text fields with respective ids:

<input type="text" name="username" id="username" value="" />
<input type="password" name="password" id="password" value="" />

you could send them like this:

var username = $('#username').val();
var password = $('#password').val();
$.ajax({
    type: 'POST',
    url: '/serverscript.cgi',
    data: { username: username, password: password },
    success: function(result) {

    }
});

Finally make sure you are using HTTPS to avoid sending this information in clear text over the wire.

Darin Dimitrov
@Darin - what if HTTPS is not an option? is there any other secure way?
Emin
No there isn't.
Darin Dimitrov
Encrypt the password before sending. Use MD5 under Javascript and do something similar on the server-side to compare the encrypted strings; as opposed to just comparing plain passwords.
Gerard