I've read and re-read every first-page Google result on JQuery/AJAX callbacks using every permutation of terms I can think of, and no re-write I've tried for the code below is successful.
I simply need to construct a callback for this function—which is part of a larger self-calling JQuery function—so that the 'message' variable holds the results of the integrity_check.php routine before proceding to the evaluation routine of 'message' at the end.
(Yes, this is yet another attempt to make JQuery synchronous, and I understand that callbacks are the answer, but I can't find it.) May success and happiness befall you if you can help me with this:
// If the integrity check passed, message will be empty.
// If the integrity check fails, message will hold text for an alert box.
var message;
$.get('integrity_check.php', { add_new_variable: $('#new_variable').val() }, function(data) {
if (data != 0) {
message = data;
}
});
[...some other code follows that may or may not set 'message' variable to a text message for alert box, so the following code must stand independently:]
if (message != '') {
alert(message);
} else {
[...proceed with using new_variable in HTML...]
}
UPDATE
The suggestion by Guest271314 pointed in the right direction, although I had to make modifications to make it work; see CAPS commentary in code solution that follows:
var request = $.get('integrity_check.php', { add_new_variable: $('#new_variable').val() }, function(data) {
if (data != 0) {
message = data;
}
return message;
});
// HERE I HAD TO SAVE THIS VALUE TO A NEW VARIABLE;
// $('#new_variable').val(); WAS NOT ACCESSIBLE OTHERWISE IN THE ROUTINE THAT FOLLOWED:
var nv = $('#new_variable').val();
// HERE IT WAS IRRELEVANT WHAT ARGUMENT WENT INTO function(),
// EXCEPT IT COULD *NOT* BE message; YOU HAD SUGGESTED msg, WHICH WAS IMMATERIAL, IT TURNED OUT
request.then(function() {
// HERE I *HAD* TO USE message, NOT THE GENERIC msg THAT YOU HAD PASSED INTO THE FUNCTION:
if (message != '') {
alert(message);
} else {
// THE ORIGINAL FORM HERE WOULDN'T WORK, AS $('#new_variable').val() WAS INACCESSIBLE IN THE FUNCTION:
//var newKeyword = '<label><input name="new_variable[]" type="checkbox" tabindex="-1" value="' + $('#new_variable').val() + '" checked /> ' + $('#new_variable').val() + '</label>';
// THIS, HOWEVER, WORKED...USING nv IN PLACE OF $('#new_variable').val();
var newVariable = '<label><input name="new_variable[]" type="checkbox" tabindex="-1" value="' + nv + '" checked /> ' + nv + '</label>';
$('#checkboxes').append(newVariable);
}
});
I'm grateful to guest271314 for what s/he posted, although I'm unclear on why I had to make the changes that I did in order for the code to work. Elucidation, anyone?
Try utilizing deferred.then()
// If the integrity check passed, message will be empty.
// If the integrity check fails, message will hold text for an alert box.
var message;
var request = $.get('integrity_check.php'
, { add_new_variable: $('#new_variable').val() }
, function(data) {
if (data != 0) {
message = data;
}
return message
});
/*
[...some other code follows that may or may not set 'message' variable to a text message for alert box, so the following code must stand independently:]
*/
request.then(function(msg) {
// `msg`: `message`
if (msg != '') {
alert(msg);
} else {
// [...proceed with using new_variable in HTML...]
}
// return msg
}, function err(jqxhr, textStaus, errorThrown) {
console.log(errorThrown)
});
Related
Something's not working this morning and I'm pretty sure it's my brain. I've got a form that tracks changes to a field under certain conditions:
-If the status = Draft, do nothing.
-If the status = Approved, prompt user to ask if they are sure they want to make the change.
-If they click 'OK', it should call the process that records the change.
-If they click 'Cancel' it should do nothing.
-If the status is anything other than draft or Approved, don't prompt but call the process that records the change.
I had the code recording changes in non-draft status, but after I added the ==true to the end of the confirm statement, everything stopped working.
var stat = $('#status').text();
var parms = just a bunch of parameters i'm passing to the url below;
if (stat=='(Draft)'){
//do nothing
}
else if (stat !== 'Approved' && stat!== '(Draft)'){
var url = webDbName + '/(CreateOTChangeRecordOnChange)?OpenAgent' + parms;
$.get(url, function(data) {
$('#tableBodyChanges').html(data);
});
}
}
else if (stat == 'Approved' && confirm('You are changing the hours on a request that has already been approved. This will send a notification to the department director. Proceed?')==true) {
var url = webDbName + '/(CreateOTChangeRecordOnChange)?OpenAgent' + parms;
$.get(url, function(data) {
$('#tableBodyChanges').html(data);
});
} else {
//do nothing });
}
It is working, but you could just ommit the == true because it already is a "if-able boolean"
if(confirm("test?")){
console.log("confirmed1");
}else {
console.log("notconfirmed1");
}
<!-- or the other way arround -->
if(!confirm("test?")){
console.log("notconfirmed2");
}else {
console.log("confirmed2");
}
<!-- it should also work the way you posted as well -->
if("foo" == "foo" && confirm("test?") == true){
console.log("confirmed3");
}else {
console.log("notconfirmed3");
}
I am working on some legacy code which is using Asp.net and ajax where we do one functionality to upload a pdf. To upload file our legacy code uses AjaxUpload, but I observed some weird behavior of AjaxUpload where onComplete event is getting called before actual file got uploaded by server side code because of this though the file got uploaded successfully still user gets an error message on screen saying upload failed.
And here the most weird thins is that same code was working fine till last week.
Code:
initFileUpload: function () {
debugger;
new AjaxUpload('aj-assetfile', {
action: '/Util/FileUploadHandler.ashx?type=asset&signup=False&oldfile=' + assetObj.AssetPath + '&as=' + assetObj.AssetID,
//action: ML.Assets.handlerPath + '?action=uploadfile',
name: 'AccountSignupUploadContent',
onSubmit: function (file, ext) {
ML.Assets.isUploading = true;
ML.Assets.toggleAsfMask(true);
// change button text, when user selects file
$asffile.val('Uploading');
$astfileerror.hide();
// If you want to allow uploading only 1 file at time,
// you can disable upload button
this.disable();
// Uploding -> Uploading. -> Uploading...
ML.Assets.interval = window.setInterval(function () {
var text = $asffile.val();
if (text.length < 13) {
$asffile.val(text + '.');
} else {
$asffile.val('Uploading');
}
}, 200);
//if url field block is visible
if ($asseturlbkl.is(':visible')) {
$asfurl.val(''); //reset values of url
$asfurl.removeClass('requiref error'); //remove require field class
$asfurlerror.hide(); //hide errors
}
},
onComplete: function (file, responseJSON) {
debugger;
ML.Assets.toggleAsfMask(false);
ML.Assets.isUploading = false;
window.clearInterval(ML.Assets.interval);
this.enable();
var success = false;
var responseMsg = '';
try {
var response = JSON.parse(responseJSON);
if (response.status == 'success') { //(response.getElementsByTagName('status')[0].textContent == 'success') {
success = true;
} else {
success = false;
responseMsg = ': ' + response.message;
}
} catch (e) {
success = false;
}
if (success) {
assetObj.AssetMimeType = response.mimetype;
$asffile.val(response.path);
$asffile.valid(); //clear errors
ML.Assets.madeChanges();
if (ML.Assets.saveAfterUpload) { //if user submitted form while uploading
ML.Assets.saveAsset(); //run the save callback
}
} else { //error
assetObj.AssetMimeType = "";
$asffile.val('');
$astfileerror.show().text('Upload failed' + responseMsg);
//if url field block is visible and type is not free offer.
if ($asseturlbkl.is(':visible') && this.type !== undefined && assetObj.AssetType != this.type.FREEOFFER) {
$asfurl.addClass('requiref'); //remove require field class
}
ML.Assets.hideLoader();
}
}
});
}
I was facing the same issue but I fixed it with some minor change in plugin.
When “iframeSrc” is set to “javascript:false” on https or http pages, Chrome now seems to cancel the request. Changing this to “about:blank” seems to resolve the issue.
Old Code:
var iframe = toElement('<iframe src="javascript:false;" name="' + id + '" />');
New Code with chagnes:
var iframe = toElement('<iframe src="about:blank;" name="' + id + '" />');
After changing the code it's working fine. I hope it will work for you as well. :)
Reference (For more details): https://www.infomazeelite.com/ajax-file-upload-is-not-working-in-the-latest-chrome-version-83-0-4103-61-official-build-64-bit/
I have installed in my project django-contib-comments and I have an HTML that displays the list of comments and also displays the form to enter a new one.
I now want to use Ajax to submit the form without a page refresh and on success to add the submitted comment to the list.
I have done most of the work, but I'm sure there must be an easier way to achieve this.
my question is if there is a way for me to render a Django HTML tag within a javascript something like this:
document.getElementById("comments").innerHTML = {% render_comment_list for obj %}
so far this is the code I have done:
1) I don't want to change anything in the django-contrib-comments project (i am avoiding to override methods.
2) I used the standard tags in django-contrib-comments to render a list of comments.
{% render_comment_list for obj %}
3) Created a JavaScript that handles the submit of the form and then creates a new entry in the list.
function submit_comments(event) {
event.stopPropagation();
$.ajax({
type: $('#comment_form').attr('method'),
url: $('#comment_form').attr('action'),
data: $('#comment_form').serialize(),
cache: false,
dataType: "html",
success: function (html, textStatus) {
var comment_count_btn = document.getElementById('comment-text-vertical-btn');
if (comment_count_btn != null) {
if (!isNaN(parseInt(comment_count_btn.innerHTML))) {
comment_count_btn.innerHTML = parseInt(comment_count_btn.innerHTML) + 1 + " Comments";
}
}
var comment_count_head = document.getElementById('kapua-comments-header');
if (comment_count_head != null) {
if (!isNaN(parseInt(comment_count_head.innerHTML))) {
comment_count_head.innerHTML = parseInt(comment_count_head.innerHTML) + 1 + " Comments:";
}
}
if (document.getElementById("comments") != null){
submitted_timestamp = getQueryParameter("timestamp", this.data);
submitted_date = new Date();
if (submitted_timestamp == null) {
submitted_date = new Date(submitted_timestamp);
}
submitted_comment = getQueryParameter("comment", this.data);
if (submitted_comment == null) {
submitted_comment = "No value entered"
}
html_comment = "<div class=\"right-aligned\"><div class=\"comment-date\">" + submitted_date + " - " + "</div>" + submitted_comment + "</div><br><br>";
current_html = document.getElementById("comments").innerHTML;
document.getElementById("comments").innerHTML = html_comment + current_html;
}
if (document.getElementById("comment_form") != null){
document.getElementById("comment_form").reset();
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
$('#comment_form').replaceWith('Your comment was unable to be posted at this time. We apologise for the inconvenience.');
}
});
return false;
};
Thanks in Advance
Yes there is way in django, You can use [escape][1] to render HTML tag. Here is an simple example -
from django.utils.html import escape
def example(request):
return "%s<div><i>%s</i></div>" % (escape(text), escape(other_text)
For more explanation you can refer to documentation.
https://docs.djangoproject.com/en/2.1/ref/utils/#django.utils.html.escape
Still have any doubts comment it out.
Here's the rundown. Users can view a razor page both anonymously and logged in. If they are logged in, they get certain features. In my controller, I have a boolean isAnonymous which I set to true or false depending on if there's a signed in user or not. I pass isAnonymous to my view model which gets sent to the razor page.
In the razor page, I have a javascript script tag which needs to retrieve that boolean value and, if isAnonymous is false (meaning someone is signed in), fire off one of two ajax calls to the server.
The first thing I do in my script tag is get the isAnonymous value and convert it to a JavaScript boolean with this:
var isAnonymous = #Json.Encode(Model.IsAnonymous);
after console logging, this appears to return correctly.
Then i put in my if statement. The summary here is if the user is not logged in, none of these functions nested inside the if statement should fire, because they take an ApplicationUser as part of the model. If there is no signed in user, Model.User is null and throws a Null Reference Exception. I thought putting my ajax calls inside the if statement would guard against the exception, but the the logic seems to be blowing right through the if (isAnonymous == false) and hitting those functions despite the logic. Any thoughts as to why this is happening? When isAnonymous is true, I can't have the functions fire.
if (isAnonymous == false) {
if ($('.bookmark-btn').hasClass('bookmark-story-btn')) {
addBookmark();
} else {
removeBookmark();
}
function addBookmark() {
//bookmark a story btn click event
$('.bookmark-story-btn').on('click', function () {
var storyid;
//the storyid should come as a string -
//try to parse it as an int for the controller
if (!isNaN($(this).attr('storyid'))) {
storyid = parseInt($(this).attr('storyid'))
//verify successful conversion from string to int before ajax call
if (typeof (storyid) == 'number') {
var userid = $(this).attr('userId')
var newBookmark = {
UserId: userid,
StoryId: storyid,
};
$.ajax({
url: "/api/bookmark/new",
method: "POST",
data: newBookmark,
success: function (data) {
//remove the save bookmark btn and dynamically add
//the remove bookmark btn so
//the page doesn't require a refresh
$('.bookmark-story-btn').remove();
$('.bookmark-btn-group').append("<button bookmarkId='"
+ data.Id
+ "' userId=#Model.User.Id storyId=#Model.StoryId"
+" class='btn remove-bookmark-btn bookmark-btn'>"
+"<i class='fas fa-2x fa-bookmark'></i></button>")
removeBookmark();
},
error: function (error) {
$('.page-alert').css('visibility', 'visible')
.html("Whoops. Something went wrong."
+" Adding the bookmark failed.")
//automatically close the alert-danger div
//after 2 seconds
setTimeout(function () {
$('.page-alert').css('visibility', 'hidden')
}, 3000);
}
});
}
}
});
}
function removeBookmark() {
//remove a bookmark click event
$('.remove-bookmark-btn').on('click', function () {
if (!isNaN($(this).attr('bookmarkid'))) {
bookmarkid = parseInt($(this).attr('bookmarkid'))
//verify successful conversion from string to int before ajax call
if (typeof (bookmarkid) == 'number') {
//call the ajax
$.ajax({
url: "/api/bookmark/" + bookmarkid,
method: "DELETE",
success: function (data) {
//show-hide the appropriate icons
$('.remove-bookmark-btn').remove();
$('.bookmark-btn-group').append("<button userId=#Model.User.Id"
+" storyId=#Model.StoryId class='btn bookmark-story-btn"
+" bookmark-btn'><i class='far fa-2x fa-bookmark'>"
+"</i></button>")
addBookmark();
},
error: function (error) {
$('.page-alert').css('visibility', 'visible')
.html("Whoops. Something went wrong here."
+" Removing the bookmark didn't work.")
//automatically close the alert-danger div
//after 2 seconds
setTimeout(function () {
$('.page-alert').css('visibility', 'hidden')
}, 3000);
}
})
}
}
})
}
}
You can use Request.IsAuthenticated in both the Razor view:
#if(Request.IsAuthenticated)
{
<script>
' your authenticated client side script here
</script>
}
And then check again server side when posting in your controller for example:
public ActionResult Index()
{
if(Request.IsAuthenticated)
{
//server logic here
}
}
Better still if you decorate the method with the AuthoriseAttribute the user will get an 403 Unauthorized.
You can then do something similar server side for the UserId:
[Authorize]
public ActionResult Index()
{
var userId = User.Identity.Name;
}
Then you don't even need to pass the UserId about. This is all based on using the common Identity practices:
https://learn.microsoft.com/en-us/aspnet/identity/overview/getting-started/introduction-to-aspnet-identity
I'm sending a value to another page. If there is results from a sql query I want to display in an overlay. If there is no results do not display the overlay.
What's happening is that the overlay pops up whether there are results or not. I'm new to this style of version of posting with jquery. I'm used to 'spelling it out' via $.ajax({}); or plain php.
This is my jquery:
$(document).ready(function ()
{
$("#signup").overlay();
$('#status').change(function()
{
whoclock=$('#associate').val();
$.post("ckrd_messsys.php",{asso:whoclock},function(result)
{
if(result)
{
$("#signup").overlay().load();
$("#signup").overlay({mask: '#999', fixed: false,load:true});
$("#spellout").html(result);
}
});
});
$("#confirm").click(function()
{
$.post("ckrd_messsys.php",{asso:whoclock,confirmread:"Y"},function(result)
{
$("#signup").overlay().close();
});
});
});
This is my php:
$asso = $_REQUEST['asso'];
$confirmread = $_REQUEST['confirmread'];
$getmess = mysql_fetch_array(mysql_query("SELECT `file` FROM `foo` WHERE `empl`='".$asso."' ORDER BY `id` ASC",$con));
if($asso != "")
{
if(file_exists("message/".$getmess[0].".txt"))
{
$txtfile = fopen("message/".$getmess[0].".txt", "r") or exit("Unable to open file!");
$readIT=fgets($txtfile);
echo $readIT;
fclose($txtfile);
}
}
If there is no txt file I do not want the overlay to load. How do I tell the jquery there is no 'file' or 'result' and not to load?? (Sorry for all the edits....just seems I'm not getting the answers/help I'm after.)
Can I just simply add to my php page:
else
{
echo "NOTHING";
}
Then change my jquery to something like:
if(result != "NOTHING")
{
....
}
I've tried this and it didn't work.
I got some observations:
1. I never used before that overlay plugin but seems like the load property fires the overlay if true so there is no need to put at first $(selector).overlay() and later invoke $(selector).overlay().load() It doesn't make sense if you specify the property at first.
2. I think will be good to check the callback response object (result). Sometimes, when implementing a rest or something else, you can return JSON, XML, string, html, etc but in general it is supposed that result is a javascript object, something similar to this:
Object: {} (if empty) or Object: {name: 'Oscar'} (with data)
So, I think what you are checking when doing your conditional if(result) { ... } is to determine if the variable is false or undefined but you are not considering if its empty or not AND! when evaluating an Object: {} as your result variable, it will pass the condition as "true".
What you can do is using the $.isEmptyObject function from jQuery when evaluating your Object as the following code I've implemented for testing.
Check this out.
Live demo: http://jsfiddle.net/oscarj24/34m2R/5/
HTML:
<div id="signup">
<input class="btn" type="button" value="Make ajax call (no results)"/>
<input class="btn" data-type="wr" type="button" value="Make ajax call (with results)"/>
</div>
jQuery:
$(document).ready(function() {
/* In this case, this is the function that replaces
* your on 'change' event handler
*/
$('.btn').on('click', function() {
var type = $(this).data('type');
makeAjaxCall(type);
});
});
/* This makes the ajax calls.
* #param {type} if 'wr' will add some extra
* data to the response obj.
*/
function makeAjaxCall(type) {
$.post('/echo/json', function(data) {
if(type === 'wr') { // wr: simulate data with results
data.name = 'Oscar';
}
if(!$.isEmptyObject(data)) {
makeOverlay($('#signup'), data);
}
}).fail(function(r) { // ajax call failed (you can test this by replacing URL)
var code = r.status;
var error = r.statusText;
alert('Error: ' + code + ', ' + error);
});
}
/* This will make the overlay with
* predefined cfg.
* #param {elem} affected element
* #param {data} callback response object
*/
function makeOverlay(elem, data) {
var cfg = {
mask: '#ccc',
load: true
};
elem.overlay(cfg);
elem.html('<b>Hello ' + data.name + '!</b>');
}
You probably always have a result object from the response, just with different properties.
I usually always return the json property success=true. Then I check:
if(response.success===true) { }
Why not add debugger; in the javascript and check the result object in your browser?