Fullcalender eventRecieve Function Not Firing Ajax under Firefox - ajax

We have the following script that works fine on all browsers.
However when the same script is placed inside the Fullcalender eventRecieve function (external events drag, drop and re render) the script does not post data to insert_events.php - but this only happens in Firefox- it does post data as expected in both Chrome and Edge. So in summary we have a situation as follows:
Edge, Chrome, FF - script is standalone --> posts data as expected
Edge and Chrome - script is inside eventRecieve --> posts data as
expected
FF script is inside eventRecieve -->fails to post data as expected
Code:
var title = "Job Request";
var description = "nothing";
var start = "2017-08-28";
var url = "google.com";
var propertyid = "WR388GG-8621";
$.post("insert_events.php?propertyid=" + propertyid, {
title: title,
description: description,
start: start,
url: url
},
function(data, status) {
alert("Data: " + data + "\nStatus: " + status);
}
);
We originally thought this issue was down to the Ajax code with FF and
searched high and low for some ideas and spent a day trying to work out what was going on. But actually the problem is only showing up in Firefox and only when the script is triggered by Fullcalendar's eventRecieve function as below.
Code:
eventReceive: function(event) {
var title = "Job Request";
var description = "nothing";
var start = "2017-08-28";
var url = "google.com";
$.post("insert_events.php?propertyid=" + id, {
title: title,
description: description,
start: start,
url: url
},
function(data, status) {
alert("Data: " + data + "\nStatus: " + status);
});
$('#calendar').fullCalendar('rerenderEvents');
window.location = 'new place to go';
},
Any ideas?

Credit goes to A Dyson on this one. It would seem that Firefox alone will trigger the redirect (window.location = 'new place to go';) before the Ajax call is made. The same is not true of Chrome or Edge - which handle the Ajax call first. Please upvote A Dyson's comment which should be the accepted answer. Apologies for dismissing A Dysons correct comment to soon.

Related

Django - Making an Ajax request

Im having a hard time figuring out how to integrate this ajax request into my view. I'm still learning how to integrate django with ajax requests.
My first question would be: Does the ajax request need to have its own dedicated URL?
In my case I am trying to call it on a button to preform a filter(Preforms a query dependent on what is selected in the template). I have implemented this using just django but it needs to make new request everytime the user preforms a filter which I know is not efficient.
I wrote the most basic function using JQuery to make sure the communication is there. Whenever the user changed the option in the select box it would print the value to the console. As you will see below in the view, I would to call the ajax request inside this view function, if this is possible or the correct way of doing it.
JQuery - Updated
$("#temp").change( function(event) {
var filtered = $(this).val();
console.log($(this).val());
$.ajax({
url : "http://127.0.0.1:8000/req/ajax/",
type : "GET",
data : {
'filtered': filtered
},
dataType: 'json',
success: function(data){
console.log(data)
},
error: function(xhr, errmsg, err){
console.log("error")
console.log(error_data)
}
});
Views.py
def pending_action(request):
requisition_status = ['All', 'Created', 'For Assistance', 'Assistance Complete', 'Assistance Rejected']
FA_status = RequisitionStatus.objects.get(status='For Assistance')
current_status = 'All'
status_list = []
all_status = RequisitionStatus.objects.all()
status_list = [status.status for status in all_status]
# This is where I am handling the filtering currently
if request.GET.get('Filter') in status_list:
user_req_lines_incomplete = RequisitionLine.objects.filter(Q(parent_req__username=request.user) & Q(status__status=request.GET.get('Filter')))
current_status = request.GET.get('Filter')
else:
user_req_lines_incomplete = RequisitionLine.objects.filter(parent_req__username=request.user).exclude(status__status='Completed')
user_reqs = Requisition.objects.filter(par_req_line__in=user_req_lines_incomplete).annotate(aggregated_price=Sum('par_req_line__total_price'),
header_status=Max('par_req_line__status__rating'))
return render(request, 'req/pending_action.html', { 'user_reqs':user_reqs,
'user_req_lines_incomplete':user_req_lines_incomplete,
'requisition_status':requisition_status,
'current_status':current_status,
'FA_status':FA_status})
def filter_status(request):
status = request.GET.get('Filter')
data = {
'filtered': RequisitionLine.objects.filter(Q(parent_req__username=request.user) & Q(status__status=status)),
'current_status': status
}
return JsonResponse(data)
Urls.py
path('pending/', views.pending_action, name='pending_action')
First: you have to divide your template to unchangeable part and the part that you want to modify with your filter.
Second: for your goal you can use render_to_string. See the followning link https://docs.djangoproject.com/en/2.1/topics/templates/#usage
code example (views.py):
cont = {
'request': request, #important key-value
'your_models_instances': your_models_instances
}
html = render_to_string('your_filter_template.html', cont)
return_dict = {'html': html}
return JsonResponse(return_dict)
In your js file you need to determine relative url "{% url 'name in yours url file'%}"
And in success you need to add next line:
success: function(data){
$(".filter-block").html(data.html);
}
i hope it will help you! Good luck!

JQuery Ajax function now working

I have wrote an ajax function and it partially works. Doesn't give any errors . but when i add alert to check my values it works completely . It renders the complete thing . Can any one tell me where did i do wrong in here
$.ajax({
type : "POST",
url : "/usermanageajax/",
data : 'key=' + key_value,
success : function (data) {
var element = users.salary[users.salary.length -1];
var hrs = users.hours[users.hours.length -1];
var html = "<span title=\"" + users.name + "\">Name \"" + users.desc(0,50) + "...\" "+ "has " + element + " of "+ hrs + "</span>";
// alert('*');
$('#title').html(html);
chart_s = draw_chart(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
}
});
The justification of this issue is that the alert call blocks the calling of the two next line. Seems that the browser needs some milliseconds to achieve something before performing the two next lines.
Try to call setTimeOut on the two other lines to be called after few milliseconds.
Again, what is the browser you are testing on?
The fact that it works with the alert indicates a race condition.
Try moving your code to a complete handler instead of a success handler. You can also check for success there.

POSTing file information via ajax after upload using PlUpload

I'm using a customized example of plupload, where
one or more files are first uploaded to an Amazon S3 bucket, and
then file info + user-entered data (e.g. description) is POSTed
via ajax to my controller action in a loop.
This controller action then verifies that the file was upload to the S3 bucket and then saves the info into the database, returning a success or failure to the ajax call.
I use the 'UploadComplete' event to check for any upload errors, and if there are none, perform the actual POSTs in a loop.
What I'd like to do is wait until the entire loop has finished processing and then display the confirmation message (all success, all failed, mix of both) accordingly.
Current code:
uploader.bind('UploadComplete', function (up, files) {
var errorsPresent = false;
var errors = '';
// re-enable buttons
$('div.plupload_buttons a').removeClass('disabled');
$.each(uploader.files, function (i, file) {
if (errorDescArray.hasOwnProperty(file.id)) {
errorsPresent = true;
errors += errorDescArray[file.id] + '<br />';
}
else if (file.status = plupload.DONE) {
var jqXhr = $.post('/documents/add', {
'__RequestVerificationToken': $('#__AjaxAntiForgeryForm input[name=__RequestVerificationToken]').val(),
'filename': file.name,
'size': file.size,
'location': $('#' + file.id + '_location').val(),
'description': $('#filedesc_text_' + file.id).text()
}).error(function (response) {
errorsPresent = true;
errors += response.responseText + '<br />';
});
}
});
//
if (errorsPresent) {
$('#uploadErrors').html('<div data-alert="alert" class="alert-message block-message fade in error">×<p>' + errors + '</p></div>');
}
else {
// set confirmation message
var message = files.length + ' file(s) were successfully uploaded.';
// clear file list
$('ul.plupload_filelist').html('');
// remove files from list
uploader.splice();
// hide modal
$('#upload-modal').modal('hide');
// show confirmation
$('#flashMessage').html('<div data-alert="alert" class="alert-message block-message fade in success">×<p>' + message + '</p></div>');
}
});
The above is obviously flawed in that the second half of the snippet doesn't really wait for the POSTs to complete, with the result that the success confirmation is displayed even if POST has an error response.
So my question is this: How do I perform an ajax post in a loop (unless there's a better way) and process the confirmation message after the loop has finished processing?

jQuery AJAX post data gets lost

I'm trying to post data with AJAX and insert it into a database table.
The problem is, half of the data is missing and I don't know why. I have checked all the names of parameters etc. because it seemed I had a typo somewhere (I was missing some characters but I fixed that) but still it won't work.
Even console.log() and alerts give me the full data I want to post but it never arrives, the php outputs empty parameters. When deactivating the JavaScript or removing "return false;" the php script is opened as expected and works perfectly well, no data is lost (as expected).
Maybe I'm really just missing one single character somewhere ...
I also tried escaping (escape()) the strings but it didn't change anything.
Here's the code and some logs/alerts/echos
$("#itemspeichern").click(function(){
setVisible("#item-process");
var itemname = escape($("#itemname").val());
if ($("#itemneu").is(":checked")) {
var itemneu = $("#itemneu").val();
} else {
var itemneu = 0;
}
var itembild = escape($("#itembild").val());
var itemkurzb = escape($("#itemkurzb").val());
var theset = escape($("#theset").val());
console.log("itemname=" + itemname + "&itemneu=" + itemneu + "&itembild=" + itembild + "&itemkurzb=" + itemkurzb + "&theset=" + theset);
$.ajax({
url: "<?php actualPath(); ?>save-admin-action.php",
type: "POST",
data: "itemname=" + itemname + "&itemneu=" + itemneu + "&itembild" + itembild + "&itemkurzb" + itemkurzb + "&theset=" + theset,
success: function(result){
alert("itemname=" + itemname + "&itemneu=" + itemneu + "&itembild=" + itembild + "&itemkurzb=" + itemkurzb + "&theset=" + theset);
document.getElementById("item-process").innerHTML = result;
}
});
return false;
});
What this does is:
- output the data of all fields on the console
- showing all the data in the alert
but when it is done saving it the database is missing the values of itembild and itemkurzb. Getting the query as response from the php file showed that indeed the parameters are empty for those fields. Here's what I did in php (I shortened it a bit, don't comment on SQL injection and stuff :P)
$ergebnis = mysql_query("INSERT INTO mk7_items(id, de, neu, kurzbeschreibung, bild) VALUES(DEFAULT, '".$_POST["itemname"]."', ".$_POST["itemneu"].", '".$_POST["itemkurzb"]."', '".$_POST["itembild"]."')");
the last two fields are empty when I get the response and nothing is saved into the db.
As I said, setting JS to OFF and running it on php only works perfectly well.
Any ideas? Any stupid mistakes I did there?
You're missing a couple = in your data, it should be this:
data: "itemname=" + itemname + "&itemneu=" + itemneu + "&itembild=" + itembild + "&itemkurzb=" + itemkurzb + "&theset=" + theset,
Or better, stop using escape (which is deprecated in favor or encodeURIComponent due to escape not handling non-ASCII data very well) and use an object for your data parameter:
var itemname = $("#itemname").val();
//...
$.ajax({
url: "<?php actualPath(); ?>save-admin-action.php",
type: "POST",
data: {
itemname: itemname,
itemneu: itemneu,
itembild: itembild,
itemkurzb: itemkurzb,
theset: theset
},
//...
});
That way $.ajax will take care of converting your data to the proper POST (or GET or ...) format and you don't have to worry about the details.
try this in your $.ajax call instead of your selfmade query string:
data: {
itemname: itemname,
itemneu: itemneu,
itembild: itembild,
itemkurzb: itemkurzb,
theset: theset
}
By passing the data as Object, jQuery will escape the values for you :)
Edit:
You could also serialize the complete form like this:
data: $('#yourform').serialize()
if you use special characters in posted items, you use this function before every vars...
sample :
var txt = encodeURIComponent(document.getElementById('txt1').value);

AJax Testing - Add a delay

I'm trying to run some tests on some Ajax code we have written, now obviously when tested locally it runs very fast and is great. I need to enforce a delay of 3 seconds so that I can see that the loader is being displayed and the user experiance is good enough.
I have tried the following but recieve the error "Useless settimeout" any other suggestions to achieve this? Any browser plugins?
$('#formAddPost').submit(function() {
//Load the values and check them
var title = $(this).find('#Title');
var description = $(this).find('#Description');
var catId = $(this).find('#Categories');
if (ValidateField(title) == false || ValidateField(description) == false) {
$('.error-message').show();
return false;
}
$('.error-message').hide();
//Show the loading icon
$('.add-post').hide();
$('.add-post-loader').show();
//Temp for testing - allows the showing to the loader icon
setTimeout(MakeAJAXCall(title.val(), catId.val(), description.val()), 1500);
return false;
});
function MakeAJAXCall(title, catId, description) {
$.ajax({
url: "/Message/CreatePost/",
cache: false,
type: "POST",
data: ("title=" + title + "&description=" + description + "&categories=" + catId + "&ajax=1?"),
dataType: "html",
success: function(msg) {
$('#TableMessageList').replaceWith(msg);
$('.add-post-loader').hide();
$('.add-post').show();
}
});
}
As you're testing your page for a delay in the server response, can you put a delay in the server side code instead of client side?
You might be able to do that using fiddler.
The examples scripts include some samples that pause the response.
Would this tool from jsFiddle.net be helpful?
Echo Javascript file and XHR requests
http://doc.jsfiddle.net/use/echo.html

Resources