Reputation: 1541
I have a simple <button type="submit" onClick="dothis();">Click</button>
.
This script below have no problem,
$(document).ready(function() {
action = 'test';
$.ajax({
url:'ajax.php',
data: 'action='+action,
type:'GET',
dataType:'json',
timeout:7000,
error:function(){ alert('Error!'); return false; },
success:function(json){ alert('ok'); }
});
});
but when I put it into function then it doesn't work,
function dothis(){
action = 'test';
$.ajax({
url:'ajax.php',
data: 'action='+action,
type:'GET',
dataType:'json',
timeout:7000,
error:function(){ alert('Error!'); return false; },
success:function(json){ alert('ok in function'); }
});
}
What was the correct way to put ajax into a function ?
Upvotes: 0
Views: 47
Reputation: 2333
either change your button from type "submit" to "button" or you need preventDefault()
$('someform').on('submit', function(ev){
ev.preventDefault();
action = 'test';
$.ajax({
url:'ajax.php',
data: 'action='+action,
type:'GET',
dataType:'json',
timeout:7000,
error:function(){ alert('Error!'); return false; },
success:function(json){ alert('ok'); }
});
});
check this http://api.jquery.com/event.preventdefault/
Upvotes: 1
Reputation: 707218
You likely have to cancel the default action on your submit button because it is probably sending a form and reloading the page. Your ajax call is getting sent, but then the page is getting reloaded immediately so you don't see any results from it.
You can cancel the default action by either adding
return false;
to the end of doThis()
.
function dothis(){
action = 'test';
$.ajax({
url:'ajax.php',
data: 'action='+action,
type:'GET',
dataType:'json',
timeout:7000,
error:function(){ alert('Error!'); return false; },
success:function(json){ alert('ok in function'); }
});
return false;
}
Or, change your button to be a normal button, NOT a submit button.
Upvotes: 2