0

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 ?

4
  • 1
    Are you calling account_register() somewhere? FYI, your first example is in a function too. Commented May 7, 2014 at 1:56
  • sorry my mistake, is dothis() Commented May 7, 2014 at 1:58
  • <button type="submit" onClick="dothis(); return false;">Click</button> Commented May 7, 2014 at 1:58
  • Try a normal button, then use a jQuery $("#button").click(function() { //ajax code here }); Commented May 7, 2014 at 1:58

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.