Issue with AJAX form submit - javascript

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

Related

Prevent redirecting after post

It's probably a bad idea to ask a question, which already have multiple answers and multiple times, but I should ask it anyway. I tried pretty much everything I find there Prevent redirect after form is submitted but nothing helps me.
There is a some minor detail, which I don't see. I'm not very familiar with jQuery and AJAX. Especially with the former.
So, the code:
<form id="form" action="uploadfile.php" method="post" enctype="multipart/form-data" ><!--action="uploadfile.php" onsubmit="return false;" -->
<label>Name</label>
<input id="username" name="username" type="text" onblur="checkUsername(this.value)" onkeypress="clearError('nameerror')" oninput="clearError('nameerror')" /><br>
<label id="nameerror"></label><br>
<label>Email</label>
<input id="email" name="email" type="text" onblur="validateEmail(this.value)" onkeypress="clearError('emailerror')"/><br>
<label id="emailerror"></label><br>
Select a file<br />
<label id="draganddroperror"></label><br>
<input name="fileToUpload[]" id="fileToUpload" type="file" onchange="onChange(event)" multiple /><br />
<button id="btnSubmit" onclick="sendData()" style="background-color: gray; color: #ffffff;" />Отправить</button>
</form>
There is my JS
function sendData() {
var file_data = $("#fileToUpload").prop("files");
console.log(file_data);
if ($("#file_data").val() != "") {
var form_data = new FormData();
//form_data.append('file', file_data);
//console.log(file);
form_data.append('file', file_data);
console.log(form_data);
$.ajax({
url: 'uploadfile.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(data) {
// get server responce here
//alert(data);
// clear file field
//$("#your-files").val("");
return false;
}
});
return false; //event.preventDefault();
} else {
alert("Please select file!");
}
}
So, this is the code in question. All works flawlessly, except redirect. Another questions contains submit, but I didn't have submit input. I tried to delink form from post method (1st line), but I got server error. Return false everywhere.
I spent countless hours on this question, it consumed almost all my night hours for a few days. I would appreciate any help, thanks.
The trick to prevent form submission is return false onsubmit as below:
<form id="form" onsubmit="return sendData()" method="post" enctype="multipart/form-data">
<!--action="uploadfile.php" onsubmit="return false;" -->
<label>Name</label>
<input id="username" name="username" type="text" onblur="checkUsername(this.value)" onkeypress="clearError('nameerror')" oninput="clearError('nameerror')" />
<br>
<label id="nameerror"></label>
<br>
<label>Email</label>
<input id="email" name="email" type="text" onblur="validateEmail(this.value)" onkeypress="clearError('emailerror')" />
<br>
<label id="emailerror"></label>
<br> Select a file
<br />
<label id="draganddroperror"></label>
<br>
<input name="fileToUpload[]" id="fileToUpload" type="file" onchange="onChange(event)" multiple />
<br />
<button type="submit" id="btnSubmit" style="background-color: gray; color: #ffffff;">Upload</button>
</form>
Note that I have written onsubmit=return sendData(). When the sendData() will return true the form will get submitted, otherwise it will never get submitted. For that the last statement in sendData() is return false;. In this way the form never gets submitted in current window, instead only Ajax submit works.
function sendData() {
var file_data = $("#fileToUpload").prop("files");
console.log(file_data);
if ($("#file_data").val()) {
var form_data = new FormData();
//form_data.append('file', file_data);
//console.log(file);
form_data.append('file', file_data);
console.log(form_data);
$.ajax({
url: 'uploadfile.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(data) {
// get server responce here
//alert(data);
// clear file field
//$("#your-files").val("");
}
});
} else {
alert("Please select file!");
}
return false;
}
I hope this gives you the clear understanding.
You want to cancel the default event handler for the submit event that the button triggers. To do this you need access to the event itself. It's best practice to handle the button click from JavaScript entirely instead of calling functions from HTML.
var submitButton = document.getElementById('btnSubmit');
submitButton.addEventListener('click', sendData);
// Then you will have access to the event in the sendData function
function sendData(ev) {
ev.preventDefault();
...
}
Live example
A slightly cleaner approach is to handle the form submitting, however this is done. This would also catch a form submit by hitting the enter key for example.
var form = document.getElementById('form');
form.addEventListener('submit', sendData);
Live example
In function sendData() you should pass event param like this
function sendData(evt) {
}
and then in this function we should add evt.preventDefault(); to stop submit action. Hope this help.
Add type attribute with the value of button and you are done:
<button id="btnSubmit" type="button" ...
By default The value for the type attribute is submit, which tells the browser to submit the from to the server, If you change it to button the browser will do nothing, you can only bind events when the button is clicked

JavaScript jQuery issue with submit button

I have a problem. I think it's because of the rendering but I don't know because that topic is new to me.
Okay, I have a simple form:
<form method="post" action="/send-mail">
<input type="text" name="msg" value="">
<input type="submit" value="send that fancy mail">
</form>
Now i want to catch that submit using jQuery like:
$('[type=submit]').submit(function(e) {
e.preventDefault();
var formHtml = $(this).parent().html();
$.ajax({
..all these options..,
beforeSend: function(xhr) {
$('form').html("sending mail");
},
success: function(data) {
$('form').html(formHtml); // I think here's the problem...
}
});
});
okay, that code works really good. It does what it should do. But, If I want to send a second request, the submit button doesn't work anylonger as intended. It tries to send the form using the default-action although I prevnted that - at least that's what I thought.
I did use google but I don't even know how to explain my problem.
Hopefully someone can help me, thanks a lot!
Greetz
Instead of .html() you can use:
.clone(true): Create a deep copy of the set of matched elements.
.replaceWith(): Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed.
The event must be click if attached to submit button or submit if attached to the form.
The snippet:
$('[type=submit]').on('click', function (e) {
e.preventDefault();
var formHtml = $(this).closest('form').clone(true);
$.ajax({
dataType: "json",
url: 'https://api.github.com/repos/octocat/Hello-World',
beforeSend: function (xhr) {
$('form').html("sending mail");
},
success: function (data) {
console.log('Success');
$('form').replaceWith(formHtml); // I think here's the problem...
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" action="/send-mail">
<input type="text" name="msg" value="">
<input type="submit" value="send that fancy mail">
</form>
Use $(document).on("click", "[type=submit]", function (e) { for dynamically created ekements instead of $('[type=submit]').submit(function(e) {
Use <input type="button"> instead of <input type="submit"> and add an onclick function like this:
<input type="button" onclick="_submitForm()" value="send that fancy mail">
And then your js will be:
function _submitForm(){
var formHtml = $(this).parent().html();
$.ajax({
..all these options..,
beforeSend: function(xhr) {
$('form').html("sending mail");
},
success: function(data) {
$('form').html(formHtml); // I think here's the problem...
}
});
}
I hope that solved your problem.

Submit URL via AJAX / PHP set variable without refreshing page, load variable

I'm having an issue with some script to perform a function via AJAX without refreshing my page. I have a field for a user to enter an external URL, and when they click submit it pops up a modal window, with some information generated through a separate PHP page (images.php currently). I have the script working when the form is actually submitted, the page reloads, and images.php is able to see index.php?url=whatever, but I'm trying to update the page without having to refresh. Do I need to re-render the DIV after defining the variable? I think this may be where I'm having problems.
JS
<script type="text/javascript">
$(function() {
$("#newNote").submit(function() {
var url = "images.php"; // the script where you handle the form input.
var noteUrl = $('#noteUrl).val();
$.ajax({
type: "POST",
url: url,
data: {noteUrl: noteUrl},
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
});
</script>
HTML
<form id="newNote">
<input type="text" class="form-control" id="noteUrl">
<input type="button" class="btn btn-default" id="addNote" data-toggle="modal" data-target="#noteModal" value="Add Note"/>
</form>
PHP (aside from form being submitted to this, this is also included in the modal, which opens, but returns NULL on var_dump($postUrl))
$postUrl = $_REQUEST['noteUrl'];
echo $postUrl;
I could definitely be missing something glaring here, but honestly I've tried every combination of AJAX example I could find on here. Am I missing a huge step about having PHP get the variable? Do I need to refresh a DIV somewhere?
Please help.
Here is a bit neater version of the same code, with the missing quote corrected.
$(function() {
$("#newNote").submit(function() {
$('#notePreview').empty();
var url = "images.php"; // the script where you handle the form input.
var noteUrl = $(this).find('#noteUrl').val();
var request = $.ajax({
type: "POST",
url: url,
data: {noteUrl: noteUrl}
});
request.done(function(data) {
$('#notePreview').append(data);
});
return false; // avoid to execute the actual submit of the form.
});
});
Add the attribute name="noteUrl" to your input
<form id="newNote">
<input type="text" class="form-control" name="noteUrl" id="noteUrl">
<input type="button" class="btn btn-default" id="addNote" data-toggle="modal" data-target="#noteModal" value="Add Note"/>
</form>
You can also do var_dump($_REQUEST); to see what request variables are being sent.
You might have missed the noteUrl as name. Try giving the name as below and get it using the same name. In your case it is noteUrl
<form id="newNote">
<input type="text" class="form-control" name="noteUrl" id="noteUrl">
<input type="button" class="btn btn-default" id="addNote" data-toggle="modal" data-target="#noteModal" value="Add Note"/>
</form>
Shouldn't this
var noteUrl = $('#noteUrl).val();
be
var noteUrl = $('#noteUrl').val();
^^^

Javascript button onclick get input value and submit post request

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
}

Looping through an ajax script to process forms on a page

I have a page with lots of small one line forms, each of which has 5 items. The forms have the id form1, form2, form3, etc, and the id of the items and the submit button follows the same pattern. I have written out the following ajax script for processing the forms one at a time, where the variable $n corresponds to the form and item number. What I am not sure about is how to loop through this script for each form on the page. Do I need to somehow count the number of forms on the page first and then create a loop, and if so how do I do this?
$(".submit$n").click(function() {
var action = $("#form$n").attr('action');
var form_data = {
name: $j("#name$n").val(),
date: $j("#date$n").val(),
attended: $j("#attended$n").val(),
paid: $j("#paid$n").val(),
method: $j("#method$n").val(),
is_ajax: 1
};
$j.ajax({
type: "POST",
url: action,
data: form_data,
success: function(response){
if(response == 'success')
$j("#form$n").fadeOut(800);
console.log(response);
}
});
return false;
});
});
I'm sorry but I don't think this is being set up correctly, and neither is the accepted answer...it's just very messy. I'm not sure if your original code is replicated for every form you have (because the whole $n variable thing confuses me and makes me think you have it several times), but it isn't needed if so. Here's what I would use:
$(document).ready(function () {
$(".submit").click(function () {
var $this = $(this);
var $form = $this.closest("form");
var action = $form.attr('action');
var form_data = {
name: $form.find("[id^=name]").val(),
date: $form.find("[id^=date]").val(),
attended: $form.find("[id^=attended]").val(),
paid: $form.find("[id^=paid]").val(),
method: $form.find("[id^=method]").val(),
is_ajax: 1
};
$.ajax({
type: "POST",
url: action,
data: form_data,
success: function (response) {
if (response == 'success') {
$form.fadeOut(800);
}
console.log(response);
}
});
return false;
});
});
Just give all the submit buttons a class of "submit", and this should work fine. Just to make sure, your HTML would have the format of this:
<form id="form1" action="page1.php">
<input type="text" id="name1" name="name1" /><br />
<input type="text" id="date1" name="date1" /><br />
<input type="text" id="attended1" name="attended1" /><br />
<input type="text" id="paid1" name="paid1" /><br />
<input type="text" id="method1" name="method1" /><br />
<input type="submit" class="submit" value="Submit" />
</form>
Just so you understand what's happening, the Javascript finds the submit button's parent form when it's clicked. Then, with that form, it finds all descendents that have an id attribute that starts with "name", "date", etc. You can do this because you have clearly separated controls into their own forms. So with this code, you can be assured that when you click a submit button, you're grabbing all of the controls' values from the form that it's in.
Add a common class to all your submit buttons, like: <input type="submit" id="submit1" name="submit1" class="submit" />
And then change your code to:
$('.submit').on('click', function() {
var n = this.id.substr(6);
// n is the number of the form. 6 because the word submit has 6 characters.
// You might want to do this some other way.
// you can get the rest of the values by doing
$('#name' + n).val()
// and so on
});

Categories

Resources