Mootools form submit & content change - javascript

I'd like to replace my_div's content after user clicks the submit button with the output that comes from my.php. I want to achieve this using mootools javascript library. How can I do this?
<div id="my_div">
<form name="myform" action="http://www.domain.com/my.php" method="POST">
<br><br>
<input type="text" size="25" value="Enter your name here!">
<br><input type="submit" value="Send me your name!">
</div>
Thanks for reading.

You should give the submit button an id, I chose 'fsubmit' in this example. And 'f' is the id of the form.
$('fsubmit').addEvent('click', function(e) {
e = new Event(e).stop();
var url = $('f').get('action');
var request = new Request({
url: url,
method: 'get',
onComplete: function(response) {
$('my_div').set('html', response);
}
});
request.send();
});
Or you could use a shortcut:
http://mootools.net/docs/core/Request/Request.HTML

Actually, MooTools More has this Form.Request package which does exactly what you need.

Related

Make an HTML button redirect me to another page [duplicate]

This question already has answers here:
Javascript Button Redirect
(4 answers)
Closed 1 year ago.
How do I make this button redirect me to another page?
<button type="submit" onclick="register()">Create new account</button>
Here is the function that the button is using:
function register() {
let object = {
"username": document.getElementById("username").value,
"password": document.getElementById("password").value
};
let json = JSON.stringify(object);
let xhr = new XMLHttpRequest();
xhr.open("POST", '/api/user/new', false)
xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8');
xhr.send(json);
if (xhr.status != 200) {
alert("Something went wrong!");
} else if (xhr.status == 200){
alert("Success!");
}
}
I want the button to redirect me to 'index.html' file
Try wrapping button in form tag like this:
<form action="index.html">
<button type="submit" onclick="register()">Create new account</button>
</form>
It seems this has already been answered in quite extensive way:
How do I redirect to another webpage?
to sum up: there is a number of ways to achieve that:
// window.location
window.location.replace('http://www.example.com')
window.location.assign('http://www.example.com')
window.location.href = 'http://www.example.com'
document.location.href = '/path'
// jQuery
$(location).attr('href','http://www.example.com')
$(window).attr('location','http://www.example.com')
$(location).prop('href', 'http://www.example.com')
If You want to go there after successful call of the function - put one of these instead of "alert("Success!");"
<form action="/action_page.php" method="get">
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"><br><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname"><br><br>
<button type="submit">Submit</button>
<button type="submit" formaction="/action_page2.php">Submit to another page</button>
</form>
Example
A form with two submit buttons. The first submit button submits the form data to "action_page.php", and the second submits to "action_page2.php":
Definition and Usage
The formaction attribute specifies where to send the form-data when a form is submitted. This attribute overrides the form's action attribute.
The formaction attribute is only used for buttons with type="submit".
Please refer this link: https://www.w3schools.com/tags/att_button_formaction.asp

Issue with AJAX form submit

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

Refresh a specific class after post ajax Javascript

So after lot of researchs, I come here to request your help, there is my problem :
I have a comment system with multiple forms on a same page (I use FOSCommentBundle on Symfony). And I want to be able to post comments with Ajax (this part work, no problems) and refresh the comment section after the post is submitted (And i'm stuck on this part).
There is an example of code :
$(document).on("submit", ".postAjax", function(e){
e.preventDefault();
$(this).LoadingOverlay("show");
data = $(this).serializeObject();
$.ajax({
url: $(this).attr('action'),
type: 'POST',
success:function(){
$(".comments").load(window.location.href + " .comments");
}
});
});
<form method="POST" class="postAjax" action="./comment/post/1">
<input type="textarea" name="comment">
<input type="hidden" name="identifier" value="1">
<input type="submit">
</form>
<div class="comments">
<!-- Comments refreshed after post here -->
</div>
<form method="POST" class="postAjax" action="./comment/post/2">
<input type="textarea" name="comment">
<input type="hidden" name="identifier" value="2">
<input type="submit">
</form>
<div class="comments">
<!-- Comments refreshed after post here -->
</div>
<!-- ... -->
I have tried lot of things, the function ".load" of JQuery but it load all the "comments" class and duplicate the comments in each class.
If someone have a solution... Thank you
First of all, in the provided code, your <form> tag lack an action attribute for your code to work properly.
Then, to answer your question, modify your controller action (the one saving your new comment) so that it return the informations of the submitted comment (json format is better). Then, transform the returned json into html code, and append the result to your comments <div>, for example :
$(document).on("submit", ".postAjax", function(e){
e.preventDefault();
$(this).LoadingOverlay("show");
data = $(this).serializeObject();
var element = $(this);
$.ajax({
url: $(this).attr('action'),
type: 'POST',
success:function(newCommentData){
/* do some process here to transform your newCommentData array into html code */
$(element).next(".comments").append(newCommentData);
}
});
});
Also, if you want it to be cleaner, you could have an hidden 'div', with the same model as a comment div, but with each content replaced by patterns ( ex : %commentTitle%, %commentBody% ). Then each time you post a new comment, you could get that hidden div, and replace patterns with your comment data. That way, if you change comment section structure later, the JS script will still work the same way, without adjustments needed.
Try this
$(document).on("submit", ".postAjax", function(e){
e.preventDefault();
$(this).LoadingOverlay("show");
data = $(this).serializeObject();
var $comment = $(this).next(".comments");
$.ajax({
url: $(this).attr('action'),
type: 'POST',
success:function(){
$comment.append("<div />");
$comment.last("div").load(window.location.href + " .comments");
}
});
});

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.

Categories

Resources