Refresh div with AJAX after form submit - javascript

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
............................
*/
});

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)
});

jQuery Ajax GET request not working correctly

I'm trying to call an AJAX query and have had lots of trouble recently.
Im trying to call a api that I have custom made myself, it displays this when the url api/reverse/test - tset (is just uses a php function to reverse the text given in the slug3.
That function works fine, just wanted to give some back on what gets requested.
reverse.php - HTML File
<textarea id="input"></textarea>
<div id="output">
</div>
index.js - All of my jQuery and AJAX
$(document).ready(function(){
var $input = $('#input');
var $output = $('#output');
$input.on('keyup', function(){
var text = $input.val();
var url = 'http://coder.jekoder.com/api/?area=reverse&text='+text;
$.ajax({
type: 'GET',
url: url,
dataType: 'text',
success: function(data) { var output = data; },
error: alert('fail')
}) // End of AJAX
$output.html = output;
});
});
api.php - PHP file being called
<?php
$area = $_GET['area'];
if ($area == 'reverse') {
if (isset($_GET['text']) ) $text = $_GET['text'];
else $text = 'Hello';
echo strrev($text);
}
It's then supposed to take the output variable and display that in a div but that's not the main thing that matters.
error removed - was trying to see if it fixed it
There are several issue I found:
Jquery:
var text = $('#input').val(); // if you are getting value from any inputbox - get value using .val() function
var url = 'http://localhost/test.php?data='+text; // pass data like this ?data='+text
// AJAX START
$.ajax({
type: 'GET',
url: url,
dataType: 'text',
async: true,
success: function(data) { var output = data; alert(output)},
error: function(data) { alert('fail') }
});
In php you ca get data like this:
echo $_GET['data'];
exit;
Try this. Scope of variable output is within the success call and you are using it outside the ajax call.
$(document).ready(function()
{
var $input = $('#input');
var $output = $('#output');
$input.on('keyup', function()
{
var text = $input.val();
var url = 'http://coder.jekoder.com/api/?area=reverse&text='+text;
$.ajax({
type: 'GET',
url: url,
dataType: 'text',
success: function(data) { var output = data; $output.html = output;},
error: alert('fail')
}) // End of AJAX
});
});

HTML5 Form Submit

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>

Re factoring jQuery functions

How can refactor this below jQuery code.
All the functions does the same job but on different key-presses on the table search box. Which is filtering the table data.
I want re factor this code and write it in single function. Please help me.
jQuery(function($) {
// when the #name field changes
$("body").on("keypup", "#name", function() {
var form = $("#users_form"); // grab the form wrapping the name bar.
var url = form.attr("action");
var formData = form.serialize();
$.get(url, formData, function(data) {
$("#reseller_admin_list").html(data); // replace the "results" div with the result of action taken
});
$("body").on("keypup", "#login", function() {
var form = $("#users_form"); // grab the form wrapping the name bar.
var url = form.attr("action");
var formData = form.serialize();
$.get(url, formData, function(data) {
$("#reseller_admin_list").html(data); // replace the "results" div with the result of action taken
});
$("body").on("keypup", "#account_manager", function() {
var form = $("#users_form"); // grab the form wrapping the name bar.
var url = form.attr("action");
var formData = form.serialize();
$.get(url, formData, function(data) {
$("#reseller_admin_list").html(data); // replace the "results" div with the result of action taken
});
$("body").on("keypup", "#email", function() {
var form = $("#users_form"); // grab the form wrapping the name bar.
var url = form.attr("action");
var formData = form.serialize();
$.get(url, formData, function(data) {
$("#reseller_admin_list").html(data); // replace the "results" div with the result of action taken
});
});
});
function update() {
var form = $("#users_form"); // grab the form wrapping the name bar.
var url = form.attr("action");
var formData = form.serialize();
$.get(url, formData, function(data) {
$("#reseller_admin_list").html(data); // replace the "results" div with the result of action taken
});
}
$("body").on("keyup", "#account_manager, #login, #email", update);
The explanation:
1.) We extract the duplicate code in a single function called update. We follow the DRY principle here
2.) JQuery allows us to use multiple selectors, so we can bind the update function to all elements at once:
$("body").on("keyup", "#account_manager, #login, #email", update);
instead of calling:
$("body").on("keyup", "#account_manager", update);
$("body").on("keyup", "#login", update);
$("body").on("keyup", "#email", update);
how about just having one code block:
$("body").on("keypup", "#name, #login, #account_manager, #email", function() {
var form = $("#users_form");
var url = form.attr("action");
var formData = form.serialize();
$.get(url, formData, function(data) {
$("#reseller_admin_list").html(data);
});
});
Much better though, would be to give you elements a class, and bind to the class rather then each id, i.e.
$("body").on("keypup", ".someClass", function() { //etc
write a new function.
$("body").on("keypup", "#login", function() {
functionName();
});
and in function
function functionName(){
var form = $("#users_form"); // grab the form wrapping the name bar.
var url = form.attr("action");
var formData = form.serialize();
$.get(url, formData, function(data) {
$("#reseller_admin_list").html(data); // replace the "results" div with the result of action taken
});`
}

Comment reply not display properly by JS

For prevent the refresh of the page after submitting the form I want to add return false;
Also have default browser behavior problem to refresh this page.
But if I add return false; or e.preventDefault(); reply of any comment show duplicate under only last/top/new comment AND after a refresh Its show original comment. not only that delete comment show loader continuously.
Now I think my problem either my html structure or JavaScript.
HTML of index.php:
<div class="content"><comment>
<div class="post'.$id.'">
//here main comment goes on
</div>
<div class="reply'.$id.'" id="replynext"><ul>
//here reply goes on
</ul></div>
<comment></div>
HTML of Reply.php:
<div class="reply'.$id.'" id="replynext"><ul>
//new reply goes here
</ul></div>
JS for reply without return false;:
var inputAuthor = $("#author");
var inputComment = $("#comment");
var inputReplycom = $(".replycom");
var inputImg = $("#img");
var inputUrl = $("#url");
var inputTutid = $("#tutid");
var inputparent_id = $("#parent_id");
var commentList = $(".content > comment");
function updateReplybox(){
var tutid = inputTutid.attr("value");
//just for the fade effect
$.ajax({
type: "POST", url: "reply.php", data: "action=update&tutid="+ tutid,
complete: function(data){
var RID = $(this).attr('class').replace('reply','');
$(".reply"+RID).append(data.responseText);
$(".reply"+RID).fadeIn(2000);
}
});
}
//on submit reply
$(".repfrm").click(function(){
error.fadeOut();
var author = inputAuthor.attr("value");
var url = inputUrl.attr("value");
var img = inputImg.attr("value");
var replycom = inputReplycom.attr("value");
var parent_id = inputparent_id.attr("value");
var tutid = inputTutid.attr("value");
$(".loader").fadeIn(400).html('<br><img src="loaders.gif" align="absmiddle"> <span class="loading">Loading Update...</span>');
//send the post to submit.php
$.ajax({
type: "POST",
url: "reply.php",
data: "action=insert&author="+ author + "&replycom="+ replycom + "&url="+ url + "&img="+ img + "&parent_id="+ parent_id + "&tutid="+ tutid,
complete: function(data){
error.fadeOut();
$(".reply"+RID).append(data.responseText);
updateReplybox();
//reactivate the send button
}
});
error_message();
//we prevent the refresh of the page after submitting the form
});

Categories