Use ajax to send a $_POST variable to php - javascript

I have a form with 2 submit buttons:
<form id="drinksForm" action="drinksHandler.php" method="POST">
<label for="drinks">Number of drinks</label>
<input type="number" class="form-control" name="drinks" min="1" max="30" required="required">
<input type="submit" name="buttonDrinks" class="btn btn-success" value="Got drinks">
<input type="submit" name="buttonDrinks" class="btn btn-danger" value="Didn't get drinks">
</form>
I use ajax to print a instant feedback message:
$('#drinksForm').submit(function(event){
event.preventDefault();
var form = $('#drinksForm');
$.ajax({
type : 'POST',
url : form.attr('action'),
data : form.serialize(),
})
.done(function(data){
$('#result').html(data);
})
.fail(function(data){
$('#result').html(data);
})
});
In drinksHander.php I want to see which button is pressed. If I delete
event.preventDefault();
I can see with
$_POST["buttonDrinks"]
which button is pressed. But because of the
event.preventDefault();
$.ajax({
type : 'POST',
url : form.attr('action'),
data : form.serialize(),
})
It doesn't send which button is pressed. So how can I send a variable to drinksHandler.php which shows which button is pressed.

Remove the buttons name attr and add dynamically an input before submit.
Also change the submit function to an on click button so the preventDefault should work.
Something like this
$('body').on('click', '.btnSubmit', function(event){
event.preventDefault();
var form = $('#drinksForm');
form.append('<input type="hidden" name="buttonDrinks" value="'+$(this).val()+'">');
var formData = form.serialize();
console.log(formData);
$.ajax({
type : 'POST',
url : form.attr('action'),
data : formData,
})
.done(function(data){
$('#result').html(data);
})
.fail(function(data){
$('#result').html(data);
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="drinksForm" action="drinksHandler.php" method="POST">
<label for="drinks">Number of drinks</label>
<input type="number" class="form-control" name="drinks" min="1" max="30" required="required">
<input type="submit" class="btn btn-success btnSubmit" value="Got drinks">
<input type="submit" class="btn btn-danger btnSubmit" value="Didn't get drinks">
</form>

Related

The jQuery ajax does not send more than two values to post url

I have the following code to send the data via Jquery AJAX and notice that I have three values that need to be sent to the receiving file(Addtocart.php).
The transmission and reception were good, but after a while I do not know why it no longer sends.. When one of the values is canceled and two remain, it sends.. but when three values are not sent.
ajax
<script >
$(document).ready(function() {
$("#add-to-card").click(function() {
var quantityq = $("#quantityq").val();
var user = $("#user").val();
var product__id = $("#product__id").val();
$.ajax({
url: 'Addtocart.php',
method: 'POST',
data: {
quantityq: quantityq,
user: user,
product__id: product__id
},
success: function(data) {
$('#result').html(data);
}
});
});
});
</script>
<input step="1" min="1" max="50" name="quantityq" id="quantityq" value="1" title="Qty" class="input-text qty text" size="4" type="number">
<input type="hidden" name="user" id="user" value="72663">
<input type="hidden" name="product__id" id="product__id" value="4">
</div>
<button type="submit" id="add-to-card" class="btn sqaure_bt fll display-f">send</button>
It is not clear what issue you are facing, as you didn't post an example that shows the issue clearly.
But Rather than binding to click event of the button, you should bind to submit event of the form. This way, client-side form validation will work correctly and your JS code will be a lot smaller.
<form id="myForm">
<input step="1" min="1" max="50" name="quantityq" id="quantityq" value="1" title="Qty" class="input-text qty text" size="4" type="number">
<input type="hidden" name="user" id="user" value="72663">
<input type="hidden" name="product__id" id="product__id" value="4">
<button type="submit" id="add-to-card" class="btn sqaure_bt fll display-f">send</button>
</form>
<script>
$(document).ready(function() {
$("#myForm").submit(function(e) {
e.preventDefault();
let postData = $(this).serialize();
$.ajax({
url: 'Addtocart.php',
method: 'POST',
data: postData,
success: function(data) {
$('#result').html(data);
}
});
});
});
</script>

Submit a form with a file without refresh

Hello guys i don't know to submit a form without page refresh.
This is my code:
My form:
<form method="POST" id="post123" action="" enctype="multipart/form-data">
<input class="form-control input-lg" name="book_name" id="inputLarge" type="text">
<input class="form-control" name="book_price" type="number">
<textarea class="form-control" id="exampleTextarea2"
name="book_description" maxlength="100" rows="7"></textarea>
<textarea class="form-control" name="book_content" id="exampleTextarea4" maxlength="200" rows="7"></textarea>
<input type="file" name="file" id="imgInp44" >
<button type="submit" name='action' id="sendbutton21" value="post1" class="btn btn-primary">
Submit
</button>
</form>
Javascript:
$("#sendbutton21").click(function() {
var url = "http://localhost:5000/magazin_insert"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#post123").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
How i can modify my code to submit along with text a file towards the mysql db?
Your first issue is in this line:
<button type="submit" name="action" ... />
You have two possibilities:
change type="submit" to type="button"
use event.preventDefault() in your $("#sendbutton21").click(function() {
After, your ajax call can be changed in order to include the file:
var form = document.getElementById('post123');
var formData = new FormData(form);
$.ajax({
url: url,
data: formData,
type: 'POST',
processData: false,
success: function(data) {
alert(data);
}
});
$("#sendbutton21").click(function() {
var url = "http://localhost:5000/magazin_insert"; // the script where you handle the form input.
// for testing...
url = 'https://api.github.com/repositories';
var form = document.getElementById('post123');
var formData = new FormData(form);
$.ajax({
url: url,
data: formData,
type: 'GET',
processData: false,
success: function (data) {
console.log(data[0].id);
}
});
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<form method="POST" id="post123" action="" enctype="multipart/form-data">
<input class="form-control input-lg" name="book_name" id="inputLarge" type="text">
<input class="form-control" name="book_price" type="number">
<textarea class="form-control" id="exampleTextarea2"
name="book_description" maxlength="100" rows="7"></textarea>
<textarea class="form-control" name="book_content" id="exampleTextarea4" maxlength="200" rows="7"></textarea>
<input type="file" name="file" id="imgInp44" >
<button type="button" name='action' id="sendbutton21" value="post1" class="btn btn-primary">
Submit
</button>
</form>
Try https://jquery-form.github.io/form/ plugin to easily send form via ajax sample code:
$('#post123').ajaxForm(function() {
// SUCCESS CALLBACK
});
To submit a form without refresh, use event.preventDefault().
$("#sendbutton21").click(function(event) {
event.preventDefault();
var url = "http://localhost:5000/magazin_insert"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#post123").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
Instead of
$("#sendbutton21").click(function() {
use
$("#post123").submit(function() {

Can submit the file and the other field in the form once?

I want to use jquery to submit the form ,the form with text field and file field ,but it just submit the text field "groupId" , I can't submit the groupId with file field .
the request header just
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
My problem is : can i submit the groupId field and file field once ?If can , what should I do?
the code below
<form id="submitForm" >
<div class="form-group">
<label for="exampleInputEmail1" >groupId</label>
<input type="text" name="groupId" class="form-control" >
</div>
<div class="form-group">
<label for="exampleInputFile" >File input</label>
<input type="file" name="file" class="form-control-file" id="exampleInputFile" aria-describedby="fileHelp">
<small id="fileHelp" class="form-text text-muted">This is some placeholder block-level help text for the above input. It's a bit lighter and easily wraps to a new line.</small>
</div>
<button id="newItemSubmitButton" type="submit" class="btn btn-primary">submit</button>
<button type="button" class="btn btn-default" >cancel</button>
</form>
js code
var submitForm = $('#submitForm');
$("#newItemSubmitButton").click(function (e) {
console.log("submit");
e.preventDefault();
console.log("after preventDefault");
$.ajax({
data:submitForm.serialize() ,
url: "./testSubmit",
type: "post",
success: function (data) {
// $("#form_output").html(data);
console.log("hello");
},
error: function (jXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
$('#newItem').modal('hide');
return false;
});

Why does the second form disappear after submiting?

There is the piece of code containing 2 forms:
<form class="emp-delete">
<label for="emp-id">Id:</label>
<input type="text" id="emp-id" />
<input type="submit" id="submit" value="delete" />
<span id="status" />
</form>
<script type="text/javascript">
$("#submit").click(function(){
$.ajax({
type: "DELETE",
url: "/corporate/employees/" + $("#emp-id").val(),
complete: function(r){
$("#status").text(r.responseText);
}
})
return false;
})
</script>
<p><spring:message code="createEmployee.title"/>
<form class="emp-create">
<label for="name" />
<input type="text" id="name" value="create"/>
<input type="submit" id="add-emp" />
</form>
<script type="text/javascript">
$("#add-emp").click(function(){
var employeeObject= { name: $("#name").val() }
$.ajax({
type: "POST",
data: JSON.stringify(employeeObject),
contentType: "application/json",
url: "/corporate/employees"
})
return false;
})
</script>
The issue is after clicking the delete button the second form dissapears.
Before:
After:
How can I do that the second form doesn't dissapear when clicking the delete button.
UPDATE
DEMO
The problem is right here:
<span id="status"/>
Change this to:
<span id="status"></span>
The browser thinks, that the span is openend and your second form is a child of it, which got replaced with your text.

Submitting two jQuery ajax form with two submit buttons

Here I just want to use two submit button in a single page, but its not sending any data through post?
<form name="form_post" id="form-post" method="post">
<label>
<span>Title *</span>
<input type="text" name="post_name" id="post-name" placeholder="Post title...." required>
</label>
<label>
<span>Body *</span>
<input type="text" name="post_body" id="post-body" placeholder="Post body...." required>
</label>
<input type="submit" id="submit_post" value="Submit Post">
</form>
Here is another form:
<form id="form_comment" method="post">
<!-- need to supply post id with hidden fild -->
<input type="hidden" name="postid" value="<?php echo $post_id ?>">
<label>
<span>Name *</span>
<input type="text" name="comment_name" id="comment-name" placeholder="Your name here...." required>
</label>
<label>
<span>Your comment *</span>
<textarea name="comment" id="comment" cols="30" rows="10" placeholder="Type your comment here...." required></textarea>
</label>
<input type="submit" id="submit_comment" value="Submit Comment">
</form>
this my script but not working? where I'm sending my request. I want to active such scrpts fro particuler submit, is there any way?
$(#form_post).submit(function(){
var form = $(form);
var submit = $('#submit_post');
form.on('submit', function(e) {
// prevent default action
e.preventDefault();
// send ajax request
$.ajax({
url: 'ajax_post.php',
type: 'POST',
cache: false,
data: form.serialize(), //form serizlize data
beforeSend: function(){
// change submit button value text and disabled it
submit.val('Submitting...').attr('disabled', 'disabled');
},
success: function(data){
// Append with fadeIn see http://stackoverflow.com/a/978731
var item = $(data).hide().fadeIn(500);
$('.wrap').append(item);
// reset form and button
form.trigger('reset');
submit.val('Submit Post').removeAttr('disabled');
},
error: function(e){
alert(e);
}
});
});
});
$(#form_comment).submit(function(){
var form = $(form);
var submit = $('#submit_comment');
form.on('submit', function(e) {
// prevent default action
e.preventDefault();
// send ajax request
$.ajax({
url: 'ajax_comment.php',
type: 'POST',
cache: false,
data: form.serialize(), //form serizlize data
beforeSend: function(){
// change submit button value text and disabled it
submit.val('Submitting...').attr('disabled', 'disabled');
},
success: function(data){
// Append with fadeIn see http://stackoverflow.com/a/978731
var item = $(data).hide().fadeIn(500);
$('.comment-block').append(item);
// reset form and button
form.trigger('reset');
submit.val('Submit Comment').removeAttr('disabled');
},
error: function(e){
alert(e);
}
});
});
});
you miss some "
it should be $("#form_comment") and $("#form_post") ...
This works for me:
$('#form_post').on('submit', function(event){
event.preventDefault();
$.ajax({
...
...
...
});
});
$('#form_comment').on('submit', function(event){
event.preventDefault();
$.ajax({
...
...
...
});
});
Use submit events like this,
$('body').on('submit', '#form_comment', function(){
e.preventDefault();
$.ajax({
...
...
...
});
});
$('body').on('submit', '#form_post', function(){
e.preventDefault();
$.ajax({
...
...
...
});
});

Categories