Reputation: 1468
I have a hard time with $.ajax(). I have this HTML page :
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<form name="gettr" id="gettr">
<input type="hidden" name="lang" value="ro">
<input type="text" name="tickkey" id="tickkey" value="">
<br>
<input type="submit" value="Send" id="submit">
<input type="reset" value="Cancel" onclick="$("#hereinfo").html("");">
</form>
</body>
</html>
And the script :
$("#gettr").submit(function() {
var url = "handler.php";
$.ajax({
type: "GET",
url: url,
dataType: "application/json",
data: $("#gettr").serialize(), // serializes the form's elements.
success: function(data) {
alert('Done');
}
});
return false;
});
I'm running the script locally now, and my problem is that the script doesn't do anything.When I click on send button it just adds ?lang=ro&tickkey=value_inputed_in_the_form
at the end of the url in the address bar.What should I do so I can store the JSON returned by the server in a variable?
Thank you!
Upvotes: 1
Views: 285
Reputation: 10132
I think the reason your query variables are appending to url is because you're executing your script before the DOM loads. You should wrap your script within $(document).ready(function () { });
handler.
Use event.preventDefault()
instead of return false;
. But Why not return false;
see here
$(document).ready(function () { //Let the DOM be loaded
$("#gettr").submit(function(event) {
event.preventDefault(); //Prevent window default behaviour
var url = "handler.php";
$.ajax({
type: "GET",
url: url,
dataType: "application/json",
data: $("#gettr").serialize(), // serializes the form's elements.
success: function(data) {
alert(data); //Alert your json data from server
}
});
});
//remember remove return false; because you're already preventing default behaviour
});
Upvotes: 7
Reputation: 607
Ensure that the DOM is ready and prevent the form submission before executing the AJAX request.
var dataFromServer = {};
// Document ready.
$(function() {
$( '#gettr' ).on( 'submit', function( event ) {
// Prevent form submission.
event.preventDefault();
// AJAX request.
var url = 'handler.php';
$.ajax({
type: 'GET',
url: url,
dataType: 'application/json',
data: $( '#gettr' ).serialize(),
success: function( data ) {
dataFromServer = data;
}
});
});
});
Upvotes: 4
Reputation: 32831
Try to call preventDefault();
$("#gettr").submit(function(event) {
event.preventDefault();
Upvotes: 4