Send button value by post request via jquery - javascript

My code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form>
<button id="test" value="123" name="test" >ok</button>
</form>
<script>
$(document).ready(function () {
$("#test").click(function() {
var combinedData = $("#test").serialize();
$.post(
"element_submit.php",
combinedData
).done(function(data) {
//alert("Successfully submitted!");
$("#result").html(data);
}).fail(function () {
//alert("Error submitting forms!");
})
});
});
</script>
<div id="result" ></div>
The element_submit.php file
<?php
//just to test it should output in the #result div
echo $_POST['test'];
?>
What I am trying to do is submit the with the value="attribute" so the data is serialized and send the post request, it's not like a submit when user insert a value and submit,What I need is to get the value attribute and submit to the php, this code is only for To simplify and illustrate what I am trying to do, because in this page I have the following buttons with ids #follow #unfollow so I need a way to get the button value to make the user follow and unfollow.

you need to serialize the form - not the elements within it .You can also have the triggering button outside the form which will prevent hte form from submitting on the button click.
<form id="testForm">
<input type="hidden" name="testInput" value="123"/>
</form>
<button name="test" id="testButton">submit</button>
...
<script>
$(document).ready(function () {
$("#testButton").click(function() {
var combinedData = $("#testForm").serialize();...
$(document).ready(function () {
$("#testButton").click(function() {
var combinedData = $("#testForm").serialize();
console.log(combinedData);
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="testForm">
<input type="hidden" value="123" name="testinput"/>
</form>
<button id="testButton">Click</button>

Straight JS might help you out. Include a function that sends the id and get the value of that id. Then just send a regular post of the value without serialize... easier.
<script>
function fetchButtonValue(theId){
var p = document.getElementById(theId).value;
alert (p);
}
</script>
<button id="myFormBtn" value ="woo"
onclick="fetchButtonValue(this.id)">My Button</button>
this works...
You could also put a class on the button let's say class="followBTN" then on a click you could just snag the value by $(this).val() I'd use this method if I had more than one button per page.

Related

Trigger script only when user press in submit button

I am executing a script through a function
<script language="javascript">
function showVariantDetail(str) {
url = "insurancemodel.php?ncvd=" + str;
getRequest(url, "txtVariantDetails");
}
</script>
The script is executing perfectly through
<div id="txtVariantDetails">
</div>
But i want the script to execute when the user press in submit button
<div class="search-box-left"></div>
<div class="search-box-right">
<input name="" type="submit" value="Calculate" class="red-btn" />
</div>
can anyone guide on how to ensure when only the user presses in submit button then the txtVariantDetails script to be processed only
Thanks
try jquery on click
$('#submitDemo').on("click",function() {
// your stuff
});
You can use click handler for the submit input.
$("input[type=submit]").on("click",function(event){
event.preventDefault();
showVariantDetail(str);
}
If you do not want to deal with jQuery:
let redButton = document.querySelector(".red-btn");
redButton.addEventListener("click",function(e){
e.preventDefault();
let buttonValue = redButton.value;
showVariantDetails(buttonValue);
});
Change Html Like below
<div class="search-box-left"></div>
<div class="search-box-right">
<input type="button" value="Calculate" class="red-btn" />
</div>
JS
<script language="javascript">
function showVariantDetail(str) {
url = "insurancemodel.php?ncvd=" + str;
getRequest(url, "txtVariantDetails");
}
$(document).on('click','.red-btn',function() {
// var str="" //get your string here
showVariantDetail(str)
});
</script>

JQuery two forms toggled, show correct form on submit

I have two forms being toggled as shown below. What I need to figure out, is how to show the correct form once it has been submitted and page refreshed. It will default to the lookup_form only currently. I have been browsing the internet for answers, but am not finding any good examples.
<div class="lookup_form">
<form method="POST" action="" id="lookup_form"></form>
</div>
<div class="nolookup_form">
<form method="POST" action="" id="nolookup_form"></form>
</div>
<a href="#" class="show"> //Firing off the script
<script>
jQuery(document).ready(function($) {
$(".nolookup_form").hide();
$(".show").click(function(){
$(".lookup_form, .nolookup_form").slideToggle("slow, linear");
});
});
</script>
Essentially I need to always show after refresh the actual form that was submitted.
I guess that you know what form you should show at the backend that produces your page, you can just pass that to javascript
<script>
var showForm2 = <?php echo $shouldShow2ndForm?'true':'false'; ?>;
if( showForm2 ){
//hide form1 and show form2
} else {
//hide form2 and show form1
}
</script>
You may use cookie or LocalStorage:
before submitting the form you can save the form id for example with:
localStorage.setItem("formId", "lookup_form");
and on dom ready you can test the value of this:
localStorage.getItem("formId")
An example:
jQuery(document).ready(function($) {
//
// on DOM Ready get formId from localstorage
//
var formId = localStorage.getItem("formId");
if (formId == null) { // never set: set the default value
formId = 'nolookup_form';
localStorage.setItem("formId", formId);
}
//
// Hide the other form
//
$("form:not(#" + formId + ")").hide();
//
// on form submit save in localstorage current form id
//
$('form').on('submit', function(e) {
e.preventDefault();
localStorage.setItem("formId", this.id);
});
$("#show").on('click', function(e) {
$("#lookup_form, #nolookup_form").slideToggle("slow, linear");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="POST" action="" id="lookup_form">
<p>First form</p>
<button type="submit">Submit lookup</button>
</form>
<form method="POST" action="" id="nolookup_form">
<p>Second form</p>
<button type="submit">Submit nolookup</button>
</form>
<button type="button" id="show">Show</button>

jquery - hide not working

By clicking on "empty cart?", I am unsetting the cart array which is working fine. Now I wanted another form to be hidden if this "empty cart" button is clicked.
html:
<form id="f1" action="checkout.php" method="post">
<input name="cust_login" type="submit" value="Continue" />
</form>
<br>
<button>empty cart?</button>
javascript:
<script>
$(document).ready(function(){
$("button").click(function(){
$("#f1").hide();
});
});
</script>
php code for unsetting array:
if (isset($_GET['cmd']) && $_GET['cmd'] == "emptycart") {
unset($_SESSION["cart_array"]);
But hide is not working here.
My question is, can we use button and link together as I have written ? If not, then how to implement it?
Try to use this:
$(document).ready(function(){
var cmd = '<?php echo $_GET["cmd"] ;?>' ;
if(cmd == "emptycart")
{
$("#f1").hide();
}
});
You can try
$(document).ready(function(){
$("button").click(function(){
$("#f1").attr('style','display: block !important')
});
});
or to add a class to style file that do the same and then just add this class when clicking on the button.
<form id="f1"
action="checkout.php"
style="<?= (isset($_SESSION['cart_array']) && count($_SESSION['cart_array']))? "display:none;": ""; ?>"
method="post">
<input name="cust_login" type="submit" value="Continue" />
</form>
<br>
<button>empty cart?</button>
On rendering form - check if cart is empty - render it on hidden state
But in this case your js code had no sense. So you can add
<script>
$(document).ready(function(){
$(document).on('click', "a[href='cart.php?cmd=emptycart']", function(ev){
ev.preventDefault();
$.get($(this).attr('href', function() {
$("#f1").hide();
});
});
});
</script>
Istead of your js code - this one prevent page reload ( which happens when you click on link ) and send request via AJAX
You can try this solution
HTML
<form id="f1" action="checkout.php" method="post">
<input name="cust_login" type="submit" value="Continue" />
</form>
<br>
<button>empty cart?</button>
JS
$(document).ready(function(){
$("button").click(function(){
//$("#f1").hide();
window.location.href = "cart.php?cmd=emptycart";
});
});

Submit and hide all labels with a containing form chekbox checked

I'd like to create a function that that submits all the formularies with a checkbox checked and hides with their respective div tags
I put the following code as an example
<html>
<script>
//the jquery function to submit all forms
$(function () {
$(".formerasemessage").each(function () {
var par_div = $(this).closest(".demo"); //finding the closest div
$(this).validate({
submitHandler: function (formbeingsubmitted) {
$.post('remove.php', $(formbeingsubmitted).serialize(), function (data) {
$(formbeingsubmitted).hide("slow");
par_div.hide('slow'); //hide the div
});
}
});
});
});
</script>
<body>
<div class="demo">
<form method="post" class="formerasemessage">
<input type="checkbox" id="checkItem"></form>
</div>
<div class="demo">
<form method="post" class="formerasemessage">
<input type="checkbox" id="Checkbox1"></form>
</div>
<div class="demo">
<form method="post" class="formerasemessage">
<input type="checkbox" id="Checkbox2"></form>
</div>
<input type="button" value="Submit all checked">
</body>
</html>
I need to reprogram the function Jquery so that it can perform the desired function.
the visual result would be something like this:
that's my inbox of Outlook, checked my mails and then I click in 'remove' and my emails are hidden and deleted
$(document).ready(function(){
$('button').click(function(){
$(":checked",".formerasemessage").each(function () {
var par_div = $(this).closest(".demo"); //finding the closest div
var form = $(this).closest('form');
form.validate({submitHandler: function () {
$.post('remove.php', form.serialize(), function (data) {
form.hide("slow");
par_div.hide('slow'); //hide the div
});
}
}).submit();
});
});
});
You could call the input using document.getElementById("inputid").value. To hide anything, use a css code :
#inputid {visibility: hidden}
You can also archieve the same effect using javascript.
Archive to execute a js function with for instance : I can be clicked
You'll find several options online (W3schools) such as onclick, onmousein, onchange ...

javascript jquery carrying html form POST data

SO I have a form that look similar to
<form action="test.php" id="checksub" method="post">
<div>
<select name="mydropdown">
<option value="buy">buy</option>
<option value="sell">sell</option>
</select>
</div>
autocomplete text input that triggers "checksub"
<input type="submit" id="checksub" name="checksub" style="visibility:hidden">
<input type="submit" id="newsbutton" name="newsbutton">
</form>
<script type="text/javascript">
$('#newbutton').click(function() {
var newaction = "cantfinditems.php";
$("#checksub").prop("action", newaction);
$('#checksub').submit();
});
</script>
Now the submit button is hidden because the autocomplete triggers it anyway, but if the user cant find what they are looking for I want a button that says "cant find what your'e looking for?"
I want this button to have a different action to the form action, ie window.location = cantfinditems.php
but I also want to carry the POST data from the form ie "mydropdown".
Thank you
Ok, so you need a second button, which calls a JavaScript function. In this function, you do a number of things:
Set the action attribute of the form to your alternate action (e.g. cantfinditems.php)
var newaction = "cantfinditems.php";
$("#form_id").prop("action", newaction);
Submit the form
$('#form_id').submit();
So a full example would be:
<script type="text/javascript">
$('#yourbuttonid').click(function() {
var newaction = "cantfinditems.php";
$("#form_id").prop("action", newaction);
$('#form_id').submit();
});
</script>

Categories