I am looking to use AJAX to submit multiple forms on submit. I need to get the value of a hidden field to use in the AJAX call. I have the first submit working just fine and returns the response expected.
example:
<form name="add_to_cart-12345" action="add_product" method="post">
<input type="hidden" name="products_id" value="12345" />
<input class="quantity" id="product_quantity" min="1" name="cart_quantity" value="1" step="1" type="number">
<input type="submit" class="add-to-cart" value="Add to Cart" id="addProduct-12345" />
This code can repeat 1 to n times with the values 12345 changing and being unique.
My Javascript is:
<script>
$(function() { // begin document ready
$('#addProduct').on('click', function(e) {
e.preventDefault();
var cart_quantity = document.getElementById('product_quantity').value;
var products_id = parseInt(document.getElementsByName('products_id').value);
var form = $(this).closest('form');
// AJAX request
$.ajax({
url: 'ajax_add_product.php',
type: 'POST',
dataType : "html",
data: {cart_quantity, products_id},
success: function(response){
console.log(response)
var TotalInCart = parseInt(document.getElementById('cartTotal').innerText);
var cartQuantity = parseInt(document.getElementById('product_quantity').value);
var headerTotal = cartQuantity + TotalInCart;
$("#cartTotal").html(headerTotal);
$("#cartProducts").html(response);
$("#ShoppingCartModal").modal({show:true});
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
});
$( document ).ajaxError(function() {
$( ".log" ).text( "Triggered ajaxError handler." );
});
});
</script>
What I need to do is to be able to submit any form when clicked. And push the product id, product quantity to the AJAX call.
Related
I am using Ajax and jQuery to submit a dynamic form.
It works fine, but the response from Servlet is shown in a new page.
function call(formid) {
alert(formid);
var form = $(formid); // id of form tag
form.submit(function () {
$.ajax({
type: form.attr('method'), //post method
url: form.attr('action'), //ajaxformexample url
data: form.serialize(), // serialize input data values
success: function (data) {
var result=data;
$('#content').html(result); //showing result
}
});
return false; // not refreshing page
});
}
How I can show response from Servlet in same page?
(out.println("<br/>Massage = "+message+"<br/>"););
You are experiencing this because you are not stopping what a form submit does:
So, according to .submit( handler ) change your line:
form.submit(function () {
to:
form.submit(function (e) {
e.preventDefault(); // stop form submit and do your ajax call
UPDATE
According to your comment I suggest you to try the following code:
function submitFrm(obj, e) {
e.preventDefault();
var form = $(obj).closest('form'); // id of form tag related to the current button
var formid = form.attr('id');
alert(formid);
$.ajax({
type: form.attr('method'), //post method
url: form.attr('action'), //ajaxformexample url
data: form.serialize(), // serialize input data values
success: function (data) {
var result=data;
$('#content').html(result); //showing result
}
});
}
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<form id="formid">
First name:<br>
<input type="text" name="firstname"><br>
Last name:<br>
<input type="text" name="lastname">
<input type="submit" value="Submit" onclick="submitFrm(this, event);">
</form>
I am working with PHP and jQuery. I have 2 files
test.php
<script>
$(document).ready(function(){
$(".form-register").submit(function (e) {
var form_data = $(this).serialize();
e.preventDefault();
$.ajax({
type: "POST",
url: "test2.php",
data: form_data,
dataType: 'json',
success: function(){
alert(form_data);
}
});
});
});
</script>
<form class="form-register">
<input name="email" type="text"/>
<input name="name" type="text"/>
<input type="submit" name="register"/>
</form>
and the second file is test2.php:
<?php
if(isset($_POST['register'])){
echo json_encode('Message from test2.php');
}else{
echo json_encode('post no received');
}
It seems like I am unable to retrieve $_POST['register'] because when I check alert(form_data); only the email and the name are displayed.
Is there anyway for me to get $_POST['register']?
Add value attribute to submit button and use $('form').serializeArray() . Try:
$(".form-register").submit(function (e) {
var formData = $(this).serializeArray();
var name = $(this).find("input[type=submit]").attr("name");
var value = $(this).find("input[type=submit]").val();
formData.push({ name: name, value: value });
//now use formData, it includes the submit button
$.ajax({
type: "POST",
url: "test2.php",
data: formData,
dataType: 'json',
success: function(){
alert(form_data);
}
});
});
Neither .serialize() nor .serializeArray() will serialize the submit button value.
.serialize()
...No submit button value is serialized since the form was not submitted using a button.
.serializeArray()
...No submit button value is serialized since the form was not submitted using a button.
Only successful controls are serialized.
The input submit element is actually a successful control, but as mentioned above since the form is not submitted using the submit button, the input submit value attribute will not be included by jquery serialization.
If you want to use .serializeArray() just add the input submit elements name and value attribute values as an object to the serialized array like so.
$(document).ready(function(){
$(".form-register").submit(function (e) {
var form_data = $(this).serializeArray();
var $submit = $(this).find('input[type="submit"]');
form_data.push({name: $submit.prop("name"), value: $submit.val()});
console.log(form_data);
// do your ajax request here...
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form-register">
<input name="email" type="text"/>
<input name="name" type="text"/>
<input type="submit" name="submit" value="register"/>
</form>
If you want to use .serialize() just add the values of the value and name attributes of the submit element to the text string created by the .serialize() method. Be careful, the string needs to be URL-encoded.
$(document).ready(function(){
$(".form-register").submit(function (e) {
var form_data = $(this).serialize();
var $submit = $(this).find('input[type="submit"]');
form_data = form_data + "&" + $submit.prop("name") + "=" + $submit.val();
console.log(form_data);
// do your ajax request here...
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form-register">
<input name="email" type="text"/>
<input name="name" type="text"/>
<input type="submit" name="submit" value="register"/>
</form>
I'm working on a website with heavy Ajax, and I'm using codeigniter for building it.
I've got a form with post method, and this form is being posted using ajax request which call a function with if/else statement, like this:
if(isset($_POST['save']))
{
$data['phase'] = 'translating';
}
elseif(isset($_POST['submit']))
{
$data['phase'] = 'waiting_approve';
}
The if/else statement check which button is being clicked, and it works 100% after posting the data of the form in the usual way, but never works when posting it using ajax request.
My ajax request:
$('#workspace-content').delegate('form#article', 'submit', function(){
var that = $('form#article'),
url = that.attr('action'),
type = that.attr('method'),
data = {};
data = that.serialize();
$.ajax({
type: type,
url : url,
data : data,
dataType: 'json',
success: function(data){
$('#header-search-field').append(data.msg).delay(3000).fadeOut(500, function(){
var that = $(this);
that.html('').fadeIn();
});
}
});
return false;
});
Any suggestion or solution?!!
The HTML form:
<button id="save-article" type="submit" name="save" class="btn btn-info btn-xs pull-left">
<span class="glyphicon glyphicon-floppy-save"></span>
</button>
<input name="title" type="text" value="<?php echo $work->title;?>" class="form-control" id="title" placeholder="" />
<textarea row="10" name="article" class="form-control" id="article" placeholder=""><?php echo $work->article;?></textarea>
<button id="submit-article" type="submit" name="submit" class="btn btn-info btn-block">Send</button>
<input name="slug" type="hidden" value="<?php echo $work->slug;?>" />
When you submit a form normally, the button that you used to submit it will be included in the POST data. But when you submit with AJAX, and use that.serialize(), the POST data just includes the input fields -- the submit button isn't included. You need to attach your submit code to the buttons, so you can add the appropriate values to the data.
$('#workspace-content').on('click', 'form#article .btn', function(){
var that = $(this).closest("form"),
url = that.attr('action'),
type = that.attr('method'),
data = that.serialize();
data += '&' + this.name + '=1';
$.ajax({
type: type,
url : url,
data : data,
dataType: 'json',
success: function(data){
$('#header-search-field').append(data.msg).delay(3000).fadeOut(500, function(){
var that = $(this);
that.html('').fadeIn();
});
}
});
return false;
});
I have this ajax call in my php code that still navigates to action page. I want the ajax call to stay on the same page and only update part of the page. What I'm doing wrong here:
<form method="post" id="holderSave" action="student_add_scene.php">
<h3> Save to Holder</h3><br/>
<div id="cutfrom">
<input placeholder="Cut from" name="from" id="from">
<button href="#" onclick="captureElapsed('elapseFrom', 'from');
return false;">capture</button>
</div>
<div id="cutto">
<input placeholder="Cut to" name="to" id="to" >
<button href="#" onclick="captureElapsed('elapseTo', 'to');
return false">capture</button>
</div>
<div id="savecapt">
<input placeholder="add label" id="label" name="label"/>
<input type='submit' value='Save' class='button'>
</div>
</form>
<script>
$('#holderSave').on("submit", (function (e) { // catch the form's submit event
e.preventDefault();
$.ajax({// create an AJAX call...
var $form = $(this), url = $form.attr('action');
var posting = $.post( url, { from: $('#from').val(), label:$('#label').val(), to: $('#to').val()});
posting.done(function(response)){
$('#holderSave').html(response); // update the DIV
alert(response);
}
});
return false;
}));
</script>
This is a syntax error:
$.ajax({// create an AJAX call...
var $form = $(this), url = $form.attr('action');
You seem to be trying to treat the object literal you pass to ajax as a function body. It isn't, so you can't just write statements in it.
Since you make the ajax request with $.post later, $.ajax is entirely pointless. Remove that line and it should work.
Fixed code. Aside from the pointless half-a-call to .ajax, you had a bunch of syntax errors which I've fixed while reformatting it.
Use your browser's developer tools console. Use http://jshint.com/
// Remove pointless ( from before the second argument of the call to on().
$('#holderSave').on("submit", function(e) {
e.preventDefault();
// Remove half a call to .ajax
var $form = $(this),
url = $form.attr('action');
var posting = $.post(url, {
from: $('#from').val(),
label: $('#label').val(),
to: $('#to').val()
});
posting.done(function(response) {
$('#holderSave').html(response);
alert(response);
// Remove line with extra } here
});
return false;
// Remove extra ) here
});
Change submit into button with id
<input type='button' id="save" value='Save' class='button'>
Trigger click event for button, serialize the form data and post the data via ajax
$(document).ready(function() {
$('#save').click(function(){ // catch the form's submit event
var form = $('#holderSave');
$.ajax( {
type: "POST",
url: form.attr( 'action' ),
data: form .serialize(),
success: function( response ) {
console.log( response );
}
} );
});
});
HTML:
<form id="message">
<input id="message-text" name="message" type="text" value="" autofocus="autofocus" />
<input type="submit" value="Send" />
</form>
JAVASCRIPT:
$(document).ready(function () {
// submit new message
var request;
$("#message").submit(function(event) {
// abort any pending request
if (request) {
request.abort();
}
var $form = $(this);
var $inputs = $form.find("input, select, button, textarea");
var postData = $form.serialize();
// note: we disable elements AFTER the form data has been serialized
$inputs.prop("disabled", true);
request = $.ajax({
url: "submit.php",
type: "POST",
data: postData
})
.done(function(response, textStatus, jqXHR) {
console.log('Success: ' + textStatus, jqXHR);
})
.fail(function(jqHXR, textStatus, errorThrown) {
console.error('Error: ' + textStatus, errorThrown);
});
});
});
I've confirmed that submit.php works when not using AJAX to submit, so I don't think that's the problem. The console log simply says: Error: error on line 66: console.error('Error: ' + textStatus, errorThrown); which is completely non-descriptive nor helpful... The page also refreshes when I hit enter or click submit, which isn't supposed to happen.
Any ideas what I'm doing wrong?
This happens because you use submit input, this is the default behavior of submit input, so you have 2 options first is disable the submit using event.preventDeafult(); on the submit process, or you can easily change your send button:
<input type="submit" value="Send" />
to
<input type="button" value="Send" />
$("#message").submit(function(event) {
event.preventDefault();
...
I prepare demo for you please download it from
https://www.dropbox.com/s/24h0o9n08iuvpo1/ajaxdemo.rar
Change as per your requirement. I think it is helpful