HTML5 Form Submit - javascript

I am trying to get a form to submit an action to an ip address without open the ip address.
So, when I hit the submit button I want it to send the post command to the ip (in this case 192.168.0.1) and just refresh the current page.
<div data-role="main" class="ui-content">
<form method="POST" action="http://192.168.0.1/">
<input type="submit" name="parser" value="thisguy"/>
</form>
</div>
My script that runs on submit:
<script src="http://ajax.googleapis.com/ajax/liubs/jquery/1.9.1/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
$('form.ajax').on('submit', function() {
var that = $(this),
url = that.attr('action'),
method = that.attr('method'),
data - {};
that.find('[name]').each(function() {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
$.ajax({
url: url,
type: method:,
data: data,
success: function(response) {}
});
});
return false;
});
</script>
Right now it submits the post and tries to open 192.168.0.1 as a webpage. Can someone help me out either by providing code with an explanation or pointing me to the command?
Any help is appreciated.

You need to prevent the default action (using e.preventDefault())
$('form.ajax').on('submit', function(e) {
e.preventDefault(); // Prevent default submit action (that is, redirecting)
var that = $(this),
url = that.attr('action'),
method = that.attr('method'),
data = {};
that.find('[name]').each(function() {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
$.ajax({
url: url,
type: method:,
data: data,
success: function(response) {}
});
});
return false;
});

Well, you can refresh the page after the POST is done in success method
success: function(response) {
window.location.reload();
}
Also do not forget to disable the form default behavior with
$('form.ajax').on('submit', function(event) {
event.preventDefault();
.
.
});
See documentation for more info

To enable debugging, you should wrap the whole submit handler in a try/catch because without it, errors will cause the default handler to submit the form, masking the errors. After the try/catch you can return false, so the page stays put.
<script src="http://ajax.googleapis.com/ajax/liubs/jquery/1.9.1/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
$('form.ajax').on('submit', function() {
try {
var that = $(this),
url = that.attr('action'),
method = that.attr('method'),
data - {};
that.find('[name]').each(function() {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
$.ajax({
url: url,
type: method:,
data: data,
success: function(response) {}
});
});
}
catch (err) {
console.log( 'submit handler error: ' + err.message );
}
return false;
});
</script>

You just had couple of typo, like - instead of = and extra :, else your code is fine, below is working example.
$(function(){
$('form.ajax').on('submit', function() {
var that = $(this),
url = that.attr('action'),
method = that.attr('method'),
data = {};
that.find('[name]').each(function() {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
$.ajax({
url: url,
type: method,
data: data,
success: function(response) {
alert('posted')
}
});
});
return false;
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div data-role="main" class="ui-content">
<form method="POST" action="http://192.168.0.1/" class="ajax">
<input type="submit" name="parser" value="thisguy"/>
</form>
</div>
My script that runs on submit:

I have done correction to your code.
<script language="javascript" type="text/javascript">
$('form').on('submit', function(e) {
e.preventDefault();
var that = $(this),
url = that.attr('action'),
method = that.attr('method'),
data = {};
that.find('[name]').each(function() {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
$.ajax({
url: url,
type: method,
data: data,
success: function(response) {}
});
});
return false;
});
</script>

Related

Only add data to ajax call if it isnt a null value

I have this div
<div class='additional_comments'>
<input type="text" id='additional_comments_box', maxlength="200"/>
</div>
Which will only sometimes appear on the page if jinja renders it with an if statement.
This is the javascript i have to send an ajax request:
$(document).ready(function() {
var button = $("#send");
$(button).click(function() {
var vals = [];
$("#answers :input").each(function(index) {
vals.push($(this).val());
});
vals = JSON.stringify(vals);
console.log(vals);
var comment = $('#additional_comments_box').val();
var url = window.location.pathname;
$.ajax({
method: "POST",
url: url,
data: {
'vals': vals,
'comment': comment,
},
dataType: 'json',
success: function (data) {
location.href = data.url;//<--Redirect on success
}
});
});
});
As you can see i get the comments div, and I want to add it to data in my ajax request, however if it doesnt exist, how do I stop it being added.
Thanks
You can use .length property to check elements exists based on it populate the object.
//Define object
var data = {};
//Populate vals
data.vals = $("#answers :input").each(function (index) {
return $(this).val();
});
//Check element exists
var cbox = $('#additional_comments_box');
if (cbox.length){
//Define comment
data.comment = cbox.val();
}
$.ajax({
data: JSON.stringify(data)
});

AJAX: form.serialize() and csrf token together?

Can someone say whats wrong with this lane data:... inside saveForm function?
I have list of tasks in my page. Every task has there own form where users can send comments. It means that I have several forms in one page. When I add new task AJAX update list of comments and then I try to send comment by one of the form and it raise error : “CSRF token missing or incorrect”. I have {% csrf_token %} in all my forms.
It seems like I need send CSRF in AJAX. Where I did mistake?
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method) {
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
// TASK
$(function () {
var loadForm = function () {
var btn = $(this);
$.ajax({
url: btn.attr("data-url"),
type: 'get',
dataType: 'json',
beforeSend: function () {
$("#modal").modal("show");
},
success: function (data) {
$("#modal .modal-content").html(data.html_group_task_form);
}
});
};
var saveForm = function () {
var form = $(this);
$.ajax({
url: form.attr("action"),
data: form.serialize().append('csrfmiddlewaretoken', getCookie(csrftoken)),
type: form.attr("method"),
dataType: 'json',
success: function (data) {
if (data.form_is_valid) {
$("#task-list").html(data.html_task);
$("#modal").modal("hide");
}
else {
$("#modal .modal-content").html(data.html_task_form);
}
}
});
return false;
};
// Create task
$("#task-add-button").click(loadForm);
$("#modal").on("submit", ".js-task-add-form", saveForm);
// Update task
$("#task-list").on("click", "#js-edit-task-button", loadForm);
$("#modal").on("submit", ".js-task-edit-form", saveForm);
});
//TASK COMMENT ADD
$(".task-comment-form").submit(function(event) {
event.preventDefault();
console.log(event.preventDefault());
var form = $(this);
$.ajax({
url: form.attr("action"),
data: form.serialize().append('csrfmiddlewaretoken', getCookie(csrftoken)),
type: form.attr("method"),
dataType: 'json',
success: function (data) {
var current_group = form.closest('.custom-list-group');
if (data.form_is_valid) {
current_group.find(".task-comments").html(data.html_task_comment);
}
else {
current_group.find(".task-comment-form").html(data.html_task_comment_form);
}
},
});
form[0].reset();
return false;
});
CODE ABOUT COMMENT ADD:
views.py:
def task_comment_add(request, project_code, task_code):
data = dict()
project = get_object_or_404(Project, pk=project_code)
task = get_object_or_404(Task, pk=task_code)
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.author = request.user
comment.save()
task.comments.add(comment)
data['form_is_valid'] = True
data['html_task_comment'] = render_to_string('project/task_comment_list.html' {'task': group_task})
else:
data['form_is_valid'] = False
else:
form = CommentForm()
context = {'project': project, 'task': task, 'form': form}
data['html_task_comment_form'] = render_to_string('project/task_comment_form.html', context, request=request)
return JsonResponse(data)
JS:
// TASK COMMENT ADD
$(".task-comment-form").submit(function(event) {
event.preventDefault();
console.log(event.preventDefault());
var form = $(this);
$.ajax({
url: form.attr("action"),
data: form.serialize(),
type: form.attr("method"),
dataType: 'json',
success: function (data) {
var current_group = form.closest('.custom-list-group');
if (data.form_is_valid) {
current_group.find(".task-comments").html(data.html_task_comment);
}
else {
current_group.find(".task-comment-form").html(data.html_task_comment_form);
}
}
});
form[0].reset();
return false;
});
.append is for DOM elements.
The result of .serialize is a string.
Why don't you just put the token in a hidden input in the form with a 'name' attr of 'csrfmiddlewaretoken'?
That will serialize it with the rest of your form data.
Here's what I did that worked for ajax forms with Django:
$('#ajax_form').submit(function(e){
e.preventDefault();
var form = this;
var action = $(form).attr('action'); // grab the action as url
var form_array = $(form).serializeArray(); // use serializeArray
form_array.push({ // *expand the array to include a csrf token*
name: 'csrfmiddlewaretoken',
value: getCookie('csrftoken') // getCookie function from django docs
});
var form_data = $.param(form_array); // set it up for submission
$.post(action,form_data,function(resp){
// do stuff after receiving resp
});
});
Basically, I used jquery's .serializeArray() instead of serialize.
.serializeArray() gives you an array of objects like this:
[{name:'name1',value:'value1'},{name:'name2',value:'value2'}]
calling $.param(serilaized_array_data) turns it into a string for submitting. So the key is to add the csrf token to the array. I did that in the code above on the line from_array.push({... with the *'s in the comments.
The problem was in my view. I use this and error disappeared:
context = {...}
context.update(csrf(request))

How to stop function if input is invalid?

I'm trying to get a value of several URL input and if value of URL isn't not valid, I just want to animate input element and stop everything.
Is there any way to do it?
$('button').click(function(e){
var linkarr = [];
var $input = $('.default');
var isValidUrl = /[0-9a-z_-]+\.[0-9a-z_-][0-9a-z]/; // URLvalid check
$input.each(function() {
var inputVal = $(this).val();
if(!isValidUrl.test(inputVal)) {
$(this).parent().animateCss('shake');
// if input is not valid, I want to stop the code here.
}
if(inputVal) linkarr.push(inputVal);
});
e.preventDefault();
$.ajax({
url: '/api/compress',
type: 'POST',
dataType: 'JSON',
data: {url: linkarr},
success: function(data){ something
});
});
You need to let outside of your each loop know the condition of the contents.
$('button').click(function(e){
var linkarr = [];
var $input = $('.default');
var isValidUrl = /[0-9a-z_-]+\.[0-9a-z_-][0-9a-z]/; // URLvalid check
var blnIsValid = true;
$input.each(function() {
var inputVal = $(this).val();
if(!isValidUrl.test(inputVal)) {
$(this).parent().animateCss('shake');
// if input is not valid, I want to stop the code here.
// Input isn't valid so stop the code
blnIsValid = false;
return false; // Alternatively don't stop so that any other invalid inputs are marked
}
if(inputVal) linkarr.push(inputVal);
});
e.preventDefault();
// Check to make sure input is valid before making ajax call
if (blnIsValid) {
$.ajax({
url: '/api/compress',
type: 'POST',
dataType: 'JSON',
data: {url: linkarr},
success: function(data){ something
});
}
});
One method is you can use flag to check and execute the Ajax method
$('button').click(function(e){
var linkarr = [];
var $input = $('.default');
var isValidUrl = /[0-9a-z_-]+\.[0-9a-z_-][0-9a-z]/; // URLvalid check
var callAjax = true;
$input.each(function() {
var inputVal = $(this).val();
if(!isValidUrl.test(inputVal)) {
$(this).parent().animateCss('shake');
callAjax = false;
return false;
// if input is not valid, I want to stop the code here.
}
if(inputVal) linkarr.push(inputVal);
});
e.preventDefault();
if(callAjax)
{
$.ajax({
url: '/api/compress',
type: 'POST',
dataType: 'JSON',
data: {url: linkarr},
success: function(data){ something
});
}
});

Refresh div with AJAX after form submit

I want to show the loading img before AJAX response every time I submit the form. The problem is that img appears only on the first submission.
This is my code :
$('form.ajax').on('submit', function(){
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value ){
$('#response').html(' loading...');
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response) {
console.log(response);
$(".ajax")[0].reset();
$("#response").hide();
}
});
return false;
});
You're not showing response section after hiding it in the first time
use this line
$("#response").show();
in the beginning
$('form.ajax').on('submit', function(){
$("#response").show();
/* bla bla your code bla bla
............................
*/
});

statying on the same page after submitting the form

I was trying to submit data to database without redirecting the page.is there any error in this code?
$('#saving').on('click', function() {
var fname = $('#fname').val();
var lname = $('#lname').val();
var company = $('#company').val();
var mnum = $('#mnum').val();
var dataString = 'fname=' +fname + '&lname=' + lname + '&company=' + company + '&mnum=' + mnum;
$.ajax({
type: "POST",
url: "submit.php",
data: dataString,
success: function() {
alert('');
$('#dialog-message').dialog('open');
}
});
});
I think you want preventDefault:
function(event) {
// ... ajax ...
event.preventDefault();
}
The documentation states:
If this method is called, the default action of the event will not be triggered.

Categories