I am trying to add product in to the cart using jQuery and AJAX. The situation is that I am getting more then 30 forms that are generated dynamically using foreach loop. after page loading i get product list but need to add only one product in to the cart , and dont want reload the page , so i am using AJAX. please help me how can i achieve this.
Most important thing is when i tried without <form> tag , the value of productId always goes 1 because its the first value of id attribute, and saves product in to the cart whose id is one. So I am using <form>.
this is code (its a sample code) :
<form id="addToCartForm" action="" method="post">
<input type="hidden" id="productId" value="${products.productid}">
<button id="btnSubmit">Add to Cart</button>
</form>
<form id="addToCartForm" action="" method="post">
<input type="hidden" id="productId" value="${products.productid}">
<button id="btnSubmit">Add to Cart</button>
</form>
<form id="addToCartForm" action="" method="post">
<input type="hidden" id="productId" value="${products.productid}">
<button id="btnSubmit">Add to Cart</button>
</form>
I already tried lots of things, like jquery.form.min.js, but nothing is going on as according just i like want.
please help. thnx in advance.
Edited
script.js:
$(document).ready(function(){
$(".addToCart").click(function(){
$.post('addToCart.htm', {productId: $('input[type=hidden]#productIdId').val()},
function(message){
$("#message").html(message);
}
);
});
});
You are looking for something like:
$(document).on('click', '#btnSubmit', function(){
var value = $(this).prev().val();
$.ajax({
url: 'path/to/server/script',
type: 'post',
data: { productid: value },
success: function(){
alert('succeeded');
}
});
});
Anyway, you have to use classes instead ids if you have same kind elements. An id is an identifier, so it must to be unique.
You could do something like this:
$("#addToCartForm").on("submit", function(e) {
var $form = $(this);
e.preventDefault();
e.stopPropagation();
$.ajax({
method: "POST",
action: $form.attr("action"),
data: $form.serialize()
}).done(function() {
...
});
});
UPDATE: Oh! and yeah, the IDs of your forms should be unique.
UPDATE 2: Without forms
<a class="addToCart" href="#" data-productid="${products.productid}">Add to Cart</a>
JavaScript:
$(".addToCart").on("click", function(e) {
e.preventDefault();
e.stopPropagation();
$.ajaxPost({
action: "addToCart.html",
data: {productId: $(this).data("productid")}
}).done(function() {
...
});
});
Related
The form is displayed dynamically and gives the id so I can found out which form it is coming from...
here is the php/html form
<div class="col-sm-4 text-center">
<!-- Task Name -->
<div><img src="{{ URL::asset('public/mealpics') }}/{{ $meal->picture }}" /></div>
<div>{{ $meal->name }} by {{ $meal->author }}</div>
<div>Rating: {{ $meal->rating }}</div>
<div>Cal: {{ $meal->calories }} Fat: {{ $meal->fat }} Chol: {{ $meal->cholesterol }}</div>
<div>Sodium: {{ $meal->sodium }} Sugar: {{ $meal->sugar }}</div>
<div>{{ $meal->created_at }}</div>
<div>
<form action="/mealtrist" method="post" enctype="multipart/form-data">
<input type="hidden" name="_token" value="{!! csrf_token() !!}">
<input type="hidden" class="form-control" id="onPlan{{$meal->id}}" name="onPlan"
value="{{ $meal->id }}">
<button id="submit_btn" data-mealid="{{$meal->id}}" type="submit" class="btn btn-default">Add To Plan</button>
</form>
</div>
</div>
and the jquery ajax
$(document).ready(function () {
$('submit_btn').click(function(event) {
event.preventDefault();
var diffValue = $(event.currentTarget).attr("data-mealId");
var mealId = '#onPlan' + diffValue;
jQuery.ajax({
url : '<?php echo URL::to('mealtrist') ?>',
type : 'POST',
data : {
onPlan: diffValue},
});
});
});
i've also tried this...
$(document).ready(function () {
$('#submit_btn').click(function(event) {
event.preventDefault();
var diffValue = $(event.currentTarget).attr("data-mealId");
var mealId = '#onPlan' + diffValue;
$('#form').submit(function (e) {
jQuery.ajax({
url : '<?php echo URL::to('mealtrist') ?>',
type : 'POST',
data : $(mealId).serialize(), success : function( response ) {
$('#added').empty();
$(response).appendTo("#added");
}
});
e.preventDefault();
});
});
});
i've also tried the
('#form').on('submit', function (e) {
///i've even tried the e.preventDefault(); here but I think that prevents the code below from sending.
////code
e.preventDefault();
});
none of this seems to be working. I'm using larvel 5.1 and trying to get a form to submit on a page and send the value of one input to a controller so that I can get that id and use it to store information from another table in my database. It works of course, but it also refreshes the page...that's what I'm looking for. The page turns up blank, which i understand that is happening because I'm not returning anything in my controller...that doesn't matter, because when I return the same page in my controller it still shows the page refreshing...which is what I want to get rid of. I just want the data sent through ajax so I can use it...no page refresh. I don't understand why I'm having this issue. I've read alot of other questions on here about preventing the refreshing, but none of the solutions are working. Any idea?
Since you're handling the POST yourself via ajax (your first jquery example), try changing the button from type "submit" to just type "button"
This should help
$('form').submit(function (e) {
return false;
});
form has no id #form. Try form instead.
$('form').on('submit', function (e) {
e.preventDefault();
});
At first set an id into form --
<form id="MyForm" action="/mealtrist" method="post" enctype="multipart/form-data">
Then use this--
$(document).ready(function() {
$("#MyForm").on('submit', function(e) {
e.preventDefault();
})
});
I tried all the form submit answers above. return false did not work and event.preventDefault() did not work. I also wasn't as clear in my question. I really thought it was more secure to submit my form rather than use ajax, so that is why i was trying to use the form. I ended up just using ajax to send the data.
$(document).ready(function () {
$('.submit_btn').click(function(event) {
event.preventDefault();
var diffValue = $(event.currentTarget).attr("data-mealId");
jQuery.ajax({
url : '<?php echo URL::to('meals') ?>',
type : 'POST',
data : {
onPlan: diffValue},
/* success : function( response ) {
$('#added').empty();
$(response).appendTo("#added");
} */
});
});
});
It works perfectly fine.
I've got the following form:
<div>
<form name="ajaxformname" id="ajaxform" action="/request" method="POST">
AJAX:
<input id="btn1" name="feeling" type="submit" value="Fine">
<input id="btn2" name="feeling" type="submit" value="Neutral">
<input id="btn3" name="feeling" type="submit" value="Bad">
</form>
</div>
which should be posted to a server via ajax.
Here is the associated javascript:
$('#ajaxform').submit(function (event) {
event.preventDefault();
var form = $(this);
var action = form.attr("action"),
method = form.attr("method"),
data = form.attr("value");
$.ajax({
url: "/request",
type: method,
data: data
});
Now - depending on which of the three buttons has been clicked - I want their values to be posted to the server. But form.attr("value") just gives me the value of the form but not of the input field.
Any suggestions? A solution would be to create the different forms but that doesn't seems to be DRY ...
First thing, if you wanna use the action attribute of the form, you should reference it in the url param of ajax request:
url: form.attr('action'),
Now, for the button clicked, you should use this (it's a workaround because submit buttons are not incluided in the form serialization, if not, I would use it instead):
$(function () {
//When any of the buttons is clicked, we store in the form data the clicked button value
$('#ajaxform').on('click', 'input[type=submit][name=feeling]', function(e) {
$(this.form).data('clicked', this.value);
});
$('#ajaxform').submit(function (event) {
event.preventDefault();
var form = $(this);
$.ajax({
url: form.attr('action'),
type: form.attr("method"),
data: { clickedButton : form.data('clicked') } //Retrieve the button clicked value from the form data
});
});
});
Here the working example: https://jsfiddle.net/68qLxLgm/1/
Hi kindly use the following to get the id of the button that has been clicked
$("input").click(function(e){
var idClicked = e.target.id;
});
I have a <form>:
<form method="post" action="">
<button type="submit" name="age" value="20">Age 20</button>
<button type="submit" name="age" value="30">Age 30</button>
</form>
When I am handling submission of this <form> with ajax like this:
$('form').submit(function (event) {
event.preventDefault();
$.ajax({
type : "POST",
cache : false,
url : $(this).attr('action'),
data : $(this).serialize(),
});
});
it completely ignores POST['age']. Is this intended behaviour or am I doing something wrong?
I've also tried <input type="submit" name="age" value="30" /> without luck.
As per the jQuery documentation for .serialize()...
Only "successful controls" are serialized to the string. No submit button value is serialized since the form was not submitted using a button.
In other words, the button value will not be part of the POST array when the form is submitted with .ajax(). A regular "non-ajax" submit, however, WILL include the clicked button in the POST array.
A workaround would be to simply append the value of the button onto the serialized array...
$('button').on('click', function (event) {
event.preventDefault();
$.ajax({
type : "POST",
cache : false,
url : $(this).parent('form').attr('action'),
data : $(this).parent('form').serialize() + '&' + $(this).attr('name') + '=' + $(this).val(),
});
});
Note that I'm using the click event of the button, rather than the submit event of the form, so that I can easily capture which button was used.
DEMO: http://jsfiddle.net/ty7c5k9b/
So I have this:
$('#id').submit(function(e){
e.preventDefault();
etc etc
I want to be able to have this:
$('#id' + variable).submit(function(e){
e.preventDefault();
etc etc
I'm not sure what I should do to go about that. The reason for it is that there are many similar forms on the page that get generated dynamically.
I tried doing this and I'm guessing that is just a terrible thing to do but it was all I could think to try as I am not very good with JQuery:
function foo(variable){
$('#id' + variable).submit(function(e){
e.preventDefault();
etc etc
}
But that causes the form to be submitted multiple times.
-edit- to respond to a request:
$.ajax({
type: "POST",
url: "process.php",
data: dataString,
success: function(data) {
var responseData = jQuery.parseJSON(data),
etc etc do some stuff like show a message (all that works)
If you are producing multiple forms with different ID's dynamically, it would probably advantageous if they all used the same class="preventSubmit" and your code looked like:
$('.preventSubmit').submit(function(e){
var currentThis = this;
alert(this.id);
e.preventDefault(); // breaks this
alert(currentThis.id);
etc etc
If you want to avoid the submission itself, there are two approaches:
1) Use a input type="button" and attach a event handler for click:
<input type="button" id="submit_btn" value="Submit" />
// (In Javascript):
$("#submit_btn").click(function() {
});
2) To stop the submission, use return false :
$("#id" + variable).submit(function() {
return false;
});
Try this.
$('form').on('submit', function(e){
var variable = $(this).attr('id');
e.preventDefault();
});
If you have this html
<div id="wrap">
<form id="id35">
<input type="submit" value="submit" />
</form>
</div>
and this js
var threeFive = 35;
$("#id"+threeFive).submit(function(e){
e.preventDefault;
alert("hi");
});
it works!! ... BUT, ...if you have this html
<div id="wrap">
</div>
and later you append dynamically the form element to the container, let's say like
sample js function
function addMe(){
$('#wrap').append('<form id="id35"><input type="submit" value="submit" /></form>')
}
sample add button
<a class="addMe" href="javascript:addMe();">add form</a>
then, the example alert doesn't work anymore when you submit the form.
You would need to modify your script to support that dynamically added form using the .on() method (and jQuery v1.7.x) targeting the parent container like
var threeFive = 35;
$("#wrap").on("submit","#id"+threeFive, function(e){
e.preventDefault;
alert("hi");
});
then it will work
if you have to deal with a lot of forms in single page, you might want to exploit bubbling.
<div class="container-for-all-forms">
<form id="..." class="..."> ..... <input type="submit" /> </form>
<form id="..." class="..."> ..... <input type="submit" /> </form>
<form id="..." class="..."> ..... <input type="submit" /> </form>
.
.
</div>
js bit might be
$('#container-for-all-forms').bind('click.formProcessor', function(event){
var $clicked = $(event.target);
if($clicked.is(':submit')){
event.preventDefault();
console.log($clicked.parents('form').attr('id'));
/* at this point you can get all id names from php (or template language), bind js variables and match. like:
var idNames = ['<?...?>','<?...?>']
*/
}
});
this will bind only one event to container element, and you can run all sorts of checking when a click occurs in that container.
I'm breaking my head trying to call a js function from a button element inside a form, here is my code:
<%
PortletPreferences prefs = renderRequest.getPreferences();
String employee = (String)prefs.getValue("name", "New Employee");
%>
<portlet:actionURL var="callURL" windowState="<%=LiferayWindowState.EXCLUSIVE.toString() %>" />
<script type="text/javascript">
Liferay.provide(window, 'insertEmployee',
function ()
{
var A = AUI();
var url = 'http://localhost:8080/c/portal/json_Service';
A.io.request(url,
{
method:'POST',
data:
{
serviceClassName: 'com.liferay.test.service.TrabajadorServiceUtil',
serviceMethodName: 'create',
servletContextName: 'TrabajadorPlugin-portlet',
serviceParameters: '[param]',
},
headers: {'Content-Type':'charset=utf-8'},
on:
{
success: function()
{
alert("success " + responseData.name);
}
},
form: {id: 'postForm'},
xdr: {dataType: 'json'}
});
},
['aui-io']
);
</script>
<div>
<aui:form name="postForm" id="postForm" method="post" onSubmit="insertEmployee();">
<input type="text" name="param" value="<%=employee %>"/>
<input type="submit" value="Submit"/>
</aui:form>
</div>
I'm not using an java class, thus I'm not using the portlet:actionURL either.
My intention is to call "insertEmployee()" when clicking the 'Submit' button, but it's only sending the param inserted by the user inside the text field. I've tried to put the 'onsubmit' also in the submit input, but the same result is given.
If you could help me or guide me to solve issue it would be so great! I'm not finding good information/tuts on the internet and I'm not sure where is the problem or what else I need to know.
Thanks a lot in advance!
I just need:
<aui:script>
window.functionName = function ()
{
//code
};
</aui:script>
and call it from:
<aui:form name="myform" action="javascript:functionName();">
<aui:input type="submit" name="Submit" value="Update"/>
</aui:form>
and the function is being called from the form tag.