user3303790
user3303790

Reputation: 137

jQuery POST Ajax request

i'm trying to post data from Server A, let's say: www.a.com to server B, www.b.com and then fetch the response from server B

I do it like this, this script runs on server A:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>    
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Naamloos document</title>
</head>

<body>

<form id="Form" onsubmit="validate();" method="post">
Email Address: <input type="text" id="email" name="email">
Password: <input type="text" id="password" name="password">
<input type="submit">
 </form>

<script>
function validate()
{
var e = $('email').value;
var p = $('password').value; //jQuery is easier to type
// the same as
// var p = document.getElementById('password').value;
var req = new Request({
    url: 'http://www.B.com/validate.php?',
    method: 'post',
    data: {'email' : e, 'password' : p},
    onComplete: function(response)
    {
        if (response == "Valid" ) 
        {
            alert("succes");
        }
        else
        {
            alert("blur");
        }
    }
}).send();
}
</script>

</body>
</html>

But at this moment, after hitting the submit button, the only thing that happends is that the fields are being cleared, thats all.

Validate.php looks like this:

<?php echo "Valid"; ?>

Upvotes: 0

Views: 113

Answers (2)

Quentin
Quentin

Reputation: 943552

You're submitting the form, so the JavaScript never gets a chance to do anything significant. Since you haven't specified an action, it submits to the current URL and reloads the page.

  1. Stop using intrinsic event attributes.
  2. Use JS event binding (since you are using jQuery already, keep using it)
  3. Capture the event object and prevent the default behaviour of the submit event

such:

<form id="Form" method="post">

$('#Form').on('submit', validate);

function validate (event) {
    event.preventDefault();
    var e = $('#email').val();

You also don't appear to have defined Request anywhere. You should probably switch to jQuery ajax


Also note that Server B will have to give Server A permission to make Ajax requests to it using CORS.

Upvotes: 2

Branimir Đurek
Branimir Đurek

Reputation: 632

Try to replace this

var e = $('email').value;
var p = $('password').value;

with this

var e = $('#email').val();
var p = $('#password').val();

Upvotes: 0

Related Questions