jQuery form plugin - no response, no errors - javascript

I'm using this plugin.
I've rewritten my code to work with the example:
function showRequest(formData, jqForm, options) {
var queryString = $.param(formData);
return true;
}
function showResponse(responseText, statusText, xhr, $form) {
$(".afterSend").removeClass("preloader");
$(".afterSend").empty().append(responseText);
}
$(function() {
$('form.wycena').bind("submit", function(e){
e.preventDefault();
if($('.formBox').hasClass('lightBox')) {
$(".afterSend").empty().addClass("preloader");
$("form.wycena").ajaxForm({
target: '.afterSend',
beforeSubmit: showRequest,
success: showResponse
});
}
else {
/* verify before sending */
toggleLightBox(true);
}
});
});
My code works, but ajaxForm and its callback functions (showRequest, showRespons) seems to do nothing at all. It is supposed to run the script defined in form's action field and show response in the .afterSend div, but I get nothing. Not even a single error in console.

Related

Form request is made three times: Status 200 OK

I created a form on /contact-us and having action="/contact-us". Now, when I added Ajax to it, it is sending the request three times, i cannot find the reason.
Ajax:
define(['jquery', 'foundation.alert'], function($) {
return {
init: function() {
$("#success-alert").hide();
$("#error-alert").hide();
$('button').click(function(e){
$('input').map(function() {
if(!$(this).val()) {
$("#error-alert").show();
$("#success-alert").hide();
return false;
} else {
$('document').ready(function() {
var form = $('#contact_us'); // contact form
var submit = $('button'); // submit button
var status = $('#form-status'); // alert div for show alert message
// form submit event
form.on('submit', function(e) {
e.preventDefault(); // prevent default form submit
$.ajax({
url: '/contact-us', // form action url
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: form.serialize(), // serialize form data
beforeSend: function() {
submit.html('Sending....'); // change submit button text
},
success: function(data) {
form.trigger('reset'); // reset form
$("#success-alert").show();
$("#error-alert").hide();
submit.html('Send'); // reset submit button text
},
error: function(e) {
console.log(e);
}
});
});
});
}
});
});
}
}
});
You are looping through all the inputs and applying on submit for every input in your form. So if it is submitting 3 times, you must have three inputs. Each time you click the button, you will be adding even more submit handlers! The whole design of this is wrong.
You should not be attaching the submit handler inside of the click event, it should be outside and have it done one time. Do your validation inside of the submit handler to make sure that it is valid before making the Ajax call.
try this solution.
var wait = false;
wait variable for global scope
if (!wait) {
wait = true;
$.ajax({
url: '/contact-us', // form action url
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: form.serialize(), // serialize form data
beforeSend: function () {
submit.html('Sending....'); // change submit button text
},
success: function (data) {
wait = false;
form.trigger('reset'); // reset form
$("#success-alert").show();
$("#error-alert").hide();
submit.html('Send'); // reset submit button text
},
error: function (e) {
console.log(e)
}
});
}
After going through my code i realized what mistakes i have been doing and also realized that reading code is more important than writing it.
This is how i rewrite the code and its working fine but i am still not sure if it is the best approach.
define(['jquery', 'foundation.alert'], function($) {
return {
init: function() {
$("#success-alert").hide();
$("#error-alert").hide();
$(function () {
$('#contact_us').on('submit', function (e) {
$.ajax({
type: 'post',
url: '/contact-us',
data: $('#contact_us').serialize(),
success: function () {
$("#success-alert").show();
$("#error-alert").hide();
}
});
e.preventDefault();
});
});
$('button').click(function(e){
$('input').map(function() {
if(!$(this).val()) {
$("#error-alert").show();
$("#success-alert").hide();
return false;
}
});
});
}
}
});
Note: Never take writing code as a burden.

Ajax Div toggle avoiding reloading content

I had a question regarding Ajax loading of html into a DIV. Ideally what I want is this:
A toggle div with close button, which I have the code for here: http://jsfiddle.net/tymeJV/uhEgG/28/
$(document).ready(function () {
$('#country').click(function () {
$("#country_slide").slideToggle(function() {
if ($(this).is(":visible")) {
alert("im visible!");
}
});
});
$('#close').click(function (e) {
e.preventDefault();
$('#country_slide').slideToggle();
});
});
Then I want some AJAX code to load a html file into the div when the div is expanded. The trick is that if the HTML is loaded successfully, I want it to avoid reloading the HTML file again if the div is closed and repoened, since I have already loaded it, and just simply toggle the content in and out with the button. The code I have for this (which I got help on from here is this):
http://jsfiddle.net/spadez/uhEgG/55/
$(function () {
$('#country_link').on('click', function (e) {
// Prevent from following the link, if there is some sort of error in
// the code before 'return false' it would still follow the link.
e.preventDefault();
// Get $link because 'this' is something else in the ajax request.
var $link = $(this);
// Exit if the data is loaded already
if ($link.data('loaded') === true)
return false;
$.ajax({
type: 'GET',
dataType: 'html',
url: '/ajax/test.html',
timeout: 5000,
beforeSend: function () {
},
success: function (data, textStatus) {
$("#country_slide").html(data);
alert('request successful');
// If successful, bind 'loaded' in the data
$link.data('loaded', true)
},
error: function (xhr, textStatus, errorThrown) {
$("#country_slide").html('Error');
},
complete: function () {
},
});
});
});
I haven't been able to get this working yet though. So my question is, is it actually possible to do this, and if it is, can anyone with more experience with jquery please help me integrate the div toggle with the ajax loading script.
This is one of my first jquery scripts and I am having a bit of a hard time with it, perhaps it is not for beginners. Thank you.
I edited the fiddle you posted adding the call to slideToogle() where appropriate. Also added a div element to hold the loaded html code.
<div id="country_slide">
Close
<div class=".content"></div> <!-- This is the div I added -->
</div>
You can check the log messages in the console to verify that the code is doing what you expect. The URL for the Ajax call you were doing always returned an error so I changed to the URL that jsfiddle provides for testing: /echo/html/.
Here's the modified JS code:
$(function () {
$('#close').click(function (e) {
e.preventDefault();
$('#country_slide').slideToggle();
});
$('#country_link').on('click', function (e) {
e.preventDefault();
var $link = $(this);
// Exit if the data is loaded already
if ($link.data('loaded') === true) {
console.log('Not using Ajax.');
$("#country_slide").slideToggle();
return false;
}
$.ajax({
type: 'GET',
dataType: 'html',
url: '/echo/html/',
timeout: 5000,
beforeSend: function () {
$("#country_slide .content").html('<p>Loading</p>')
},
success: function (data, textStatus) {
console.log('Fecthed with Ajax.');
$("#country_slide .content").html(data);
$("#country_slide").slideToggle();
// If successful, bind 'loaded' in the data
$link.data('loaded', true)
},
error: function (xhr, textStatus, errorThrown) {
alert('request failed');
},
complete: function () {
},
});
});
});

Prevent Ajax Form Submission Without Content

I'm trying to get some client side validation working to prevent a form submission occurring if an object has no value. I've been plugging away at this for a while now but cannot get a satisfactory solution.
My form submission Js looks like this:
$(document).ready(function () {
$('#localUsersDateTime').val(setLocalDateTime());
$('#createentry').ajaxForm({
beforeSubmit: checkTextObjHasValue($('#newentry'), 'You need to add some text.'),
dataType: 'json',
success: function (result) {
$('#entries-list').prepend('<li>' + $('#newentry').val() + '</li>');
$('#newentry').val('').blur();
},
error: function (xhr)
{
try {
var json = $.parseJSON(xhr.responseText);
alert(json.errorMessage);
} catch (e) {
alert('Oops, Something very bad has happened');
}
}
});
return false;
});
However when the page loads it runs my checkTextObjHasValue() specified in the beforeSubmit: function so that check needs to only execute on actual form submission.
function checkTextObjHasValue(obj, message) {
if ($(obj).val() === '') {
alert(message);
return false;
}
return true;
}
How can I prevent this beforeSubmit: callback from being executed when just loading the page and only execute on actual form submission?
The beforeSubmit option expects a reference to a function. You were immediately calling a function. Try using this:
beforeSubmit: function () {
return checkTextObjHasValue($('#newentry'), 'You need to add some text.');
},
The added return allows for the submission to cancel if false is actually returned (which is possible in checkTextObjHasValue under a certain condition).
Technically, it could've worked if you returned a function from checkTextObjHasValue, but I think this way is a little cleaner. And it lets you customize it in case you want to validate several fields.
UPDATE:
Like in the documentation for the plugin, you could take this approach:
beforeSubmit: beforeSubmitHandler,
And then define a function separately like this:
function beforeSubmitHandler() {
return checkTextObjHasValue($('#newentry'), 'You need to add some text.');
}

Ajax not loading in IE

Here is the script. It works fine in all other browsers, so I thought it was a cache problem but not really. I have been banging my head for hours and nothing is working.
$.ajaxSetup({
cache: false
});
$("#send").live('click', function () {
console.log("AAAAA");
$("#loader").show();
$form = $('#reservationForm');
$inputs = $form.find('input[name^="entry"]'),
serializedData = $('#reservationForm :input[name^="entry"]').serialize();
console.log(serializedData);
serializedData += "&pageNumber=0&backupCache=1&submit=Submit";
// fire off the request to /form.php
$.ajax({
url: "https://docs.google.com/spreadsheet/formResponse?formkey=d",
// url: "https://docs.google.com/spreadsheet/formResponse?formkey=d;ifq",
type: "post",
data: serializedData,
// callback handler that will be called on success
success: function (response, textStatus, jqXHR) {
// log a message to the console
console.log("Hooray, it worked!");
$("#loader").hide();
document.getElementById('error<?php echo"$uname";?>').innerHTML = error;
$("#success").fadeIn();
setTimeout(function () {
$("#success").fadeOut();
}, 5000);
},
// callback handler that will be called on error
error: function (jqXHR, textStatus, errorThrown) {
// log the error to the console
console.log("The following error occured: " + textStatus, errorThrown);
alert('Due to an unknown error, your form was not submitted, please resubmit it or try later.');
},
// callback handler that will be called on completion
// which means, either on success or error
complete: function () {
// enable the inputs
$inputs.removeAttr("disabled");
}
});
// prevent default posting of form
event.preventDefault();
});
console.log is available after you open Developer Tools (F12 to open) in IE. Try turning it on or use an alert instead in your code.
or use a try catch;
try{
console.log('worked')
}
catch(err){
}
And You might want to check if your event variable is undefined:
event= event || window.event;
event.preventDefault();
At the beginning of the script you are not adding the "event" declaration in the handler:
$("#send").live('click', function () {
should be:
$("#send").live('click', function (e) {
And at the end of the script there is a reference for the variable event:
// prevent default posting of form
event.preventDefault();
I think that IE doesn't have a 'preventDefualt' function in the global event object (which you are referencing): this function is added to the "e" event object passed by jQuery. Any way, it should fail too in all other browsers with a "event is not defined". Try this too:
// prevent default posting of form
e.preventDefault();
An additional note: jQuery team currently discourage the use of the "live" event binding function, instead you should use the equivalent form of the "on" function.
IE doesn't understand the content type of response in ajax. So put your dataType value in the request and it should work.
for e.g. -
dataType: ($.browser.msie) ? "text" : "xml"

jQuery: How to apply a function to all elements including some which are loaded later via Ajax?

I have a simple jQuery function that resizes text areas, and I want it to apply to all text areas.
For the most part, this works great:
$(document.ready(function(){$("text_area").resizer('250px')});
However, because it is only called once when the document is ready, it fails to catch text areas that are later added onto the page using Ajax. I looked at the .live() function, which seems very close to what I'm looking. However, .live() must be bound to a specific event, whereas I just need this to fire once when they're done loading (the onLoad event doesn't work for individual elements).
The only thing I can get working is a really obtrusive inclusion of the JavaScript call directly into the Ajax. Is that the recommended way to be doing this?
Edit: Here is the rails source code for what it does for Ajax requests:
$('a[data-confirm], a[data-method], a[data-remote]').live('click.rails', function(e) {
var link = $(this);
if (!allowAction(link)) return false;
if (link.attr('data-remote') != undefined) {
handleRemote(link);
return false;
} else if (link.attr('data-method')) {
handleMethod(link);
return false;
}
});
// Submits "remote" forms and links with ajax
function handleRemote(element) {
var method, url, data,
dataType = element.attr('data-type') || ($.ajaxSettings && $.ajaxSettings.dataType);
if (element.is('form')) {
method = element.attr('method');
url = element.attr('action');
data = element.serializeArray();
// memoized value from clicked submit button
var button = element.data('ujs:submit-button');
if (button) {
data.push(button);
element.data('ujs:submit-button', null);
}
} else {
method = element.attr('data-method');
url = element.attr('href');
data = null;
}
$.ajax({
url: url, type: method || 'GET', data: data, dataType: dataType,
// stopping the "ajax:beforeSend" event will cancel the ajax request
beforeSend: function(xhr, settings) {
if (settings.dataType === undefined) {
xhr.setRequestHeader('accept', '*/*;q=0.5, ' + settings.accepts.script);
}
return fire(element, 'ajax:beforeSend', [xhr, settings]);
},
success: function(data, status, xhr) {
element.trigger('ajax:success', [data, status, xhr]);
},
complete: function(xhr, status) {
element.trigger('ajax:complete', [xhr, status]);
},
error: function(xhr, status, error) {
element.trigger('ajax:error', [xhr, status, error]);
}
});
}
So in my particular case, I've got a link, that has data-remote set to true, which points to a location that will return JavaScript instructing a form containing a text area to be appended to my document.
A simple way to do this would be to use ajaxComplete, which is fired after every AJAX request:
$(document).ajaxComplete(function() {
$('textarea:not(.processed)').resizer('250px');
});
That says "every time an AJAX request completes, find all textarea elements that don't have the processed class (which seems to be added by the resizer plugin -- terrible name for its purpose!) and call the resizer plugin on them.
You may be able to optimise this further if we could see your AJAX call.
Generally speaking, I would do it this way..
$.ajax({
type : "GET",
url : "/loadstuff",
success: function(responseHtml) {
var div = $("#containerDiv").append(responseHtml);
$("textarea", div).resizer("250px");
}
});
Wondering if you could use .load for this. For example:
$('text_area').load(function() {
$("text_area").resizer('250px');
});

Categories

Resources