Javascript button onclick get input value and submit post request - javascript

I have a form that looks like this:
<form method="post">
<input type="text" name="username" id="username">
<input type="text" name="password" id="password">
<select id="item" name="item">
<option value="1">Blue</option>
<option value="3">Pink</option>
<option value="4">Black</option>
</select>
<input type="button" id="submit" onclick="addItem();" name="submit" value="Submit"/>
</form>
How can I use javascript to call the addItem() function and send a post request to test.php with the value of the username as username, password as password, and item as item?
EDIT:
This is the only code in my addItem(); function so far:
$.post("http://test.com/test.php",{username:username, password:pword, item:item}, function(data) {
$('#message').html(data);
});
However, I'm wondering, how can I grab the data from all of the input fields and put it into the code I have above? This is because the function is called through a button and NOT a submit button.

To grab the data, jQuery has beautiful function inside. based upon your edited question you can try this :
var username = $("#username").val();
var pword = $("#password").val();
var item = $("#item option:selected" ).text();
// you can check the validity of username and password here
$.post("http://test.com/test.php",{username:username, password:pword, item:item},
function(data) {
$('#message').html(data);
});
(again, if you are following this way then there is no use of form tag.)

Using jQuery you can send the form as simply as doing:
$('form').submit(function(){
$.post('path/to/server/file', $(this).serialize(),function(response){
/* do something with returned data from server*/
});
return false; /* prevent browser submitting form*/
});
$.post is a shortcut method of $.ajax
jQuery $.ajax() docs
jQuery $.post() docs

give a form name and a action url, then use form.sumit() method to post form data
<form method='post' name='myform' action='test.php'>
...
<script type="text/javascript">
function addItem() {
document.myform.submit();
}
</script>

<form action="your.php" onSubmit="return addItem()">
This should do it
then in js
function addItem() {
//whatever you want to do
return true;
}
=============================================================
I see you are using Ajax, if you want to do it, then you should do the following:
$(document).on("click", "#yoursubmitbuttonID", function(e){
var password = $("#password").val();
var username = $("#username").val();
//send Ajax here
}

Related

Issue with AJAX form submit

Required the form to be submitted via an ajax call and you will intercept the result and update your page. You never leave the index page.
I'm having trouble having the ajax call working
<form action="/cart" method="post" id="addProduct">
Quantity: <input type="number" name="quantity">
<button type="submit">Add to Cart</button>
<input type="hidden" name="productid" value="{{id}}">
<input type="hidden" name="update" value="0">
</form>
var form = $('#addProduct');
form.submit(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "/cart",
data: form,
dataType: "json",
success: function(e) {
window.location.href = "/";
}
});
})
you can use
JavaScript
new FormData(document.querySelector('form'))
form-serialize (https://code.google.com/archive/p/form-serialize/)
serialize(document.forms[0]);
jQuery
$("form").serializeArray()
You are changing the whole meaning of the ajax call. Ajax call is used for updating something without page refresh. In your case on success, you are changing the URL which is not right. Remove window.location.href = "/"; from your code and try to append messages or alert something like alert('Product is added to cart');
Your ajax call is not sending data to the server. Use formdata object or serialize() to get form input values then send it to the server.
Use
var form = new FormData($('#addProduct')[0]);
OR
var form = $("'#addProduct").serialize();
Instead of
var form = $('#addProduct');
And on success, send response from server and update your DOM in success function. Don't use window.location.href = "/";
To update your document after success you can use append(e) to update your DOM
<form method="post" id="addProduct">
Quantity: <input type="number" name="quantity">
<button type="submit">Add to Cart</button>
<input type="hidden" name="productid" value="2">
<input type="hidden" name="update" value="0">
</form>
<div id="display">
</div>
$(function(){
$("#addProduct").submit(function(e){
e.preventDefault();
var quantity = $(this).children("input[name=quantity]").val();
var productid = $(this).children("input[name=productid]").val();
var update = $(this).children("input[name=update]").val();
$.ajax({
type:"post",
url:"/cart.php",
data:{update:update,quantity:quantity,productid:productid},
success: function(feedback){
$("#display").html(feedback);
},
error: function(err){
alert("error");
}
});
});
});
I update my answer and i use the div with id display to show my data return from ajax success

Using hidden inputs to POST JavaScript function result

I have a single form input on my homepage userinput. The homepage also contains a JavaScript function that uses that userinput value to calculate a result.
<form action="/run.php" method="POST" target="_blank">
<input type="hidden" id="idg" value="<?php echo $rand ?>"> // gets random url, can be ignored
<input type="text" name="userinput" id="userinput">
<button type="submit" onclick="calcResult();">Go!</button>
</form>
<script>
function calcResult() {
var userinput = document.getElementById('userinput').value;
var result = userinput + 10; // want to POST result in a hidden input field w/ form
</script>
I'm trying to find a way in which a user can enter their input, submit the form, the JavaScript takes that userinput and calculates a result, then that result is POST'ed along with the userinput in the form.
The problem I can forsee with this method is that:
The JavaScript function needs the userinput before it can calculate the result. However, the only way to get the userinput is to submit the form, which means the form data will be POSTed before the JavaScript result is returned.
My attempted solution(s):
I've been attempting to use AJAX (Unable to access AJAX data [PHP]) and have been consistently running into issues with that.
I was wondering whether it's possible to use a button (type="button"), instead of a submit (type="submit") for the form. Then just use that button to call the JS function, then (somehow) submit the form (with the JS function result) after the JS function has completed? (either with plain JS or jQuery).
there are multiple approaches to do this,
i'm gonna use jquery here instead of pure javascript to simplify it
[without submission] you may check the event change
$('#userinput').change(function (e) {
// make some calculation
// then update the input value
});
[with form submission] you will disable the submission using the object preventDefault inside the submit event
$('#userinput').submit(function (e) {
e.preventDefault();
// make some calculation
// then update the input value
// your ajax goes here OR resubmission of your form
// to resubmit the form
$(this).submit();
});
What you will find useful in this scenario is event.preventDefault();
function calcResult(e) {
// Prevent the default action of the form
e.preventDefault();
var userinput = document.getElementById('userinput').value;
var result = userinput + 10;
// Do whatever else you need to do
// Submit the form with javascript
document.getElementById("myForm").submit();
}
I believe this is what you are looking for. A way of having the information computed over PHP, without a page request. This uses a form and then serializes the data, then transmits it to PHP and displays the result from run.php.
Note:
I did change your id to a name in the HTML so the code would serialize properly. I can change this per request.
index.php
$rand = rand(10,100);
?>
<form action="javascript:void(0);" id="targetForm">
<input type="hidden" name="idg" value="<?php echo $rand ?>">
<input type="text" value="12" name="userinput" id="userinput">
<button onclick="ready()">Go!</button>
</form>
<div id="result"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
function ready() {
$.post('run.php', $('#targetForm').serialize(), function (data) {
$("#result").html(data);
})
}
</script>
run.php
<?php
echo floatval($_POST['userinput']) * floatval($_POST['idg']);
?>
Nowhere in your question is there any indicator that your task requires AJAX. You're just trying to change an input value right when you submit. AJAX is not needed for that.
First, attach an onsubmit event handler to your form instead of using an onclick attribute on your button. Notice, we are not stopping the form from submitting with return false as we still want the form to submit.
For convenience, let's add an ID to your form and let's add a hidden input field to store the calculated value.
(Side-remark: you don't need to use document.getElementById(ID) if the ID is a string with no dashes i.e. document.getElementById('userinput') can be shortened to just userinput )
<form action="/run.php" method="POST" target="_blank" id="theform">
<input type="hidden" id="idg" value="<?php echo $rand ?>">
<input type="text" name="userinput" id="userinput">
<input type="hidden" name="hiddeninput" id="hiddeninput">
<button type="submit">Go!</button>
</form>
<script>
// this will be called right when you submit
theform.onsubmit = function calcResult() {
// it should update the value of your hidden field before moving to the next page
hiddeninput.value = parseInt(userinput.value, 10) + 10;
return true;
}
</script>
One way is by onSubmit
<form action="/run.php" method="POST" onSubmit="return calcResult()">
<input type="hidden" id="idg" value="<?php echo $rand ?>"> // gets random url, can be ignored
<input type="text" name="userinput" id="userinput">
<button type="submit" onclick="calcResult();">Go! </button>
</form>
And when you return true then only form will submit.
<script>
function calcResult() {
var userinput = document.getElementById('userinput').value;
var result = userinput + 10; // want to POST result in a hidden input field w/ form
return true;
}
</script>

PHP-AJAX passing input text to action url directly with ajax

Html:
<form id="yourFormId" method="POST" action="/">
{{csrf_field()}}
<div id="check" class="input-group margin-bottom-sm">
<input class="form-control" type="text" name="find" placeholder="Search">
<button type="submit"><div id="search" class="input-group-addon"><i class="fa fa-search"></i></div></button>
</div>
</form>
JS:
<script>
$(function(){
$(".form-control").on('change',function(e){
$("#yourFormId").attr("action","/" + this.val() );
});
});
</script>
That script doesn't work. I need an ajax solution to pass dynamically my input text to action url. How to do that?
Try this:
<script>
$(function(){
$(".form-control").on('change',function(e){
$("#yourFormId").attr("action","/" + $(this).val() );
});
});
</script>
i think u want to submit your form with ajax request with dynamic text field value.
you can use simple java script function on change or click event whatever you want or with ajax request
you simple use like this
window.location.href="/"+$(this).val();
return false;
This code will submit your form on keyup (as soon as you stop typing)
var timerid;
jQuery("#yourFormId").keyup(function() {
var form = this;
clearTimeout(timerid);
timerid = setTimeout(function() { form.submit(); }, 500);
});
In this code you intercept the form submit and change it with an ajax submit
$('.form-control').bind('keyup', function() {
$("#yourFormId").submit(function (event) {
event.preventDefault();
$.ajax({
type: "post",
dataType: "html",
url: '/url/toSubmit/to',
data: $("#yourFormId").serialize(),,
success: function (response) {
//write here any code needed for handling success }
});
});
});
To use the delay function you should use jQuery 1.4. The parameter passed to delay is in milliseconds.

Generating multiple AJAX codes for dynamically generated elements in Javascript,

I have a script which dynamically generates form elements with their corresponding ID, for e.g.
response from MySQL db says - 4, then
<form ID="form0">
<Input>....
<Button type="submit>....
</form>
<form ID="form1">
<Input>....
<Button type="submit>....
</form>
<form ID="form2">
<Input>....
<Button type="submit>....
</form>
<form ID="form3">
<Input>....
<Button type="submit>....
</form>
once this list of forms are generated, I have an AJAX code which detects the submit buttons and send the input values off to db via PHP page, something like this below,
$(document.body).on('submit', '#form' ,function(e){
e.preventDefault();
var postData = $("#form").serialize();
$.post("../../../functions/processing.php",postData,function(data, status){
var selectedData = JSON.parse(data);
$.each( selectedData, function( i, val ) {
// do something here...
});
});
});
So my question is that, for the list of forms, I have to somehow generate multiple of this AJAX code for form0, form1, form2, form3.. and because I can't anticipate how many forms will be generated, I can't just write one AJAX code like the one above.. is there anyway to dynamically generate AJAX codes for dynamically generated multiple forms?
Give the form a class that identifies it as a form to be handled by your AJAX handler. Then, inside the handler, reference this to get the form element that is being submitted.
<form ID="form0" class="js-ajax-form">
<input>....
<button type="submit>....
</form>
Handler
$(document).on('submit', '.js-ajax-form' ,function(e){
e.preventDefault();
var postData = $(this).serialize();
$.post("../../../functions/processing.php",postData,function(data, status){
var selectedData = JSON.parse(data);
$.each( selectedData, function( i, val ) {
// do something here...
});
});
});

Get a submitted form value using jQuery, have more than 1 form with the same class name

I've tried to search for an answer here but there are no answers that match what I need. I have more than 1 form with class name .sbt-form:
<form class='sbt-form'>
<input name='kord' val=1/>
</form>
<form class='sbt-form'>
<input name='kord' val=2/>
</form>
<form class='sbt-form'>
<input name='kord' val=3/>
</form>
When one form is submitted (let's say the third one) I want just to get the value of input element with name = 'kord'
How do i do this using jQuery?
You can attach a submit handler to the forms and search within them for the element you want to find. Try this:
$('.sbt-form').submit(function(e) {
e.preventDefault(); // stop the form submission to the server. Comment this if not needed.
var inputValue = $(this).find('input[name=kord]').val();
});
Try this :
$("mySubmitButton").click(function () {
$(this).closest(".sbt-form").find("input[name='kord']").val();
});
try
$('.sbt-form').click(function() {
$(this).find("input[name='kord']").val();
});
OR you can get whole form's value with serialize() function on submitting the form:
JS Code:
$(".sbt-form").submit(function(e){
e.preventDefault();
console.log($(this).serialize());
});

Categories

Resources