Jquery - use the same function for multiple requests - php

I have this CLICK function that works for one specific HTML button. I'd like to use it on multiple buttons, but each button needs to pass different variables to the same page.
BUTTON
<input type="button" id="scs" value="TEST" />
JQUERY
$("#scs").click(function() {
$("#status").html("<p>Please Wait! TESTING</p>");
$.ajax({
url: 'go.php?ab=1',
success: function(data, textStatus, xhr) {
alert (data);
}
});
});
How can I adapt this so if I have 4 more buttons each button uses the function, calls the same page but uses unique values ?
EG :
<input type="button" id="update" value="update" /> Calls go.php?up=1
<input type="button" id="new" value="new" /> Calls go.php?new=1
etc...
Thanks

Give your buttons the same class and call the code using the class name, and add a data attribute to each button to retrieve the seperate values.
Give this a try:
<input type="button" class="clickButton" data-value="go.php?up=1" value="Update" />
<input type="button" class="clickButton" data-value="go.php?new=1" value="New" />
$(".clickButton").click(function() {
$("#status").html("<p>Please Wait! TESTING</p>");
$.ajax({
url: $(this).attr("data-value"),
success: function(data, textStatus, xhr) {
alert (data);
$(this).prop('value', 'New Text');
}
});
});

Use the data-attribute to to set the url.
Use event delegation to target the buttons
<input type="button" class='btn' data-params='up=1' value="update" /> Calls go.php?up=1
<input type="button" class='btn' data-params='new=1' value="new" /> Calls go.php?new=1
$("button").on('click', '.btn', function() {
var url = 'go.php?' + $(this).data('params');
$("#status").html("<p>Please Wait! TESTING</p>");
$.ajax({
url: url,
success: function(data, textStatus, xhr) {
alert (data);
}
});
});

Use class for click event and new attribute to find the button like 'data-id'
<input type="button" class="clickevent" data-id="update" value="update" />
Jquery
`
$(".clickevent").click(function() {
$("#status").html("<p>Please Wait! TESTING</p>");
$.ajax({
url: $(this).attr('data-id'),
success: function(data, textStatus, xhr) {
alert (data);
}
});
});
`

You can check by the value of the clicked button and use a 'url' variable for the ajax request:
$("button").click(function() {
$("#status").html("<p>Please Wait! TESTING</p>");
var url='';
var value = $(this).val();
if(value == 'update'){
url='go.php?up=1';
} else if(value=='new') {
url='go.php?new=1';
} else if(value=='scs') {
url='go.php?ab=1';
}
$.ajax({
url: url,
success: function(data, textStatus, xhr) {
alert (data);
}
});
});

Use same class for each button
<input type="button" id="update" class="click" value="update" />
<input type="button" id="new" class="click" value="new" />
$(document).ready(function(){
$(".click").click(function(){
var val=$(this).val();
if(val =="update")
{
$.post("go.php",{'up':'1'},function(data){
alert(data);
});
}
else
{
$.post("go.php",{'new':'1'},function(data){
alert(data);
});
}
});
});

Related

How to send AJAX request from a <form> created by jQuery

I have a jQuery textarea from where I am posting form values with a button. I don't want to refresh the page and use AJAX for this purpose so that the page does not get refreshed. I have tried a lot but the solution does not seem to be coming out. Here is my code for the same. Any insight will be really helpful.
Here is my code,
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.click_notes').on('click',function(){
var tid = $(this).data('question-id');
$(this).closest('ul').find('.demo').html("<div class='comment_form'><span onclick='$(this).parent().hide()'><b>X</b></span><form id = 'contactForm1' action='submit.php' method='post'><textarea required cols ='50' class='span10' name='notes' rows='6'></textarea><br><input class='btn btn-primary' id = 'submitnotes' name= 'submit_notes' type='submit' onclick = 'submitform()' value='Add Notes'><input type='hidden' name='submitValue' value='"+tid+"' /></form><br></div>");
});
});
</script>
<script type="text/javascript">
function submitform() {
e.preventDefault();
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
console.log('Submission was successful.');
console.log(data);
},
error: function (data) {
console.log('An error occurred.');
console.log(data);
},
});
}
</script>
To achieve this hook to the submit event of the form itself, not the click event of the submit button. Also note that you shouldn't be using on* event attributes. As the HTML content of the form is dynamically appended to the DOM you can use a delegated event handler on both the form and span instead. Try this:
$(document).ready(function() {
$('.click_notes').on('click', function() {
var tid = $(this).data('question-id');
$(this).closest('ul').find('.demo').html('<div class="comment_form"><span><b>X</b></span><form id="contactForm1" action="submit.php" method="post"><textarea required cols="50" class="span10" name="notes" rows="6"></textarea><br><input class="btn btn-primary" id="submitnotes" name="submit_notes" type="submit" value="Add Notes"><input type="hidden" name="submitValue" value="' + tid + '" /></form><br></div>');
});
$(document).on('submit', '#contactForm1', function(e) {
e.preventDefault();
$.ajax({
type: this.method,
url: this.action,
data: $(this).serialize(),
success: function(data) {
console.log('Submission was successful.');
console.log(data);
},
error: function(xhr) {
console.log('An error occurred.');
console.log(xhr);
},
});
}).on('click', 'span', function() {
$(this).parent().hide()
});
});
Also note that you're including two versions of jQuery, one of which (1.6.1) is getting nearly 8 years out of date. I'd suggest using a single reference to jQuery 3.3.1 instead.

How to display the AJAX response in input field and pass that value to PHP?

I am getting Id value from my AJAX and I am also able to display it. I set the Id value input text in the AJAX and displaying it on HTML like this <input value="4864" id="compare_id" type="hidden"> Now I have to pass that value to PHP to get the result from database.
Is there any idea how to do it?
AJAX
$(document).ready(function() {
arr = [];
$("[type=checkbox]").click(function() {
$.ajax({
type: "POST",
url: "includes/compare_process.php", //
data: 'users=' + arr,
dataType: 'json',
success: function(msg) {
$("#pics_name,#pics_Id").empty();
$.each(msg, function() {
$("#pics_Id").append("<input type=hidden value=" + this.Id + " id=compare_id name=compare_id>");
//alert(msg.id);
});
},
error: function() {
alert("failure");
}
});
});
});
//tried AJAX
$(document).ready(function(){
$('#search-button').click(function(){
$.ajax( {
type: "GET",
url: 'includes/compare_process.php?key=compare_details',
data: $('#search-form').serialize(),
success: function(response) {
//$('#response').html(response);
alert(response);
}
} );
});
});
PHP
<div class="bg-popup" style="display: none;" id="open_compare_popup">
//popup code here
<?php
$val2=htmlentities($_GET['compare_id']);
echo $val2;
$sql = "SELECT * FROM `request` WHERE Id IN($val2)";
?>
//end popup code here
This output I am getting from AJAX
<form action="#" method="get" id="search-form">
<span id="pics_Id">
<input value="4869" id="compare_id" name="compare_id" type="hidden">//output
<input value="4884" id="compare_id" name="compare_id" type="hidden">//output
<input value="5010" id="compare_id" name="compare_id" type="hidden">//output
</span>
<button class="action action--button action--compare" type="button" id="search-button" name="search-button"><span class="action__text">Compare</span></button>
</form>
I have to pass the input value to PHP after clicking on a button.

Call PHP function with button onClick with parameter/ AJAX?

Hello I want to call my function download when the user click on the button, basically:
<input type='button' name='Release' onclick="document.write('<?php downloadFichier($tab1, $t2) ?>');" value='Click to Release'>
Of course doesn't work, so I try to do with a AJAX, I don't know this language, but it is possible to do what I want: call my PHP function with 2 parameters?
<button type="button">Click Me</button>
<p></p>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$.ajax({
type: 'POST',
url: 'file_product.php',
success: function(data) {
$("p").text(data);
}
});
});
});
</script>
Thank you for helping me.
You should call a js-function with onclick event like this:
<input type='button' name='Release' onclick="downloadFichier(param1, param2)" value='Click to Release'>
And your AJAX-function should be like this:
function downloadFichier(param1, param2){
$.ajax({
type: 'POST',
url: 'file_product.php',
data: "param1=" + param1 + "&param2=" + param2,
success: function(data) {
$("p").text(data);
}
});
You can get your params in PHP-script from the $_REQUEST array by their names (param1, param2).
#PaulBasenko inspired this alternative, where you set the parameters through some <input type="hidden" /> :
HTML
<form action="#" method="POST" id="form1">
<input type="hidden" name="tab1" value="<?= $tab1 ?>" />
<input type="hidden" name="t2" value="<?= $t2 ?>" />
<button type="submit">Click to Release</button>
</form>
Javascript
$(function() { // equivalent of "$(document).ready(function(){"
$('body').on('submit', '#form1', function(event) {
event.preventDefault();
var formData = $(this).serialize();
$.ajax({
type : 'POST',
url : 'file_product.php',
data : formData,
success : function(data) {
$('#p').text(data);
}
});
});
});
PhP
<?php
$tab1 = (isset($_POST['tab1'])) ? $_POST['tab1'] : null;
$t2 = (isset($_POST['t2'])) ? $_POST['t2'] : null;
// process & return json_encoded data
?>
How it works ?
When clicking on the button, which is a type="submit", it will trigger the submit event for its parent form. Then, jQuery listen to this event and immediately blocks it using èvent.preventDefault() in order to call Ajax instead of a regular synchronous call to a php file.

How to include value of form submit button that was clicked?

I must submit a form and I need to include the value of the submit button that was clicked. How can I do that? This is my code:
<form id="form_update" >
<input type="text" class="form-control" name="title" value="" >
<input type="hidden" name="prova" value="prova" />
<button type="submit" name="salva" value="delete" class="btn btn-success">delete</button>
<button type="submit" name="salva" value="modify" class="btn btn-success">modify</button>
<button type="submit" name="salva" value="save" class="btn btn-success">save</button>
</form>
$(document).on('submit', '#form_update', function() {
return callAjax($(this).serialize());
});
function callAjax(data) {
$.ajax({
type: 'POST',
url: 'call/function.php',
data: data,
success: function(data) {
// code
},
error: function(data) {
alert('error');
}
});
return false;
};
I would change the event type to a click on the button and the access their values with $(this).val()
$(document).on('click', 'button', function(e) {
e.preventDefault(); // Prevent from submitting form.
var buttonValue = $(this).val();
return callAjax($('#form_update').serialize());
});
Use the below function.
$(document).on('submit', '#form_update', function() {
var val = $("input[type=submit][clicked=true]").val();
return callAjax($(this).serialize()+'&clickedVal='+val );
});
It will pass the clicked button value with the ajax request.
Thanks...
With Arun solution I get undefined val value...
With Daan solution the problem was the same...
But with your response I have resolved with a mix :)
$(document).on('click', 'button', function(e) {
e.preventDefault(); // Prevent from submitting form.
var buttonValue = $(this).val();
return callAjax($('#form_update').serialize()+'&salva='+buttonValue );
});
Thanks a lot ;)

how to use a single ajax process looped form

I have a HTML form that might be in a loop thus:
<form name="ajaxform" id="ajaxform<?php echo $sn;?>" action="" method="POST">
<p>Comment:<br /> <input type="text" value="" style="width:400px" name="comment<?php echo $sn;?>" />
<input type="button" id="simple<?php echo $sn;?>" class="submit" value="Save" />
<div id="simple-msg<?php echo $sn;?>"></div>
</form>
<?php
// the loop is ending here
?>
Now, the ajax code for posting these form onto a specific url is here:
<script>
$(document).ready(function()
{
$("#simple<?php echo $sn;?>").click(function()
{
$("#ajaxform<?php echo $sn;?>").submit(function(e)
{
//$('#simple').val().submit(function()
//$("#ajaxform1").submit(function(e)
//{
//$('#simple-msg').show();
$("#simple-msg<?php echo $sn;?>").html("<img src='ajax/profile/ajax-loader.gif'/>");
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url : "ajax/results/comment.php?id=<?php echo $sn;?>",
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
$("#simple-msg<?php echo $sn;?>").html(''+data+'');
},
error: function(jqXHR, textStatus, errorThrown)
{
$("#simple-msg<?php echo $sn;?>").html('<font color="red">Failed to save<br/> textStatus='+textStatus+', errorThrown='+errorThrown+'</font><span class="icon icon-color icon- close"></span>');
}
});
e.preventDefault(); //STOP default action
e.unbind();
});
$("#ajaxform<?php echo $sn;?>").submit(); //SUBMIT FORM
});
});
</script>
The problem is how do I use this ajax script to process all the form without having to loop the script too. as you can see in the script above, I want to remove all the(). if I do that and submit the form, only the first form process, but if I put the script in the loop, all will process. I figure that this is a bad practise as if I have a thousand form in a page, the script also repeat a thousand time. large data to the browser huh?
Use classes:
<form name="ajaxform" action="" method="POST" data-sn="<?php echo $sn;?>">
<p>Comment:<br /> <input type="text" value="" style="width:400px" name="comment<?php echo $sn;?>" />
<input type="button" class="simple submit" value="Save" />
<div class="simple-msg"></div>
</form>
And JS:
$(document).ready(function() {
$(".simple").click(function() {
var $ajaxForm = $(this).parents('form');
var $simpleMsg = $ajaxForm.find('simple-msg');
$ajaxForm.submit(function(e) {
$simpleMsg.html("<img src='ajax/profile/ajax-loader.gif'/>");
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax({
url: "ajax/results/comment.php?id=" + $ajaxForm.data('sn'),
type: "POST",
data: postData,
success: function(data, textStatus, jqXHR) {
$simpleMsg.html('' + data + '');
},
error: function(jqXHR, textStatus, errorThrown) {
$simpleMsg.html('<font color="red">Failed to save<br/>textStatus=' + textStatus + ', errorThrown=' + errorThrown + '</font><span class="icon icon-color icon-close"></span>');
}
});
e.preventDefault(); //STOP default action
e.unbind();
});
$ajaxForm.submit(); //SUBMIT FORM
});
});

Categories