preventDefault is not working - javascript

I am trying to send an ajax request to complete a task when a link is clicked. For some reason the e.preventDefault is not working and I still get sent to the page. Is there something I am missing?
It is simply supposed to go to the page set the check-box to checked (or unchecked) then redirect. But again it just goes to the page. Any help would be great!
here is the main.js
$(function() {
$('.ajax-task-complete').on({
click: function(e) {
e.stopPropagation();
e.preventDefault();
var href = $(this).attr('href');
$('<div></div>').load(href+' form', function() {
// Set Form
var form = $(this).children('form');
// Set Checkbox
var cb = form.find('input[type="checkbox"]');
// Taggle Checkbox
cb.prop('checked', !cb.prop('checked'));
// Form Action URL
var url = form.attr('action');
// Set Data
var data = form.serialize();
$.ajax({
url: url,
data: data,
method: 'post',
dataType: 'json',
cache: false,
success: function(obj) {
var tic = $('#task-complete-' + obj.id + ' .ajax-task-complete');
},
complete: function() {
console.log('complete');
},
error: function(err) {
console.log(err);
}
});
});
}
});
});
here is the requested button
<td id="task-complete-{{ entity.id }}">
{% if entity.completed %}
<a class="check ajax-task-complete" href="{{ path('task_edit_complete', { 'id': entity.id }) }}">✔</a>
{% else %}
<a class="uncheck ajax-task-complete" href="{{ path('task_edit_complete', { 'id': entity.id }) }}">✔</a>
{% endif %}
</td>

This is your problem:
Uncaught ReferenceError: $ is not defined?
Read HERE from SO how you load your jQuery-plugin the right way.

you might need to stop bubbling depending on where the click event is occurring. Try adding this and see what happens.
e.stopPropagation();

**"$"**
is missing before (function() {
javascript pageload event should be like
$(function(){
//code here
});
or
function will be called by themself
(function(){
//code here
)}();
or
(function($){
//code here
})(jQuery)
You can check the fiddle here

Your scope is wrong, you are missing the () after (function)(). The function is never called :
(function() {
$('.ajax-task-complete').on({
click: function(e) {
e.stopPropagation();
e.preventDefault();
var href = $(this).attr('href');
$('<div></div>').load(href+' form', function() {
// Set Form
var form = $(this).children('form');
// Set Checkbox
var cb = form.find('input[type="checkbox"]');
// Taggle Checkbox
cb.prop('checked', !cb.prop('checked'));
// Form Action URL
var url = form.attr('action');
// Set Data
var data = form.serialize();
$.ajax({
url: url,
data: data,
method: 'post',
dataType: 'json',
cache: false,
success: function(obj) {
var tic = $('#task-complete-' + obj.id + ' .ajax-task-complete');
},
complete: function() {
console.log('complete');
},
error: function(err) {
console.log(err);
}
});
});
}
});
})(); //Add () here
But is the scope really needed here?
Maybe you meant a ready handler, then it should be like this :
$(function); //Missing '$'

Try placing the preventDefault event at the end of the function as below
$('.ajax-task-complete').on({
click: function(e) {
//
//your code here then,
e.preventDefault();
e.stopPropragation();
});
I can't test if it works or not, as I'm on mobile.

Related

Need to be able to run an ajax call with element loaded after document.ready()

I've got checkbox inputs on a page and am filtering the results using ajax.
One search option is type and the vendors option updates depending on the type selected. But this means that the change function used to update the actual results no longer works within the document.ready(). To rectify this, I also call the function within .ajaxComplete().
But as an ajax call is being called within the ajaxComplete(), it is causing an infinite loop and crashing the site.
$(document).ready(function(){
$('input[type=radio]').change(function(){
var type = $(this).attr('data-id');
$.ajax({
method: 'POST',
url: 'assets/ajax/update-filters.php',
data: {type : type},
success: function(data)
{
$('#vendor-filter input[type=checkbox]').prop('checked', false);
vendors = [];
$('#vendor-filter').empty();
$('#vendor-filter').html(data);
}
});
$('#vendor-filter input[type=checkbox]').change(function(){
filterResults(this);
});
});
$(document).ajaxComplete(function(){
$('#vendor-filter input[type=checkbox]').click(function(){
filterResults(this);
});
});
function filterResults($this)
{
var type = $('input[type=radio]:checked').attr("data-id");
var vendor = $($this).attr('data-id');
if($($this).prop('checked'))
{
var action = 'add';
vendors.push(vendor);
}
else
{
var action = 'remove';
var index = vendors.indexOf(vendor);
if(index >= 0)
{
vendors.splice(index, 1);
}
}
$.ajax({
method: 'POST',
url: 'assets/ajax/filter-results.php',
data: {'vendor' : vendor, 'action' : action, 'vendors' : vendors, 'filter_type' : type},
success: function(data)
{
$('#results').empty();
if(action == 'add')
{
window.history.pushState("", "Title", window.location.href+"&v[]="+vendor);
}
else if(action == 'remove')
{
var newUrl = window.location.href.replace("&v[]="+vendor, "");
window.history.replaceState("", "Title", newUrl);
}
$('#results').html(data);
}
});
}
How do I get the .change function to still work after the input checkbox has been called via ajax previously and without causing a loop with .ajaxComplete() ?
Any help would be greatly appreciated.
Thanks
Please try by change function as follow :
$(document.body).on("change",'input[type=radio]',function(){
var type = $(this).attr('data-id');
$.ajax({
method: 'POST',
url: 'assets/ajax/update-filters.php',
data: {type : type},
success: function(data)
{
$('#vendor-filter input[type=checkbox]').prop('checked', false);
vendors = [];
$('#vendor-filter').empty();
$('#vendor-filter').html(data);
}
});

div.load() causing full page postback

After saving form data, need to load the div only not whole page refresh but it first goes to Main Page Action Controller and then the DIV Load Partial Action Controller. I am unable to find the reason why it is posting whole page.
I have added the preventDefault() command too.
$("#btnSave").click(function (e) {
e.preventDefault();
var url = "#Url.Action("Save", "Note")";
var id = "1";
var model = {
modelfields.....
};
$.ajax({
type: "POST",
data: JSON.stringify(model),
url: url,
contentType: "application/json",
success: function (data) {
if (data == "True") {
// Load div
var settings = { editUrl: '#Url.Action("Get", "Note", new { ID = "-1" })' };
settings.editUrl = settings.editUrl.replace("-1", id);
$("#divNoteDetails").load(settings.editUrl);
}
else if (data == "False") {
alert('not saved');
}
},
error: function () {
alert('error');
}
});
return false;
});
if your button is inside a form then its default type is submit. see the spec for details
try adding type="button" to the button, or event.preventDefault() on an event handler attached to the form itself.

Jquery onchange Ajax

i made a function that sends data (ajax) to the database and depending on the response from the server i need to alert a message but it seems like whenvever i change the select option i get the alert message for each change(if i change the select four times when i click i get the alert four times ) , but if i remove my ajax function and replace it simply by an alert i get it once not repeating itself here is my JS
$('.select_ids').change(function () {
var id = $(this).val();
var form = $('#form_widget_ids_' + id);
var container = form.parent('.ewb_forms');
var box = container.parent('.edit_widget_box');
container.children('.selected').fadeOut(300, function () {
$(this).removeClass('selected');
form.fadeIn(300, function () {
$(this).addClass('selected');
});
});
Widget.updateSSOUrl(box);
$.ajax({
type: "POST",
url: window.location + "",
data: {'id': id}
}).done(function (msg) {
$(".red").on('click', function (evt) {
if ('done' == msg) {
evt.preventDefault();
alert('NOP');
}
})
});
});
the event that you are binding i think is wrong. For newly append items is better in your case to use
$(document).on('click', ".red", function (evt) {
})
And it must be moved outside the ajax success because now you are triggering it every time
----- Edited ---
If you want just to alert the output of the ajax you dont need the onClick event
$('.select_ids').change(function () {
var id = $(this).val();
var form = $('#form_widget_ids_' + id);
var container = form.parent('.ewb_forms');
var box = container.parent('.edit_widget_box');
container.children('.selected').fadeOut(300, function () {
$(this).removeClass('selected');
form.fadeIn(300, function () {
$(this).addClass('selected');
});
});
Widget.updateSSOUrl(box);
$.ajax({
type: "POST",
url: window.location + "",
data: {'id': id}
}).done(function (msg) {
if (msg === 'done') {
evt.preventDefault();
alert('NOP');
}
});
});
If you want to show the latest result on a button click you can store the msg on a global variable and on click of a div show that like
var globalMsg = "";
$('.select_ids').change(function () {
var id = $(this).val();
var form = $('#form_widget_ids_' + id);
var container = form.parent('.ewb_forms');
var box = container.parent('.edit_widget_box');
container.children('.selected').fadeOut(300, function () {
$(this).removeClass('selected');
form.fadeIn(300, function () {
$(this).addClass('selected');
});
});
Widget.updateSSOUrl(box);
$.ajax({
type: "POST",
url: window.location + "",
data: {'id': id}
}).done(function (msg) {
globalMsg = msg
});
});
$(".div").click(function() { alert(globalMSG); });

Updating an element via ajax: shall I use global variable to keep element's id or it is a bad habit?

On a page I have a list of dates which I want to edit via AJAX.
Example:
<li>January 2015<a data-update_url="/frame_date/22/update/" class="update" id="update_framedate_22" href="javascript:void(0)">Edit</a>
When the user clicks on the Edit link, I catch element id and the edit link.
Than AJAX requests the update form from the server. And now I have to place the form instead of the element with the mentioned id.
In other words, in frame_date_update_show_get I need element's id. In the example below, I keep it in the global variable date_id. But inside me there is a protest: I was always taught that global variables is a bad practice. But in this case I don't know how to get along without the global variable date_id.
Could you give me some piece of advice: is my code acceptable or there is a better way to cope with the problem.
function frame_date_update_show_get(data){
$("#" + date_id).replaceWith(data);
}
function frame_date_update_get_data(){
date_id = this.getAttribute('id')
var cuaghtUrl = this.getAttribute('data-update_url');
$.ajax({
method: 'get',
url: cuaghtUrl,
success: frame_date_update_show_get,
error: fail
});
}
var date_id = ""
Use an anonymous function as success callback function and then call frame_date_update_show_get with an additional date_id parameter:
function frame_date_update_show_get(data, date_id) {
$("#" + date_id).replaceWith(data);
}
function frame_date_update_get_data() {
var date_id = this.getAttribute('id')
var cuaghtUrl = this.getAttribute('data-update_url');
$.ajax({
method: 'get',
url: cuaghtUrl,
success: function(data) {
frame_date_update_show_get(data, date_id);
},
error: fail
});
}
I would use contenteditable combined with AJAX this way:
function dateChange(options){
switch( options.action ) {
case 'update':
if( options.id && options.text && options.updateUrl ) {
$.ajax({
method: 'post',
url: options.updateUrl,
data: {
id: options.id,
html: options.text
},
success: function(response) {
options.element.html( response );
options.element.removeClass('editing');
},
error: function(err) {
console.log( 'request failed: ' + err.text );
}
});
};
break;
default:
console.log( 'action invalid' );
return false;
break;
};
};
var editTimeout = null;
$('li[data-update-url]').on('input', function(e) {
var thisText = $(this);
thisText.addClass('editing');
clearTimeout( editTimeout );
editTimeout = setTimeout(function() {
var updateUrl = thisText.data('updateUrl');
var id = thisText.data('id');
dateChange({
'action': 'update',
'element': thisText,
'id': id,
'updateUrl': updateUrl,
'text': thisText.html()
});
}, 1000);
});
.editing {
color: orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li data-update-url="/echo/html/" data-id="update_framedate_22" contenteditable>January 2015</li>
</ul>
Check how it works on JSFiddle.
This code would be easy to expand for other actions you may need, as delete, add.

jquery iframe load dynamically

I am using following jquery script to load another url after successful ajax request.
$(document).ready(function() {
var $loaded = $("#siteloader").data('loaded');
if($loaded == false){
$("#siteloader").load(function (){
if(ad_id != undefined){
var req_url = base_url+'ajax/saveclick/'+ad_id+'/';
var preloader = $('#preloader');
var reqloader = $('#reqloader');
$.ajax({
url: req_url,
type: 'GET',
beforeSend: function() {
$(preloader).show();
$('#adloading').remove();
},
complete: function() {
$(preloader).hide();
},
success: function(result) {
$(reqloader).html(result);
$("#siteloader").data("loaded", "true");
$("#siteloader").attr("src", base_url+'userpanel/cpa/'+ad_id+'/');
}
});
}
else{
$('#reqloader').html('<span class="text-danger">Invalid Approach!</span>');
}
});
}
});
<iframe src="remote_url" id="siteloader"></iframe>
I don't want to run ajax again after changing src on iframe and i have also tried to stop it by $("#siteloader").data("loaded", "true");
Please suggest me a good solution for this. thanks.
If you only want to execute the "load" handler once
Simply add the line
$("#siteloader").unbind('load');
In the success callback.
If you want the "load" handler to be executed on each src change, you may do something like that :
$(document).ready(function () {
$("#siteloader").load(function () {
// Move the test in the event Handler ...
var $loaded = $("#siteloader").data('loaded');
if ($loaded == false) {
if (ad_id != undefined) {
var req_url = base_url + 'ajax/saveclick/' + ad_id + '/';
var preloader = $('#preloader');
var reqloader = $('#reqloader');
$.ajax({
url: req_url,
type: 'GET',
beforeSend: function () {
$(preloader).show();
$('#adloading').remove();
},
complete: function () {
$(preloader).hide();
},
success: function (result) {
$(reqloader).html(result);
$("#siteloader").data("loaded", "true");
$("#siteloader").attr("src", base_url + 'userpanel/cpa/' + ad_id + '/');
}
});
}
else {
$('#reqloader').html('<span class="text-danger">Invalid Approach!</span>');
}
}
});
});
Maybe your ad_id variable is not well defined / changed ...

Categories

Resources