multiple submit buttons different actions with passing variables - javascript

I have a form like the code below (called index.php) with multiple submit buttons. I'd like to have different php actions on submit buttons. The 1st button without refreshing the browser's page and of course with passing the variables. The other with normal action which can redirect to a new page (here form_submit.php). I managed to make the 1st button working with the help of this topic but I can't distinguish the 2nd button from the 1st one. Is there any way to switch between functionality of these buttons ?
<? php>
if($_POST['formSubmit'] == "Next") {
$var1 = $_POST['name1'];
$var2 = $_POST['name2'];.
session_start();
$_SESSION['variable1'] = $var1;
$_SESSION['variable2']= $var2;
header("Location: form_submit.php");
exit;
}
?>
<html>
<body>
<form action="index.php" method="post">
<input type="text" name="name1" id="name1" maxlength="50" value="<?=$var1;?>" />
<input type="text" name="name2" id="name2" maxlength="50" value="<?=$var2;?>" />
<input type="submit" name="dataSubmit" value="Insert Data" />
<input type="submit" name="formSubmit" value="Next" />
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'data_submit.php',
data: $('form').serialize(),
});
});
});
</script>
</form>
</body>
</html>

As soon as 1st button doesn't actually need to make submit you can set 'onClick' event handler on it and make it just 'button'. In this case only JS will be triggered when you press the button and browser will not submit the form. Here is what I mean:
<input type="button" id="justButton" name="dataSubmit" value="Insert Data" />
<input type="submit" name="formSubmit" value="Next" />
<script>
$(function () {
$('#justButton').on('click', function (e) {
$.ajax({
type: 'post',
url: 'data_submit.php',
data: $('form').serialize(),
});
});
});
</script>

First, add clicked class to button:
$('.submitButton').click(function(){
$('.submitButton').removeClass('clicked');
$(this).addClass('clicked');
});
Than in submit event check button:
$('form').submit(function(){
var button = $('.submitButton.clicked');
if (button.attr('id') == 'name1') {
...
} else {
...
}
return false;
});

Related

JavaScript ActiveElement is form not button with Safari

I have a list of forms on my site with JS/AJAX that submits the forms on click. The JavaScript determines the submit type based on the active element. This has been working find across multiple browser.
Problem: Basically Safari (Version 10.0.2) on MAC considers the activeElement the form instead of the button so the getAttribute returns null. Is there a way to get the clicked element? I need to know which button the user clicked.
HTML Stuff:
<div id="#Records">
<form action="update.php" method="post">
...
<input name="submit" type="submit" data-action="send" value="send stuff" />
<input name="submit" type="submit" data-action="update" value="update" />
<input name="submit" type="submit" data-action="delete" value="delete" />
</form>
</div>
JavaScript stuff
$("#Records form").submit(function (e) {
e.preventDefault();
var url = this.action;
var data = $(this).serializeArray();
var action = document.activeElement.getAttribute('data-action');
data.push({ name: 'submit', value: action });
$.ajax({
type: "POST",
data: data,
cache: false,
url: url
}).done(function (data) {
$("#Records").html(data);
}).fail(function (result) {
ShowMessage("Error updating record!");
});
return false;
});
Can't you get the element using e.currentTarget instead of the active element? Something like
var action = $(e.currentTarget).attr('data-action');
(I'm assuming button click leads to the submit)
Ok, based on Tiny Giant and other comments I have changed the code to this. Not sure it is the best method but seems to work everywhere I have tested.
note simplified, comments welcome
HTML
<div id="#Records">
<form action="update.php" method="post">
...
<input type="button" onclick="return $(this).processRequest(this, 'send');" data-action="send" value="send stuff" />
<input type="button" onclick="return $(this).processRequest(this, 'update');" data-action="update" value="update" />
<input type="button" onclick="return $(this).processRequest(this, 'delete');" data-action="delete" value="delete" />
</form>
</div>
JavaScript
jQuery.fn.processRequest =
function(button, action)
{
var form = $(button).parents('form');
var url = form[0].action;
var data = $(form).serializeArray()
data.push({ name: 'submit', value: action });
$.ajax({
type: "POST",
data: data,
cache: false,
url: url
}).done(function (data) {
$("#Records").html(data);
}).fail(function (result) {
ShowMessage("Error updating record!");
});
return false;
}

PHP Form with Button

I have some experience in JAVA GUI programming and I want to achieve the same in a PHP form.
Situation: I want to have a php form with a submit button. When the button is pressed an ActionEvent should be called to update another part of the form.
How to implement such a feature with HTML,PHP,JAVASCRIPT ?
Load latest version of jQuery:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
HTML code:
<form>
<button type="button" class="formLoader">Click button</button>
<div id="formContentToLoad"></div>
</form>
jQuery code:
<script type="text/javascript">
$(function(){
$(".formLoader").click(function(){
$("#formContentToLoad").load("scriptToRun.php");
});
});
</script>
Whatever markup you need to update in the form, can be put into scriptToRun.php
Use jQuery
Javascript
$(document).ready(function() {
$(".myForm").submit(function() {
$.ajax({
type: "POST",
url: "myForm.php",
data: $(this).serialize(),
success: function(response) {
// todo...
alert(response);
}
})
})
});
Html
<form method="POST" class="myForm">
<input type="text" id="a_field" name="a_field" placeholder="a field" />
<input type="submit" value="Submit" />
</form>
PHP
<?php
if(isset($_POST)) {
$a_field = $_POST["a_field"];
// todo..
}
If you want to use PHP and HTML to submit a form try this:
HTML Form
<form action="" method="post">
<input type="text" placeholder="Enter Name" name="name" />
<input type="submit" name="sendFormBtn" />
</form>
PHP
<?php
if(isset($_POST["sendFormBtn"]{
$name = isset($_POST["name"]) ? $_POST["name"] : "Error Response Here";
//More Validation Here
}

Submit jQuery ajax Form with multi buttons and PHP

here is my problem:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<form id="roomform" action="room.php" method="POST">
<button name="room" value="Room01">IMG01</button>
<button name="room" value="Room02">IMG02</button>
<button name="room" value="Room03">IMG03</button>
<button name="room" value="Room04">IMG04</button>
<button name="room" value="Room05">IMG05</button>
<button name="room" value="Room06">IMG06</button>
<button name="room" value="Room07">IMG07</button>
<button name="room" value="Room08">IMG08</button>
<button name="room" value="Room09">IMG09</button>
<button name="room" value="Room10">IMG10</button>
</form>
<script type="text/javascript">
var frm = $('#roomform');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert('ok');
}
});
ev.preventDefault();
});
</script>
</body>
</html>
PHP using $_POST['room'] to get the room name Room01-Room10(Room100 maybe?) and doing something special.
It works good.
Now I need to do this using Ajax. Above code seems ok, but I cannot get any data(Room01-Room10) from it.
then I found this:
<form action="/vote/" method="post" class="vote_form">
<input type="hidden" name="question_id" value="10" />
<input type="image" src="vote_down.png" class="vote_down" name="submit" value="down" />
<input type="image" src="vote_up.png" class="vote_up" name="submit" value="up" />
</form>
$(".vote_form").submit(function() { return false; });
$(".vote_up, .vote_down").click(function(event) {
$form = $(this).parent("form");
$.post($form.attr("action"), $form.serialize() + "&submit="+ $(this).attr("value"), function(data) {
// do something with response (data)
});
});
but it seems not suitable to my case, my all buttons with same name="room" for $_POST['room'] and no class.
and this not works:
$(function() {
$('input[name=room]').click(function(){
var _data= $('#roomform').serialize() + '&room=' + $(this).val();
$.ajax({
type: 'POST',
url: "room.php?",
data:_data,
success: function(html){
$('div#1').html(html);
}
});
return false;
});
});
anyone know how to solve this problem?
Your (last) code is not sending AJAX requests because you attached the handler to the wrong input selector. Your buttons are button elements, not input elements. This should work:
$('button[name=room]').click(function() { ...
Edit:
Your first code isn't working because your buttons are just buttons. You have to add the type attribute to let your form know you're pressing a submit button: <button type="submit"...>
The serialize() method does not collect the data from a button element. Take a look to the documentation on this link: https://api.jquery.com/serialize/. In your code I would assume that your data object is empty.
Also if you post several form controls (serialized) , they should have different name attributes.

How to prevent from page refresh on submit button click

i have form with one input and one submit button.
<form method='POST' action='' enctype='multipart/form-data' id="form_search">
<input type='hidden' name="action" id="form_1" value='1' />
</span><input id="query" type="text" name="mol" value="">
<input type='submit' value='Search' name="Search" id="Search" />
on form submission form input data goes to php below code
if (isset($_POST['Search'])) {
$_SESSION["query"] = $_POST["mol"];
$_SESSION["action"] = $_POST["action"];
}
i want to avoid page refresh on form submission. i tried e.preventDefault() and return false;
methods in my java script but not working(this methods helping me from page refresh but does not allowing me to send data to php code)
please help me out of this problem, please suggest working ajax code for this problem.
Page refresh will delete you previous data so to reserve it you can use $.post() or $.ajax()
You can prevent page refreshing by adding one of these two things in event handler function
for pure js
return false;
for jquery you can use
e.preventDefault(); // e is passed to handler
Your complete code will be something like
using $.post() in js
function checkfunction(obj){
$.post("your_url.php",$(obj).serialize(),function(data){
alert("success");
});
return false;
}
html
<input type='submit' onclick="return checkfunction(this)" />
or same effect with onsubmit
<form onsubmit="return checkfunction(this)" method="post">
Without ajax you can simply add the checked attribute in PHP. So for example if your radio group has the name radio and one has value a, the other b:
<?php
$a_checked = $_POST['radio'] === 'a';
$b_checked = $_POST['radio'] === 'b';
?>
<input type="radio" name="radio" value="a"<?=($a_checked ? ' checked' : '')?>></input>
<input type="radio" name="radio" value="b"<?=($b_checked ? ' checked' : '')?>></input>
So when a user submits the form and you display it again, it will be like the user submitted it even the page refreshes.
<input type="radio" name="rbutton" id="r1">R1
<input type="radio" name="rbutton" id="r2">R2
<input type="button" id="go" value="SUBMIT" />
<div id="result"></div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#go').click(function(){
var val1 = $('input:radio[name=rbutton]:checked').val();
var datastring = "partialName="+val1;
$.ajax({
url: "search.php",
type: "POST",
data: datastring,
success: function(data)
{
$("#result").html(data);
}
});
});
});
</script>

Submit form to other page

I need help with submiting data form #send_form to #f_from in another page.
<script type="text/javascript">
function post_form() {
$('#send_form').action = "form01.html";
$('#send_form').submit();
return false;
}
</script>
<form id='send_form' action='form01.html' method='POST' onsubmit="post_form();">
<input type="text" name="f_in01" value="User" />
<input type="text" name="f_in02" value="12345" />
<input type="submit" />
</form>
The form01.html
<script type="text/javascript">
function f_res()
{
var res01=document.f_form.f_in01.value;
var res02=document.f_form.f_in02.value;
var result = res01 + " " + res02;
document.f_form.f_out01.value=result;
}
</script>
<form id="f_form" onSubmit="f_res();return false;">
<input type="text" name="f_in01" /><br>
<input type="text" name="f_in02" /><br>
<br>
<input type="submit" onClick="f_res();" value="Enter w/Sub" /><br>
<input type="text" name="f_out01" />
</form>
Now it doesn't work. The data doesn't post in page01.html
Have you tried
$('#send_form').attr('action', "form01.html");
instead of
$('#send_form').action = "form01.html";
check out this fiddle
Amin is right, but in jQuery, when an event handler returns false, it amounts to the same as e.preventDefault(); e.stopPropagation(). Essentially, you cancel the event. Try returning true, instead of false.
If you don't want the page to change, you'll have to look at AJAX to post the form data.
You want AJAX for this something like:
$('#button').click(function(){
$.ajax({
type:"POST", //php method
url:'process.php',//where to send data...
cache:'false',//IE FIX
data: data, //what will data contain (no SHIT Sherloc...)
//check is data sent successfuly to process.php
//success:function(response){
//alert(response)
//}
success: function(){ //on success do something...
$('.success').delay(2000).fadeIn(1000);
//alert('THX for your mail!');
} //end sucess
}).error(function(){ //if sucess FAILS!!
alert('An error occured!!');
$('.thx').hide();
});
});

Categories

Resources