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 ;)
Related
I'm trying to detect which was button was pressed with jQuery and then server-side do different things depending on the outcome.
The jQuery works fine (although I may have gone about it in a long- handed way) but I can't figure out why in my code whichever button I press I get the same response from php: "Add button detected". I hope someone can tell me what I've got wrong?
The jQuery
$(document).ready(function() {
$(".btn_add").on("click", function() { //If add btn pressed
var id = this.id;
var url = "process_ajax4.php?btn=" + this.id;
var formdata = $('.myForm').serialize();
$.post(url, formdata,
function(data) {
$("#results").html(data); //Response
});
});
$(".btn_remove").on("click", function() { //If remove btn pressed
var id = this.id;
var url = "process_ajax4.php?btn=" + this.id;
var formdata = $('.myForm').serialize();
$.post(url, formdata,
function(data) {
$("#results").html(data); //Response
});
});
});
The Php
<?php
$btn=$_POST["btn"]; //Other posted variables removed for simplicity
if($btn="btn_add"){
echo "<h1>Add button detected</h1>";
//Do stuff
}
elseif($btn="btn_remove"){
echo "<h1>Remove button detected</h1>";
//Do other stuff
}
?>
The html Form
<td>
<form id=\ "myForm\" class=\ "myForm\" action=\ "\" method=\ "post\" enctype=\ "multipart/form-data\">
<input type=\ "hidden\" name=\ "user_id\" value=". $collab_userid." />
<input type=\ "hidden\" name=\ "id\" value=".$upload_id." />
<button type=\ "submit\" id=\ "btn_remove\" class=\ "btn_remove\" name=\ "btn_remove\">Remove</button>
<button type=\ "submit\" id=\ "btn_add\" class=\ "btn_add\" name=\ "btn_add\">Approve</button>
</form>
</td>
You should add the pressed button to your formdata, otherwise the click couldn't be detected.
$(document).ready(function() {
$(".btn_add").on("click", function() { //If add btn pressed
var id = this.id;
var url = "process_ajax4.php?btn=" + this.id;
var formdata = $('.myForm').serialize();
formdata += "&btn=btn_add"; // added the btn
$.post(url, formdata,
function(data) {
$("#results").html(data); //Response
});
});
$(".btn_remove").on("click", function() { //If remove btn pressed
var id = this.id;
var url = "process_ajax4.php?btn=" + this.id;
var formdata = $('.myForm').serialize();
formdata += "&btn=btn_remove"; // added the btn
$.post(url, formdata,
function(data) {
$("#results").html(data); //Response
});
});
});
Change php code as follows
<?php
$btn=$_POST["btn"]; //Other posted variables removed for simplicity
if ($btn=="btn_add") {
echo "<h1>Add button detected</h1>";
//Do stuff
} elseif ($btn=="btn_remove"){
echo "<h1>Remove button detected</h1>";
//Do other stuff
}
?>
You need not have two separate function for jquery button handling. Also you can remove the button type="submit" from your code since you are detecting the click event
$(document).ready(function() {
$("button").on("click", function() { //If add btn pressed
var id = this.id;
var url = "process_ajax4.php?btn=" + this.id;
console.log(url);
var formdata = $('.myForm').serialize();
$.post(url, formdata,
function(data) {
$("#results").html(data); //Response
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td>
<form id="myForm" class="myForm" action="\" method= "post" enctype="multipart/form-data">
<input type="hidden" name="user_id" value=". $collab_userid." />
<input type="hidden" name="id" value=".$upload_id." />
<button type="submit" id="btn_remove" class="btn_remove" name= "btn_remove">Remove</button>
<button id="btn_add" class= "btn_add" name="btn_add">Approve</button>
</form>
</td>
You can use the parse_url() and parse_str() for getting the query string in php. In order to use $btn=$_POST["btn"]; tbn attribute must be passed as a form data, query parameters wont will be available through this method
<?php
$parts = parse_url($url);
parse_str($parts['query'], $query);
$btn = $query['btn'];
if($btn=="btn_add"){
echo "<h1>Add button detected</h1>";
//Do stuff
}
elseif($btn=="btn_remove"){
echo "<h1>Remove button detected</h1>";
//Do other stuff
}
?>
Your code works just make var url = process_ajax4.php that will fix your problem.in PHP use == instead of =, also add e.preventDefault() to your button clicks to prevent the form from being submitted with action='url'
$(document).ready(function() {
$(".btn_add").on("click", function(e) { //If add btn pressed
e.preventDefault();
var id = this.id;
var url = "process_ajax4.php";
var formdata = $('.myForm').serialize();
formdata += "&btn=btn_add"; // added the btn
$.post(url, formdata,
function(data) {
$("#results").html(data); //Response
});
});
$(".btn_remove").on("click", function(e) { //If remove btn pressed
e.preventDefault();
var id = this.id;
var url = "process_ajax4.php";
var formdata = $('.myForm').serialize();
formdata += "&btn=btn_remove"; // added the btn
$.post(url, formdata,
function(data) {
$("#results").html(data); //Response
});
});
});
i think your code looks ok.
i think in php you cannot compare string by =
you may need to change it to strcmp(strA,strB)==0 in order to ensure the input parameter is add button or remove button.
You don't actually need the jQuery code at all. Since both btn_remove and btn_add are submit buttons, you can check which of the buttons where used to submit the form by using:
if(isset($_POST["btn_remove"])) {
//Remove button was pressed.
}
I am working in wordpress and I have one form and two submit buttons. I am using ajax and it is wordpress.
When first submit button is pressed I want statement 1 to be echoed and when submit button number 2 is pressed I want state 2 be echoed. I have followed the code tutorials but when I press submit from the control returns empty or no result and in inspect there is no error in the browser. Below is my code.
HTML Form
<form id="voteform" action="" method="post">
<input name='vote' value='two' src='http://localhost:8080/test/wp-content/uploads/2015/04/up.jpg' type='submit' type='image'>
<input name='vote' value='one' src='http://localhost:8080/test/wp-content/uploads/2015/04/up.jpg' type='submit' type='image'>
</form>
I am not copying the enqueue code but just the actual php function that executes
function articlevote ()
{
if ($_POST['vote'] == 'one') {
echo json_encode("1 vote button is pressed");
die();
}
else if ($_POST['vote'] == 'two') {
echo json_encode("2 vote button is pressed");
die();
}
}
Ajax and jquery
jQuery(function ($) {
$(document).on("click","input[name=vote]", function() {
var _data= $('#voteform').serialize() + '&vote=' + $(this).val();
$.ajax({
type: 'POST',
url: yes.ajaxurl,
data:_data,
success: function(html){
$("#myresult").html(res);
}
});
return false;
});
});
Again kindly note that I am using wordpress so kindly guide me in this thanks
This should get you what you need:
Html:
<form id="voteform" action="" method="post">
<input type="text" name="field1" value="field one value"/>
<input type="text" name="field2" value="field two value"/>
<input class='vote' value='two' src='http://localhost:8080/test/wp-content/uploads/2015/04/up.jpg' type='submit' type='image'/>
<input class='vote' value='one' src='http://localhost:8080/test/wp-content/uploads/2015/04/up.jpg' type='submit' type='image'/>
</form>
jQuery
jQuery(function($) {
var yes = {ajaxurl:"mypage.php"}; // created for demo
$('.vote').click(function(e) {
e.preventDefault(); // stop the normal submit
var _data = $('#voteform').serialize()+'&vote=' + $(this).val();
//alert(_data)
$.ajax({
type: 'POST',
url: yes.ajaxurl,
data: _data,
success: function(html) {
$("#myresult").html(html); // you had `res` here
}
});
});
});
$(document).ready(function(){
$('input[value=\'one\'], input[value=\'two\']').on('click', function(){
var _data= $('#voteform').serialize() + '&vote=' + $(this).val();
$.ajax({
type: 'POST',
url: yes.ajaxurl,
data:_data,
success: function(html){
$("#myresult").html(res);
}
});
return false;
});
});
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);
});
}
});
});
I want a code for get textbox value when submit button is clicked. It must be Ajax.Here is the code I tried so far.But I culdent get to work....
<form action="" method="post">
<p>Route No :
<input type="text" name="route_no" required="required" />
<input type="submit" value="Search" name="search" />
</form>
Ajax Code
<script type="text/javascript">
$(document).ready(function() {
$("#sub").click(function() {
var textboxvalue = $('name or id of textfield').val();
$.ajax({
type: "POST",
url: 'ajaxPage.php',
data: {txt1: textboxvalue},
success: function(result) {
$("div").html(result);
}
});
});
});
</script>
PHP code
$txt = null;
if((isset($_POST)) && (isset($_POST['txt1'])))
{
echo $txt = $_POST['txt1'];
}
HTML:
<label for="route_no">Route No:</label><input type="text" id="route_no" name="route_no" required="required" />
<input type="button" value="Search" id="search" />
<div id="result"></div>
JavaScript:
$(document).ready(function()
{
$("#search").click(function()
{
var textboxvalue = $('input[name="route_no"]').val();
$.ajax(
{
type: "POST",
url: 'ajaxPage.php',
data: {txt1: textboxvalue},
success: function(result)
{
$("#result").html(result);
}
});
});
});
ajaxPage.php:
if(isset($_POST) && isset($_POST['txt1']))
{
echo $_POST['txt1'];
}
You have problem here
$("#sub").click(function() {
you are using id ="sub" for submit button but you are not assigning id to that button so give id to submit button as id="sub".
To get the value of the textbox you can use:
$('#elementid').val()
I have a feedback form in a pop-up div that otherwise works fine but processes SQL twice when the form results in error at first instance.
This is the html form:
<div id="stylized" class="myform">
<form id="form" method="post" name="form">
<p>Report:
<select id="fbtype" name="fbtype">
<option>Bug</option>
<option>Suggestion</option>
<option>Discontentment</option>
<option>Appreciation</option>
</select>
</p>
<p>Brief description:
<textarea name="comments" id="comments" cols="45" rows="10"></textarea>
</p>
<span class="error" style="display:none">Please describe your feedback.</span>
<span class="success" style="display:none">We would like to thank you for your valuable input.</span>
<input type="button" value="Submit" class="submit" onclick="feedback_form_submit()"/>
</form>
</div>
The feedback_form_submit() function is:
function feedback_form_submit() {
$(function() {
$(".submit").click(function() {
var fbtype = $("#fbtype").val();
var comments = $("#comments").val();
var dataString = 'fbtype='+ fbtype + '&comments=' + comments;
if(fbtype=='' || comments=='' )
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "processfeedback.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
}
And the processfeedback.php has:
include "./include/session_check.php";
include_once "./include/connect_to_mysql.php";
if (isset($_POST['fbtype'])){
$userid =$_SESSION['id'];
$fbtype=$_POST['fbtype'];
$comments=$_POST['comments'];
$sql = mysql_query("INSERT INTO feedback (userid, type, comments)
VALUES('$userid','$fbtype','$comments')") or die (mysql_error());
}
Could anyone figure out why does the form submits twice? And any suggestion to control this behaviour?
If this is actually the code you're using, you seem to have wrapped your onclick function around the $.click event-adding function:
function feedback_form_submit() {
$(function() {
// This adds a click handler each time you run feedback_form_submit():
$(".submit").click(function() {
// ... //
return false;
});
});
}
When I tried this on jsFiddle.net, I clicked Submit the first time and nothing happened, then the second time it posted twice, the third click posted three times, etc.
You should just keep it simple: take out the onclick attribute:
<input type="button" value="Submit" class="submit" />
and remove the feedback_form_submit() wrapper:
$(function() {
$(".submit").click(function() {
// ... //
return false;
});
});
This way the $.click handler function will be applied just once, when the page loads, and will only run once when Submit is clicked.
EDIT:
If your form is loaded via AJAX in a popup DIV, you have two options:
Keep your onclick but remove the $.click wrapper instead:
function feedback_form_submit() {
// ... //
}
and
<input type="button" value="Submit" class="submit" onclick="feedback_form_submit()" />
Note that you only need to return false if you're using <input type="submit" ... >; when using <input type="button" ... >, the browser does not watch the return value of onclick to determine whether to post the form or not. (The return value may affect event propagation of the click, however ...).
Alternatively, you can use jQuery's $.live function:
$(function() {
$('.submit').live('click',function() {
// ... //
});
});
and
<input type="button" value="Submit" class="submit" />
This has the effect of watching for new DOM elements as they are added dynamically; in your case, new class="submit" elements.
Your feedback_form_submit function doesn't return false and on submit click you're also posting to the server. There is no need to have onClick in:
<input type="button" value="Submit" class="submit" onclick="feedback_form_submit()"/>
Change that to:
<input type="button" value="Submit" class="submit"/>
And change your code to:
// Update: Since you're loading via AJAX, bind it in the success function of the
// AJAX request.
// Let's make a function that handles what should happen when the popup div is rendered
function renderPopupDiv() {
// Bind a handler to submit's click event
$(".submit").click(function(event) {
var fbtype = $("#fbtype").val();
var comments = $("#comments").val();
var dataString = 'fbtype='+ fbtype + '&comments=' + comments;
if(fbtype=='' || comments=='' )
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "processfeedback.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
// This is the success function for the AJAX request that loads the popup div
success: function() {
...
// Run our "onRender" function
renderPopupDiv();
}