can't stop submitted form from refreshing page - javascript

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.

Related

How to pass parameters to jQuery function when using Laravel

I'm trying to pass the value of a star rating using rateYo and the log gives me a:
4main.js:11 undefined
the way its set up, it uses the div to get a value. I'm trying to set the value for the star, and ultimately pass the value to route params. The backend PHP works, it's just a matter of passing the parameters.
Show.blade.php
<h5>Click to rate:</h5>
<form action="{{ route('rate', $book->id) }}" method="POST">
{!! csrf_field() !!}
<!-- <input id="rateYo" name="val" value="0" type="text"> -->
<div id="rateYo" name="val"></div>
<button type="submit" class="btn btn-primary">submit</button>
</form>
Main.js
$(document).ready(function() {
'use strict'
$('#rateYo').rateYo({
starWidth: "40px"
});
$('#rateYo').click(function() {
var owl = $('#rateYo').val();
console.log(owl);
$.ajax({
type: 'POST',
url: 'rate/' + owl,
success: function(data) {
// $("#msg").html(data.msg);
}
});
});
});
Route
Route::post('rate/{book_id}','BookController#rate')->name('rate');
See plugin documentation from http://rateyo.fundoocode.ninja/.
You can not get rating value using val() function.
Try using
var rating = $rateYo.rateYo("rating");
console.log(rating)

Using AJAX to submit form

I have developed a Python API and am now integrating it with a HTML template I have downloaded. It is a simple one page HTML template with a form to accept a album name and artist name. I am looking to process the form using AJAX. So once the form has been successfully submitted, it is replaced with a message returned by the API.
The (simplified) html snippet is:
<div class="form">
<form role="form" action="form.php" id="signup">
<div class="form-group">
<label>Artist Name</label>
<input type="text" name="artist" id="artist">
</div>
<div class="form-group">
<label>Tracking Number</label>
<input type="text" name="album" class="album">
</div>
<button type="submit" class="btn">Submit!</button>
</form>
</div>
Then I have a JS file I import at the beginning of the html file. Below is the JS file.
$(function() {
var form = $('#signup');
var formMessages = $('#form-messages');
$(form).submit(function(e) {
e.preventDefault();
var formData = {
'artist' : $('input[name=artist]').val(),
'album' : $('input[name=album]').val(),
};
// process the form
$.ajax({
type : 'POST',
url : 'form.php',
data : formData,
dataType : 'json'
})
.done(function(data) {
var content = $(data).find('#content');
$("#result").empty().append(content);
});
});
I think the issue is with the .done(function(data)) however, the website I found the code on wasn't clear.
form.php returns a JSON string. At the moment when I use the form, it sends the information to the Python API and the Python API returns a JSON message. But I cannot access the JSON message. It is in contains
'code': X, 'message':'returned messaged...'
ideally I would like to do a if/else statement. So
if code = 1:
display: Success
etc but I have no idea where to start with it in PHP/JS.
I was able to get it working eventually after seeing a few other stack overflow answers and another website.
I added one div to the html file under the button before the end of the form to make:
<form>
...
...
<button type="submit" class="btn">Submit!</button>
<div id="thanks" style="display:none;"></div>
</form>
Then, in the JS file I amended .done(function(data)) to be:
.done(function(data) {
if (data.result == '1') {
$('#thanks').show().text("Success!");
$('input[type="text"],text').val('');
} else if (data.result == '2') {
$('#thanks').show().text("Album and Artist already exists");
} else {
$('#thanks').show().text("Uh Oh. Something has gone wrong. Please try again later or contact me for more help");
}
});

how to submit the form without refreshing the page

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() {
...
});
});

Post value of submit button

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/

Response from AJAX request is only displayed once

I've got some code that sends an ajax request when a form is being submitted. This works the first time the form is submitted (it's a search module), but only once. I've added an effect to highlight the table when data is returned, and you can only see it once (the data changes only once as well).
When I look at the response in the chrome dev tools, I can see it contains the data of the new search query but this isn't shown. Why can I only display results once?
JS:
$(function () {
// Creates an ajax request upon search form submit
var ajaxFormSubmit = function () {
var $form = $(this);
var options = {
url: $form.attr("action"),
type: $form.attr("method"),
data: $form.serialize()
};
$.ajax(options).done(function (data) {
var $target = $($form.attr("data-nn-target"));
var $newHtml = $(data);
$target.replaceWith($newHtml);
$newHtml.effect("highlight");
});
// Prevent default action
return false;
};
$("form[data-nn-ajax='true']").submit(ajaxFormSubmit);
});
HTML:
<form method="GET" action="#Url.Action("Index", "Show")" data-nn-ajax="true" data-nn-target="#contentlist" class="form-search">
<div class="input-append mysearch">
<input type="search" class="span5 search-query" name="query" data-nn-autocomplete="#Url.Action("AutoComplete")" />
<input type="submit" class="btn" value="Search" />
</div>
</form>
<div id="contentlist">
#Html.Partial("_Shows", Model)
</div>
I think you should use html() instead of replaceWith() method:
$target.html($newHtml);
just an idea... try
$target.html(data);
instead of
$target.replaceWith($newHtml);
By replaceWith, you might actually remove the div that you want to fill your content in. Then, the second time, it doesnt find the div to insert the content into.

Categories