Peter
Peter

Reputation: 1541

Jquery ajax not working in function

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

Answers (2)

Se0ng11
Se0ng11

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

jfriend00
jfriend00

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

Related Questions