When document ready i have set
$.ajaxSetup({
"error": function (XMLHttpRequest, textStatus, errorThrown) {
if(XMLHttpRequest.status == 403) {
display_modal( 'Please login to continue.', 'Session in closed.');
//XMLHttpRequest.abort();
}
}
});
to prevent ajax request from unauthenticated users.
but in a specific view, when a POST/GET request is made I have
var posting = $.post(
post_url,
$("#" + form).serialize(),
function(data) {
packet = data;
},
'json'
);
posting.done(function() {
form_post_response_function(e, packet);
});
posting.fail(function() {
var packet = {};
packet.data = {};
packet.data.type = "Ajax Post Fail";
packet.status = -200;
packet.statusMessage = "ERROR";
form_post_response_function(e, packet);
});
I was expecting to posting.fail(function() { and getting.fail(function() { not be called. But they are, so all the flow goes and it ends with another modal overlaping the 403 message.
How can I avoid this without raw $.ajax ? How stop JQuery flow at the error catch?
FINAL code
posting.fail(function(jqXHR, textStatus, errorThrown) {
if(jqXHR.status != 403) {
var packet = {};
packet.data = {};
packet.data.type = "Ajax Post Fail";
packet.status = -200;
packet.statusMessage = "ERROR";
form_post_response_function(e, packet);
} else {
// event also can be accessed here
$(get_target(e)).button('reset');
}
});
and it stop gently. looks good.
Throw an exception to stop the execution of further code.
For example: throw "stop execution here";
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/throw
See que Question for all the details
This is the final code
posting.fail(function(jqXHR, textStatus, errorThrown) {
if(jqXHR.status != 403) {
var packet = {};
packet.data = {};
packet.data.type = "Ajax Post Fail";
packet.status = -200;
packet.statusMessage = "ERROR";
form_post_response_function(e, packet);
} else {
// event also can be accessed here
$(get_target(e)).button('reset');
}
});
Related
I perform an edit to ensure against duplicate emails by making an ajax call and supplying a callback. If a duplicate exists, I want to return false from submit event. Is there an elegant way to achieve this without setting async=false? What I tried (see emailCallback) is not working.
submit event
EDIT (included the rest of the submit handler).
$("#form-accounts").on("submit", function (e) {
e.preventDefault();
if (!$(this).get(0).checkValidity()) return false;
if (!customValidation(true, false)) return;
checkDupEmail(emailCallback);
function emailCallback(result) {
if (result) return (function () { return false } ());
}
if ($("#submit").text() == "Create Account") {
var formData = $("#form-accounts").serialize().replace("''", "'");
ajax('post', 'php/accounts.php', formData + "&action=create-account", createSuccess);
function createSuccess(result) {
if (isNaN(result)) {
showMessage(0, result);
return;
}
localStorage.setItem("account-id", result);
debugger
setUsertype($("input[name=user-type]:checked").val());
showMessage(1, "Account Created");
};
return
}
var rString = randomString(32, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
function randomString(length, chars) {
var result = '';
for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
return result;
};
var anRandom = randomString(14, rString);
$("#code").val(anRandom);
console.log("v-code=" + anRandom);
$("#submit").css({ 'display': 'none' });
$("#verify").css({ 'display': 'block' });
var subject = "Writer's Tryst Verification Code"
$("#subject").val(subject);
var msg = "This mail is intended for the person who requested verification of email ownership at Writers-Tryst (" + getWriterTrystURL() + ").\n\n" + "Double click on the code below and then copy it. Return to our website and and paste the code.\n\nYour verification code: \n\n" + anRandom;
$("#msg").val(msg);
var formData = $("#form-accounts").serialize().replace("''", "'");
ajax('post', 'php/sendmail.php', formData, successMail, "create-account error: ");
function successMail(result) {
$("#ver-email-msg").val("An email has been sent to you. Double-click the verification code then copy and paste it below.").css({ 'display': 'block' });
}
});
function checkDupEmail(callback) {
var data = {};
data.action = "validate-email";
data.email = $("#email").val();
ajax('post', 'php/accounts.php', data, emailSuccess);
function emailSuccess(result) {
if (parseInt(result) > 0) {
showMessage(0, "The email address is in use. Please supply another or login instead of creating a new account.")
callback(true);
} else callback(false);
}
}
Instead of passing a callback, why don't you just submit the form when your Ajax call completes successfully?
$("#form-accounts").on("submit", function (e) {
// Always cancel the submit initially so the form is not submitted until after the Ajax call is complete
e.preventDefault();
...
checkDupEmail(this);
...
});
function checkDupEmail(form) {
var data = {};
data.action = "validate-email";
data.email = $("#email").val();
ajax('post', 'php/accounts.php', data, function(result) {
if (parseInt(result) > 0) {
showMessage(0, "The email address is in use. Please supply another or login instead of creating a new account.")
} else {
form.submit();
}
}
}
A better approach than that would be to submit your form using Ajax. That would eliminate the need for two calls to the server.
I am using Spring MVC, Following is a method which will take either String or Input Stream from the Request and convert into PDF and write the PDF to the respose.
public void generatePDF(RequestDTO requestUIDTO, Map<String, Object> responseMap,
HttpServletRequest request, HttpSession session, HttpServletResponse response) {
Document document = new Document();
PdfWriter writer;
try {
writer = PdfWriter.getInstance(document, response.getOutputStream());
document.open();
//Here I need to get the HTML file as String or InputStream from the request.
//For now i am getting InputStream, It may be string
InputStream in = request.getInputStream();
XMLWorkerHelper.getInstance().parseXHtml(writer, document, in);
document.close();
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Now the problem is, I don't know how to send the current rendered page as HTML to the server, I tried the following Java script but it is not working, the request itself is not going to the server May be because i am sending a huge file as request parameter.
function downloadLoanForm(){
var params = {};
params = {
htmlContent : "htmlContent"
}
handleRequest(this, params, 'generatePDF.htm', '');
}
$(document).ready(function(){
var htmlContent = $('#mainFormId').html();
$('#htmlContent').val(htmlContent);
});
My Question is this, Please let me know a way to send the current rendered HTML code to the Server as either a String (or) Stream.
Here is the Java script code for handleRequest() function,
function handleRequest(obj, params, request_url, replacement_element_id,
error_redirection, function_call_after_response) {
//check if there is any value present for the request url
if(!request_url)
{
alert('<spring:message code="JS_MSG_PROVIDE_URL_FOR_REQUEST" text=""/>');
return false;
}
//check if the url is an external url
if(isExternal(request_url) === true)
{
alert('<spring:message code="JS_MSG_REQUEST_CANNOT_SENT_TO_EXTERNAL_LINK" text=""/>');
return false;
}
//global variable for making the decision on the page redirect after the error from the server - default value is false
error_redirection = error_redirection || false;
//variable containing the replacement element id which will be used to place the content after the response from the server
replacement_element_id = replacement_element_id || false;
//variable to decide whether some manipulation has to be done on the response data from the server
// the response data is being sent to this function along with the replacement element id
function_call_after_response = function_call_after_response || '';
//alert(function_call_after_response+'-here');
//set the replacement element's html values to to be empty before the request is being made so as to ensure that user does not go forward without getting the correct result
if(replacement_element_id)
{
$('#'+replacement_element_id).html("");
}
//var serializedData = Array();
var counter = 0;
//SETTING THE REQUIRED ELEMENTS VALUES TO AN JSON OBJECT FOR SENDING TO THE SERVER - the elements required for the post is passed as an array in the arguments
var serializedData = {};
$.each(params, function(key, field) {
if($("#"+key).length > 0) {
//field = escapeHtml(field);
var value = $("#"+key).val();
/*if($('input[name="'+field+'"]').length > 0)
{
value = $('input[name="'+field+'"]').val();
}
else if($('select[name="'+field+'"]').length > 0)
{
value = $('select[name="'+field+'"]').val();
}
else if($('textarea[name="'+field+'"]').length > 0)
{
value = $('textarea[name="'+field+'"]').val();
}*/
value = escapeHtml(value);
if(value != "")
{
counter++;
}
//serializedData.field = value;
serializedData[field] = value;
/*
if(counter == 0)
{
serializedData = field+'='+value;
}
else
{
serializedData += '&'+field+'='+value;
}
counter++;
*/
}
});
if(counter == 0)
{
return false;
}
serializedData.csrfToken = $('form > input[name=csrfToken]').val();
//alert($('form > input[name=csrfToken]').val());
if(isExternal(request_url) === false)
{
$('input[name="'+$(obj).attr('name')+'"]').css('float', 'left');
$.blockUI({ message: "<h3><img src='images/processing.gif' id='processing_plz_wait' alt='Processing...' title='Processing...' border='0' class='processing_img' /><br/><spring:message code="JS_MSG_PLEASE_WAIT" text=""/></h3>" });
$(".blockOverlay").show();
$(".blockOverlay").css("opacity", "0.6");
$(".blockMsg").show();
$(".blockMsg").css("opacity", "1");
//setTimeout(function() {
$.ajax({
type: "POST",
url: request_url,
data: serializedData,
success: function(data, status, xhr) {
if(data) {
//check for some strings to validate session time out - TODO need proper validation check
if(data.contains("<html>") && data.contains("<head>")){
document.location.href = 'logout.htm';
} else {
if(replacement_element_id === false) {
alert('<spring:message code="JS_MSG_OPERATION_PERFORMED_SUCCESSFULLY" text=""/>');
return false;
}
else {
//set the response from the server to the form display element
$('#'+replacement_element_id).html(data);
setTokenValFrmAjaxResp();
$('#'+replacement_element_id).find("form ").append('<input type="hidden" value="'+$('#csrfToken').val()+'" name="csrfToken">');
$('form > input[name=csrfToken]').val($('#csrfToken').val());
if(function_call_after_response != "")
{
eval(function_call_after_response);
}
return false;
}
}
}
},
//ERROR HANDLING AS PER THE RESPONSE FROM THE SERVER - TO DO (some extra layer of error handling to be done)
error: function(jqXHR, exception) {
if (jqXHR.status === 0) {
alert('<spring:message code="JS_MSG_NOT_ABLE_TO_CONNECT_VERIFY_NETWORK" text=""/>');
} else if (jqXHR.status == 404) {
alert('<spring:message code="JS_MSG_REQUEST_PAGE_NOT_FOUND" text=""/>');
} else if (jqXHR.status == 500) {
alert('<spring:message code="JS_MSG_INTERNAL_SERVER_ERROR" text=""/>');
} else if (exception === 'parsererror') {
alert('<spring:message code="JS_MSG_REQUESTED_DATA_PARSE_FAILED" text=""/>');
} else if (exception === 'timeout') {
alert('<spring:message code="JS_MSG_TOME_OUT_ERROR" text=""/>');
} else if (exception === 'abort') {
alert('<spring:message code="JS_MSG_AJAX_REQUEST_ABORTED" text=""/>');
} else {
alert('<spring:message code="JS_MSG_UNCAUGHT_ERROR" text=""/>' + jqXHR.responseText);
if(error_redirection === true)
{
//redirect to the corresponding error page
document.location.href = '';
}
}
setTokenValFrmAjaxResp();
return false;
}
});
//}, 100);
}
}
I have chat on Socket.IO, MySQL, PHP. Everything is working good, but i need download and diplay messages history when you update the page.
php code:
<script>var USER = {"id":"<?php echo $_SESSION['steamid']?>","login":"<?php echo $_SESSION['personaname']?>","image":"<?php echo $_SESSION['avatarmedium']?>","hash":"<?php echo md5($_SESSION['steamid']) ?>"};</script>
js site code:
var messageTpl = _.template($("#chat-message").html());
function sendMessage(text) {
socket.emit('message', {user: USER, message: text});
}
var lastUser = null;
function addMessage(data, checkLast) {
var a = $("#chatScroll")[0];
var isScrollDown = (a.offsetHeight + a.scrollTop) == a.scrollHeight;
if (checkLast && lastUser && lastUser.id == data.user.id) {
$('.chatMessage').last().find('.body').append('<br/>' + _.escape(data.message))
}
else {
console.log(data);
data.user.url = 'http://steamcommunity.com/profiles/' + data.user.id;
data.user.image = 'https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/' + _.escape(data.user.image).replace('_medium', '');
var html = messageTpl(data);
$('#messages').append(html);
if ($('.chatMessage').length > 100) {
$('.chatMessage').eq(0).remove();
}
}
lastUser = data.user;
if (isScrollDown) a.scrollTop = a.scrollHeight;
$("#chatScroll").perfectScrollbar();
}
socket.on('online', function(data) {
$('#online').text(data.online);
});
socket.on('chat-message', function(data) {
addMessage(data, true);
});
socket.on('chat-history', _.once(function(data) {
$("#chatScroll").perfectScrollbar();
if (data) _.each(data, addMessage);
}));
function addMessage works good, but with socket.on('chat-history') i got error
Uncaught TypeError: Cannot read property 'id' of undefined
js server code:
connection.query('SELECT * FROM cs_chat ORDER BY id DESC LIMIT 50', function(error, rows) {
if(!error) {
var user = [];
rows.forEach(function (data) {
user.push(data);
});
console.log(user);
socket.emit('chat-history', {user: JSON.stringify(user)});
} else {
console.log(error.message);
}
});
when you refresh the page - all last messages lost
console.log server js rows.forEach below.
[{"id":668,"message_text":"3qwe","user_steamid":"76561198056267433","user_personaname":"#Saundefined","date":"2015-10-06T15:22:15.000Z","user_avatarmedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/c2/c2ff9427410ea1121363de0e651f6d4e8c485ab6_medium.jpg"},{"id":667,"message_text":"12312","user_steamid":"76561198056267433","user_personaname":"#Saundefined","date":"2015-10-06T15:22:14.000Z","user_avatarmedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/c2/c2ff9427410ea1121363de0e651f6d4e8c485ab6_medium.jpg"},{"id":666,"message_text":"213123","user_steamid":"76561198056267433","user_personaname":"#Saundefined","date":"2015-10-06T15:22:14.000Z","user_avatarmedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/c2/c2ff9427410ea1121363de0e651f6d4e8c485ab6_medium.jpg"},{"id":665,"message_text":"cvb","user_steamid":"76561198056267433","user_personaname":"#Saundefined","date":"2015-10-06T15:22:12.000Z","user_avatarmedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/c2/c2ff9427410ea1121363de0e651f6d4e8c485ab6_medium.jpg"},{"id":664,"message_text":"cvb","user_steamid":"76561198056267433","user_personaname":"#Saundefined","date":"2015-10-06T15:22:12.000Z","user_avatarmedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/c2/c2ff9427410ea1121363de0e651f6d4e8c485ab6_medium.jpg"},{"id":663,"message_text":"g","user_steamid":"76561198056267433","user_personaname":"#Saundefined","date":"2015-10-06T15:22:12.000Z","user_avatarmedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/c2/c2ff9427410ea1121363de0e651f6d4e8c485ab6_medium.jpg"},{"id":662,"message_text":"gdf","user_steamid":"76561198056267433","user_personaname":"#Saundefined","date":"2015-10-06T15:22:12.000Z","user_avatarmedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/c2/c2ff9427410ea1121363de0e651f6d4e8c485ab6_medium.jpg"},{"id":661,"message_text":"df","user_steamid":"76561198056267433","user_personaname":"#Saundefined","date":"2015-10-06T15:22:12.000Z","user_avatarmedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/c2/c2ff9427410ea1121363de0e651f6d4e8c485ab6_medium.jpg"}]
I can upload single photos via URL to Facebook, but I'm having trouble doing it using batch. I'm getting the (#324) Requires Upload File uncaught exception. I'm ensuring the user is logged in and when I look at the batch payload (batchJson) it looks okay.
To be clear, if I remove all the batch-related setup code and in the FB.api call replace "batch" : batchJson with a single "url": photoUrl the code works.
Here's my code. TIA for any insight on my error:
var message = $("#message-fb").val();
var batchItems = [];
var photoUrl = "";
$(".photo-selected").each(function () {
photoUrl = $(this).data('content');
item = {};
item['method'] = 'POST';
item['relative_url'] = 'me/photos';
item['url'] = encodeURI(photoUrl);
item['caption'] = message;
batchItems.push(item);
});
batchJson = JSON.stringify(batchItems);
alert(batchJson);
FB.getLoginStatus(function (response) {
if (response.status === 'connected') {
// Already logged in and authorized
FB.api(
"/",
"POST",
{
"batch": batchJson
},
function (response) {
if (response && !response.error) {
/* successful upload */
alert('Photos uploaded to Facebook (nl) - ' + JSON.stringify(response));
}
if (response && response.error) {
/* Provide error info during testing */
alert('Sorry, there was a problem uploading your photo to Facebook - ' + JSON.stringify(response));
}
});
} else {
// Need to login and authorize
FB.login(function () {
FB.api(
"/",
"POST",
{
'batch': batchJson
},
function (response) {
if (response && !response.error) {
/* successful upload */
alert('Photos uploaded to Facebook - ' + JSON.stringify(response));
}
if (response && response.error) {
/* Provide error info during testing */
alert('Sorry, there was a problem uploading your photo to Facebook - ' + JSON.stringify(response));
}
});
}, { scope: 'publish_actions' });
}
});
EDIT: Here are the relevant changes using #CBroe's answer:
$(".photo-selected").each(function () {
var photoUrl = $(this).data('content');
var item = {};
item['method'] = 'POST';
item['relative_url'] = 'me/photos';
var itemUrl = encodeURI(photoUrl);
var itemCaption = encodeURIComponent(message);
item['body'] = "caption=" + itemCaption + "&url=" + itemUrl;
batchItems.push(item);
});
batchJson = JSON.stringify(batchItems);
You are sending url and caption parameters on the same “level” as the method and relative_url – they need to be put inside a body property however. And the content of that field has to be encoded the same way an actual POST request via a form would be encoded (so like a URL query string, param1=value1¶m2=value2).
I am trying to make an Ajax request to the page specified in the drop down menu. I have successfully used most of my script code in binding a mouse click to table rows, but it does not work in this case when I try it here. I get ReferenceError: fnsuccess is not defined. I did not get this ReferenceError when I used most of this script to bind a mouse click.
<script type="text/javascript">
function isValid(frm){
$("#courseinfo").hide();
$("#frm").validate();
var four04 = $("#frm :selected").val();
console.log('Testing console');
if (four04 == "404")
{
console.log("404");
var txt = ($(this).text());
$.ajax({url:"404.json", data:{coursename:txt}, type:"GET", dataType:"json",
success:fnsuccess, error:fnerror});
function fnsuccess(serverReply) {
if (serverReply && serverReply.info) {
$("#infohere").text(serverReply.info);
$("#courseinfo").show();
} else
fnerror();
}
function fnerror() {
alert("Error occurred");
$("#courseinfo").hide();
}
}
else
{
console.log("else 404");
}
}
</script>
Course -->
Rating
404 error
403 error
Fix:
<script>
function isValid(frm){
$("#otherPageContent").hide();
$("#frm").validate();
var dropDownSelected = $("#frm :selected").val();
if (dropDownSelected == "404")
{
var txt = ($(this).text());
$.ajax({url:"404_error.json",
data:{coursename:txt},
type:"GET",
dataType:"json",
success:fnsuccess,
error: function(xhr, status, error){
$("#infohere").text(
"The requested page was: 404_error.json" +
". The error number returned was: " + xhr.status +
". The error message was: " + error);
$("#otherPageContent").show();
}
}); // end of ajax
} // end of if 404
function fnsuccess(serverReply) {
if (serverReply && serverReply.info) {
$("#infohere").text(serverReply.info);
$("#otherPageContent").show();
}
}
return false; // pause message on screen
}
</script>
define function fnsuccess(serverReply) and fnerror outside isValid function