I have two buttons where each button do the same function but one variable. I'm using ajax to handle some PHP. I'm thinking the problem is that the ajax is being run before the js function.
Do you have any solutions for passing a parameter along the specific button click?
$('.button').click(function(){
$.ajax({
type: "POST",
data: {
userid: <?php echo $userid ?>,
upgradePrice: price,
resource: upgResource
},
url: "UpgradeResHandler.php",
dataType: "json",
async: true,
beforeSend: function(){
$(".ajaxTest").text("Trying to upgrade...");
},
success: function(data) {
$(".ajaxTest").text(data.a);
if (data.b == "true") {
location.reload();
}
}
});
});
function setResource(resource) {
var upgResource = resource;
}
<input type="submit" class="button" name="upgGold" value="Upgrade" onclick="setResource('gold')" />
<input type="submit" class="button" name="upgMetal" value="Upgrade" onclick="setResource('metal')" />
You can only have 1 onclick event handler per element. Try putting the ajax call inside of the function you are calling then get rid of the $('.button').click(); handler.
function setResource(resource) {
var upgResource = resource;
$.ajax({
type: "POST",
data: {
userid: <?php echo $userid ?>,
upgradePrice: price,
resource: upgResource
},
url: "UpgradeResHandler.php",
dataType: "json",
async: true,
beforeSend: function(){
$(".ajaxTest").text("Trying to upgrade...");
},
success: function(data) {
$(".ajaxTest").text(data.a);
if (data.b == "true") {
location.reload();
}
}
});
}
This is what is recommand you. Remove you're function setResource() and the onclick attribute on the inputs. And instead, just fill an attribute with the value you want to pass. Here I am using data-resource. You can access any jquery element attribute by using the .attr() jquery method. And in this watcher $(this) is the element you click on. So he will have the good value for the attribute. This method is saving you for a function and a variable assignation.
$('.button').click(function(){
$.ajax({
type: "POST",
data: {
userid: <?php echo $userid ?>,
upgradePrice: price,
resource: $(this).attr('data-resource')
},
url: "UpgradeResHandler.php",
dataType: "json",
async: true,
beforeSend: function(){
$(".ajaxTest").text("Trying to upgrade...");
},
success: function(data) {
$(".ajaxTest").text(data.a);
if (data.b == "true") {
location.reload();
}
}
});
});
<input type="submit" class="button" name="upgGold" value="Upgrade" data-resource="gold" />
<input type="submit" class="button" name="upgMetal" value="Upgrade" data-resource="metal" />
In the case you prefer to keep your onclick and you're function, you can pass your ajax call into that function and remove the jquery watcher. the same job will be done. My method just use jQuery resources.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With