Frank
Frank

Reputation: 61

Why some ajax buttons not working?

As you can see, I have 5 buttons. they working good.

<button type="submit" id="submit_button1">Img1</button>
<button type="submit" id="submit_button2">Img2</button>
<button type="submit" id="submit_button3">Img3</button>
<button type="submit" id="submit_button4">Img4</button>
<button type="submit" id="submit_button5">Img5</button>

script.js:

function button(name,url) {
$(name).click(function(){
   $.ajax({
      url:url+'.php',
      success: function(html){
      $("#show").after(html);
      }
   });
return false;
});
}

$(document).ready(function(){
    button(submit_button1,'action1');
    button(submit_button2,'action2');
    button(submit_button3,'action3');
    button(submit_button4,'action4');
    button(submit_button5,'action5');
});

by using the same script.js, the following works too:

<button type="submit" id="submit_button1">Img1</button>
<button type="submit" id="submit_button2">Img2</button>

but if i use this:

<button type="submit" id="submit_button1">Img1</button>
<button type="submit" id="submit_button3">Img3</button>

button1 works, button3 not. I don't know why.

or this:

<button type="submit" id="submit_button3">Img3</button>
<button type="submit" id="submit_button4">Img4</button>

button3 and button4 not work.

looks like I have to use all buttons if I add them in script.js, if I skip one, then some buttons will not work. how to solve this problem?

Upvotes: 1

Views: 70

Answers (1)

Royi Namir
Royi Namir

Reputation: 148524

You have 2 problems :

1 )

Why are you invoking button(submit_button1,'action1'); and not button('submit_button1','action1');

2) your function should treat it as ID :

function button(name,url) {
$('#'+name).click(function(){
   $.ajax({ ...

Also - another way can be :

button($('#submit_button1'),'action1');

and so the function will be :

function button(name,url) {
$(name).click(function(){ ... //$ is redundant but anyway...

Upvotes: 2

Related Questions