Ajax with multiple submit buttons - php

How can I change the code below so instead of a text input type with a submit button I want multiple submit buttons each with their own unique value? Everything I try just ends up with submit's value being undefined. Any help would be great!
Code source: Submit Search query & get Search result without refresh
<script type="text/javascript">
$(function() {
$("#lets_search").bind('submit',function() {
var value = $('#str').val();
$.post('db_query.php',{value:value}, function(data){
$("#search_results").html(data);
});
return false;
});
});
</script>
<form id="lets_search" action="" >
Search:<input type="text" name="str" id="str">
<input type="submit" value="send" name="send" id="send">
</form>

You can add multiple submit buttons and attach to all of them onclick event listener. When button was clicked - get the value and send with a POST request.
<script>
$(function(){
$('input[type=submit]').click(function(){
$.post('db_query.php', {value:$(this).val()}, function(data){
$("#search_results").html(data);
});
return false;
});
});
</script>
<form id="lets_search" action="">
<input type="submit" name="button1" value="hi"/>
<input type="submit" name="button2" value="bye"/>
</form>

If you want to use multiple submit buttons, you can catch the click event and determine which button was clicked. then run different Ajax submit. this also works when enter is hit.
//submit buttons
<form id="lets_search" action="" >
Search:<input type="text" name="str" id="str" />
<input type="submit" value="v1"/>
<input type="submit" value="v2"/>
//...more submit buttons
</form>
//submit func
$(function() {
$("#lets_search input[type=submit]").click(function() {
switch ($(this).val){
case 'v1':...;
case 'v2':...
}
});
});

Here is my version - which now looks very much like Bingjies because it was written while I was testing out his version
DEMO
<form id="lets_search" action="" >
Search:<input type="text" name="q" id="q">
<input type="submit" value="Google" name="send" id="google">
<input type="submit" value="Bing" name="send" id="bing">
</form>
$(function() {
$("#lets_search input[type=submit]").click(function() {
switch ($(this).val()) {
case "Bing" :
$("#lets_search").attr("action","http://www.bing.com/search");
break;
case "Google":
$("#lets_search").attr("action","https://www.google.com/search");
break;
}
});
});

Here, I would prefer to Vamsi's solution n Why not Sanjeev mk?
Give some extra thought on prefering the solution.
case: If there are mulitple submit buttons
If the user is in the text field and hits enter, the system will assume the first submit button was hit.
So, here, it would be good to go for not having mulitple submit
buttons for end user point of view

You can have multiple submit buttons in the form, no problem. They may have the same name, type etc, but just assign them different values. Like Submit Button 1 can have value="hi" and Button 2 can have value="bye".
Then when the action function is called for the button, all you have to do when entering the function is do a check with: $(this).val
HTML:
<input type="submit" name="button1" value="hi"/>
<input type="submit" name="button2" value="bye"/>
jQuery:
$(function() {
$("#lets_search").bind('submit',function() {
var value = $(this).val();
if(value == "hi")
do_something;
else
do_something_else;
});
});

Related

how to show error in jquery after clicking submit button

My problem is that after clicking on submit button the page will go to php file any way my html code is like this
<form action="register.php" method="post">
<input type="text" name="name" id="name"><div id="adiv"></div>
<input type="submit" value="submit" id="button">
</form>
and my jquery code goes like this
$('#name').focusout(function(){
if($('#name').val().length==0){
$('#adiv').html("please enter name")
}
});
$('#button').click(function(){
if($('#name').val().length==0){
$('#adiv').html("please enter your name")
}
});
but after clicking submit button it redirects to php file and doesn't show any error and store blank data in the database.
Because your input type is submit you can either change the type to button or add event.preventDefault() to avoid automatic passing of form
use event.preventDefault()
$('#button').click(function(e) {
e.preventDefault();//this will stop form auto submit thus showing your error
if ($('#name').val().length == 0) {
$('#adiv').html("please enter your name")
}
});
Or
<input type="submit" value="submit" id="button">
change to
<input type="button" value="submit" id="button">//also prevent form auto submit thus will show the error
Well you need to stop the code to execute after error has been detected. For example you can simple use return false or return:
$('#name').focusout(function() {
if ($('#name').val().length == 0) {
$('#adiv').html("please enter name")
}
});
$('#button').click(function() {
if ($('#name').val().length == 0) {
$('#adiv').html("please enter your name")
return false;//add this
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="register.php" method="post">
<input type="text" name="name" id="name">
<div id="adiv"></div>
<input type="submit" value="submit" id="button">
</form>
I strongly recommend never to assign validation to a submit button click.
Instead assign the submit event handler of the form.
I also added trim and removed the content of the error from the code.
$(function() {
$('#name').focusout(function() {
var empty = $.trim($('#name').val()).length == 0;
$('#adiv').toggle(empty);
});
$('#form1').on("submit",function(e) {
$('#name').focusout();
if ($('#adiv').is(":visible")) {
e.preventDefault()
}
});
});
#adiv { display:none }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="register.php" method="post" id="form1">
<input type="text" name="name" id="name">
<div id="adiv">please enter name</div><br/>
<input type="submit" value="submit" id="button">
</form>
Please check this
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post">
<input type="text" name="name" id="name">
<div id="adiv"></div>
<input type="button" value="submit" id="button">
</form>
<script>
$(document).ready(function(){
$('#button').on('click',function(){
if($('#name').val() == ''){
$('#adiv').text("Please enter name!!");
}else{
$('#adiv').text($('#name').val());
}
})
})
</script>
try this..:D
function validateFunction(){
if(document.getElementByID('name').value.length==0){
document.getElementByID('adiv').innerHTML = "please enter your name";
return false;
}
return true;
}
<input type="submit" value="submit" id="button" onclick="return validateFunction();" />
$('your-form').on('submit', function(e) {
e.preventDefault();
//your code bere
});
preventDefault stop the normal submit behaviour of your browser so that you can trigger any event you want

Save Jquery var sum in DB MySQL

I'm using jquery to sum values of input checkbox and i need to save the sum into DB MySQL but how can i put the value in a php var? I don't know how can i do this.
Can someone help me out? I'm newbie in jquery :/
Here's the code i'm using:
<script type="text/javascript">
$(document).ready(function () {
function recalculate() {
var sum = 0;
$("input[type=checkbox]:checked").each(function() {
var val = $(this).attr("preco").replace(',', '.');
sum += parseFloat(val);
});
$("#output").html(sum);
}
$("input[type=checkbox]").change(function() {
recalculate();
});
});
</script>
<?php
if (isset($_POST['submit'])){
$transporte = $_POST['metodoenvio'];
(... save into DB)
}
?>
<span id="output"></span> // the sum in html shows up here
<form class="cmxform" id="pedidoForm" method="post" action="">
<input type="checkbox" name="metodoenvio" class="metodoenvio" preco="20" />
<input type="checkbox" name="metodoenvio" class="metodoenvio" preco="10" />
(...)
<input type="submit" name="submit" id="submit" value="submit"/>
</form>
Take a hidden type variable with some id in form tag and put value in hidden variable by jquery like:
$("#hidden_var").val(sum);
Then at the end submit the form
add new hidden input field to the form to hold the sum
<form class="cmxform" id="pedidoForm" method="post" action="">
//add new hidden input field to have the sum
<input id="sum_input" name="sum" type="hidden"/>
<input type="checkbox" name="metodoenvio" class="metodoenvio" preco="20" />
<input type="checkbox" name="metodoenvio" class="metodoenvio" preco="10" />
(...)
<input type="submit" name="submit" id="submit" value="submit"/>
</form>
//Then use the jquery to put the sum to input id sum
function recalculate() {
var sum = 0;
$("input[type=checkbox]:checked").each(function() {
var val = $(this).attr("preco").replace(',', '.');
sum += parseFloat(val);
});
$("#output").html(sum);
//jquery to put sum into form
$("#sum_input").val(sum);
}
You should split your php server side scripts out of your html/js client side pages. create a separate php page so process the data and call it through an ajax call.
change your submit button to just be a button and attach an onclick event to call a function that will sum the checkboxes and then initiate the and ajax request.
<script>
function sumChecked(){
i = 0;
$.each($('#pedidoForm:ckecked), function({
i++;
});
$.ajax({
url:"yourPHPpage.php",
type:"POST",
data:{"sumVar":i},
success: function(data){
alert ("Process Complete");
}
})
}
...
</script>
...
<form class="cmxform" id="pedidoForm">
<input type="checkbox" name="metodoenvio" class="metodoenvio" preco="20" />
<input type="checkbox" name="metodoenvio" class="metodoenvio" preco="10" />
(...)
<input type="button" name="submit" id="submit" value="submit" onClick="sumChecked()"/>
</form>
then on your php page catch the $_POST['sumVar'] variable sent through from the form and do whatever you want to server-side with that info.

Doesn't get value with jQuery

<form method="POST">
<div id="showme">Show me <?php echo $_POST['name']?></div>
Send the value<input type="radio" name="name" value="ja"/>
<input type="submit" id="submit" name="submit" value="BEREKENEN! ">
</form>
<script>
$(document).ready(function () {
$('#showme').hide();
$('#submit').click(function(e) {
e.preventDefault();
$('#showme').fadeIn(5000);
});
});
</script>
This code won't send the value of the radiobutton to the showme div.
I can't receive the $_POST['name'] when I use hide() and fadeIn() between the <script> tags.
Whenever I don't use jQuery it sends the data - when using it , it won't let me send the value.
How do I fix this problem, this is just an example of 1 radio button. I have a list of 6 radiobuttons that need to be sent to PHP section in the same file, I don't want to make another file for this.
This code will FadeIn the requested div, it shows me Show me but it won't show the value where I ask for with the line <?php echo $_POST['name']?>
PHP is parsed on the server. <?php echo $_POST['name']?> has already been evaluated and echod to the page long before any of the submission stuff happens. What you need is to use AJAX.
You can replace the submit button with just a regular button, remove the <form> element entirely even.
jQuery:
$('#submit').on('click', function(evt) {
var e = evt || window.event;
e.preventDefault();
$.post('page.php', { name: $('input[name="name"]').val() }, function ( data ) {
$('#showme').append(data).fadeIn(5000);
});
return false;
});
(if you do what I did below turning submit into button, you dont need the e.preventDefault())
PHP:
if(isset($_POST['name'])) {
echo $_POST['name'];
return;
}
HTML:
<div id="showme">Show me </div>
<label for="name">Send the value</label><input type="radio" name="name" value="ja"/>
<input type="button" id="submit" name="submit" value="BEREKENEN!">
I'm not so sure you can get a non-BOOLEAN value from a radio button with PHP though. You're probably better off using <input type="hidden" value="ja" /> or maybe type="text".

How to have two buttons in a same form to do different actions in ajax?

I have a form, which take name from form and it sends to javascript codes and show in php by Ajax. these actions are done with clicking by submit button, I need to have another button, as review in my main page. how can I address to ajax that in process.php page have "if isset(submit)" or "if isset(review)"?
I need to do different sql action when each of buttons are clicked.
how can I add another button and be able to do different action on php part in process.php page?
<script type="text/javascript">
$(document).ready(function(){
$("#myform").validate({
debug: false,
submitHandler: function(form) {
$.post('process.php', $("#myform").serialize(), function(data) {
$('#results').html(data);
});
}
});
});
</script>
<body>
<form name="myform" id="myform" action="" method="POST">
<label for="name" id="name_label">Name</label>
<input type="text" name="name" id="name" size="30" value=""/>
<br>
<input type="submit" name="submit" value="Submit">
</form>
<div id="results"><div>
</body>
process.php:
<?php
print "<br>Your name is <b>".$_POST['name']."</b> ";
?>
You just need to add a button and an onclick handler for it.
Html:
<input type="button" id="review" value="Review"/>
Js:
$("#review").click(function(){
var myData = $("#myform").serialize() + "&review=review";
$.post('process.php', myData , function(data) {
$('#results').html(data);
});
}
);
Since you have set a variable review here, you can use it to know that is call has come by clicking the review button.
Bind the event handlers to the buttons' click events instead of the form's submit event.
Use the different event handler functions to add different pieces of extra data to the data object you pass to the ajax method.

Confirm before a form submit

I have searched for an answer but couldn't find one!
I have a simple form,
<form action="adminprocess.php" method="POST">
<input type="submit" name="completeYes" value="Complete Transaction" />
</form>
How would I adjust this to confirm before processing the form?
I tried onclick, but couldn't get it working.
Any ideas?
UPDATE - What I now have.
<script type="text/javascript">
var el = document.getElementById('myCoolForm');
el.addEventListener('submit', function(){
return confirm('Are you sure you want to submit this form?');
}, false);
</script>
<form action="adminprocess.php" method="POST" id="myCoolForm">
<input type="submit" name="completeYes" value="Complete Transaction" />
</form>
HTML:
<form action="adminprocess.php" method="POST" id="myCoolForm">
<input type="submit" name="completeYes" value="Complete Transaction" />
</form>
JavaScript:
var el = document.getElementById('myCoolForm');
el.addEventListener('submit', function(){
return confirm('Are you sure you want to submit this form?');
}, false);
Edit: you can always use inline JS code like this:
<form action="adminprocess.php" method="POST" onsubmit="return confirm('Are you sure you want to submit this form?');">
<input type="submit" name="completeYes" value="Complete Transaction" />
</form>
<input type="submit" onclick="return confirm('Are you sure you want to do that?');">
The correct event is onSubmit() and it should be attached to the form. Although I think it's possible to use onClick, but onSubmit is the correct one.
If you're already using jQuery.. you can use an event handler to trigger before submission
$(document).ready(function() {
$("#formID").submit(function(){
// handle submission
});
});
Reference:
http://api.jquery.com/submit/
var submit = document.querySelector("input[type=submit]");
/* set onclick on submit input */
submit.setAttribute("onclick", "return test()");
//submit.addEventListener("click", test);
function test() {
if (confirm('Are you sure you want to submit this form?')) {
return true;
} else {
return false;
}
}
<form action="admin.php" method="POST">
<input type="submit" value="Submit" />
</form>
In my case, I didn't have a form ID and couldn't add inline in the form tag. I ended up with the following jQuery code
var form = $("form").first();
form.on('submit', function() {
return confirm('Are you sure you want to submit this form?');
});
if you have more then one submit buttons that do different actions you can do it this way.
<input TYPE=SUBMIT NAME="submitDelete" VALUE="Delete Script" onclick='return window.confirm("Are you sure you want to delete this?");'>

Categories