Prevent redirecting after saving post in blogengine - javascript

I am using BlogEngine as my blogging platform and I would like to know if there is a way to prevent the post redirect action after I am saving my post, I tried to debug the code but couldn't find the redirect action.
this is the save post method in the client side:
function SavePost() {
$('.loader').show();
var content = document.getElementById('<%=txtRawContent.ClientID %>') != null ? document.getElementById('<%=txtRawContent.ClientID %>').value : tinyMCE.activeEditor.getContent();
var title = document.getElementById('<%=txtTitle.ClientID %>').value;
var slug = document.getElementById('<%=txtSlug.ClientID %>').value;
var photo = document.getElementById('<%=txtPostPhoto.ClientID %>').value;
var kind = $("[id$='ddlKind'] option:selected").val();
var isPublished = $("[id$='cbPublish']").is(':checked');
var date = document.getElementById('<%=txtDate.ClientID %>').value;
var time = document.getElementById('<%=txtTime.ClientID %>').value;
var dto = {
"id": Querystring('id'),
"content": content,
"title": title,
"slug": slug,
"postPhoto": photo,
"kind": kind,
"isPublished": isPublished,
"date": date,
"time": time
};
//alert(JSON.stringify(dto));
$.ajax({
url: SiteVars.ApplicationRelativeWebRoot + "admin/AjaxHelper.aspx/SaveMiniPost",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(dto),
beforeSend: onAjaxBeforeSend,
success: function (result) {
var rt = result.d;
if (rt.Success) {
if (rt.Data) {
window.location.href = rt.Data;
} else {
ShowStatus("success", rt.Message);
}
} else ShowStatus("warning", rt.Message);
}
});
$('.loader').hide();
return false;
}

What causes redirecting is:
window.location.href = rt.Data;
Comment it or replace it with alert('success') or something else.

Try this:
$('#form').submit(function (e) {
e.preventDefault();
//your code
});

Related

Jquery/JS - AJAX response if condition

Sorry, I'm new to JS and don't know how to test this IF condition.
If the JSON response has content = false, then this popupSubmit function must be called.
Please assist in checking and letting me know where the error is if the condition is written.
Thanks
{
"id": "4974635f-514e-4d26-8170-ae77c984e8ab",
"content": "true",
"status": "SUCCESS",
"redirect": null
}
var checkID = $('#id-no').val();
var getDomainName = window.location.origin;
$.ajax({
url: getDomainName + '/.rest/stripe/v1/checkID?id=' + checkID,
type: 'GET',
dataType: 'json',
success: function success(response) {
//response = JSON.parse(response);
$.each(response, function (i, v) {
console.log(i.content);
if (i.content == 'false') {
popupSubmit();
}
});
}
});
if(response.content == 'false'){
popupSubmit();
}

Unable to save data using jquery which is lengthy

I have a textareafor
<div class="inner-addon left-addon">
Html.TextAreaFor(m => m.DataFixes, new { #class = "resizedTextbox", id = "txtDataFixes", placeholder = "Data Fixes" , style = "width : 70px,height : 70px;" })
</div>
I have used jquery to save the data using the button click. When i click on the save button then iam able to save the data in the textbox for when the data entered is small, But when i try to save a lengthy data, it doesnot get saved. The below is my jquery code. I think it has something to do with the var object.
$('#btnUpdateDataSet').click(function() {
var note = $("#txtNote").val();
var fileContentName = $("#txtFileContentName").val();
var fileContentId = $("#fileContentId").val();
var dataFixes = $("#txtDataFixes").val();
var oldWorkitemId = $('#drpOldWorkitemId option:selected').val();
if (fileContentName.length == 0) {
var fileContentId = null;
} else {
var fileContentId = $("#fileContentId").val();
}
updateDataSet(workItemID, dataSetDateStamp, cycle, reference, feed, source, target, lineStart, extension, note, fileContentId, dataFixes, oldWorkitemId);
});
The below is my controller
public ActionResult EditDataSet( string dataFixes)
{
EditDataSetVM editDataSetVM = new EditDataSetVM();
editDataSetVM.DataFixes = dataFixes;
return PartialView("EditDataSetView", editDataSetVM);
}
My Ajax call
function updateDataSet(workItemID, dataSetDateStamp, cycle, reference, feed, source, target, lineStart, extension, note, fileContentId, dataFixes,oldWorkitemId) {
$.ajax({
type: "POST",
url: "/DataSet/UpDateDataSetDetails",
contentType: "application/json; charset=utf-8",
data: { "workItemId": workItemID, "dataSetDateStamp":
dataSetDateStamp, "cycle": cycle, "reference": reference, "feed": feed, "source": source, "target": target, "lineStart": lineStart, "extension":
extension, "note": note, "fileContentId": fileContentId, "dataFixes":
dataFixes, "oldWorkitemId": oldWorkitemId },
datatype: "json",
success: function (data) {
if (data == "Update Succeeded") {
$("#btnViewDataSet").click();
}
else {
$("div.toshow").show();
$('#lblUpdateDataSetResult').html('Following error(s) occured:<br\>' + data);
}
},
error: function () {
alert("Update WorkItem metadata failed.");
}
});
}

Inserting image to SAP HANA Table using XSJS

I know this is a known issue but I'm having difficulty on fixing my problem. It seems that I don't receive anything from my UI5 Application when I sent an image via FileUploader to my server. I am new to HCP and this is my first time handling XSJS file. I hope you can help me.
UI5.controller.js
sap.ui.define([
"sap/ui/core/mvc/Controller"
], function(Controller) {
"use strict";
return Controller.extend("sample.controller.View1", {
handleUploadPress : function(oEvent)
{
var fileLoader =this.getView().byId("FileLoader");//XML View
var fileName = fileLoader.getValue();
jQuery.sap.require("sap.ui.commons.MessageBox");
if (fileName === "" )
{
sap.ui.commons.MessageBox.show("Please choose File.", sap.ui.commons.MessageBox.Icon.INFORMATION, "Information");
}
else
{
var uploadUrl = "https://xxxxxx/services/Sample.xsjs?file_name="+fileName;
var formEle = jQuery.sap.domById("UpdateContact--FileLoader");
var form = $(formEle).find("form")[0] ;
var fd = new FormData(form);
$.ajax({
url: uploadUrl,
type: "GET",
beforeSend: function(xhr)
{
xhr.setRequestHeader("X-CSRF-Token", "Fetch");
},
success: function(data, textStatus, XMLHttpRequest) {
var token = XMLHttpRequest.getResponseHeader('X-CSRF-Token');
$.ajax({
url: uploadUrl,
type: "POST",
processData :false ,
contentType: false,
data: fd,
beforeSend: function(xhr)
{
xhr.setRequestHeader("X-CSRF-Token", token);
},
success: function(data, textStatus, XMLHttpRequest)
{
var resptext = XMLHttpRequest.responseText;
jQuery.sap.require("sap.ui.commons.MessageBox");
sap.ui.commons.MessageBox.show(resptext, sap.ui.commons.MessageBox.Icon.INFORMATION, "Information");
if(data === "Upload successful"){
sap.ui.commons.MessageBox.show("File uploaded.", sap.ui.commons.MessageBox.Icon.INFORMATION, "Information");
}
},
error: function(data, textStatus, XMLHttpRequest)
{
sap.ui.commons.MessageBox.show("File could not be uploaded.", sap.ui.commons.MessageBox.Icon.ERROR, "Error");
}
});
}} ) ;
}
}
});
XSJS Service:
$.response.contentType = "text/html";
try
{
var conn = $.hdb.getConnection();
var filename = $.request.parameters.get("file_name");
var headers = $.entity.headers.length;
var pstmt = conn.prepareStatement("INSERT INTO \"XXX_ASSETS\".\"XXX\" VALUES('1',?,'test',CURRENT_USER,CURRENT_TIMESTAMP)");
if($.request.entities.length > 0){
var file_body = $.request.entities[0].body.asArrayBuffer();
pstmt.setBlob(1,file_body);
pstmt.execute();
$.response.setBody("[200]:Upload successful!");
}
else
{
$.response.setBody("No Entries");
}
pstmt.close();
conn.commit();
conn.close();
}
catch(err)
{
if (pstmt !== null)
{
pstmt.close();
}
if (conn !== null)
{
conn.close();
}
$.response.setBody(err.message);
}
}
My code was built based on the tutorials I have found on the internet. Thank You.
A good way to save the image is converting(Base64) and save as blob in HANA table.
Regards

JQuery Success Function not firing

I have the following script. It runs, it passes the variables to the controller, the controller executes correctly, but for whatever reason the success function does not fire and therefore does not refresh my html. Instead the error fires off. Nothing is jumping out at me as to the cause. Thanks for the help!
$(function() {
$("#btnUpdateTick").unbind('click').click(function () {
var currenttick =
{
"TicketID":#Html.Raw(Json.Encode(Model.TicketID)),
"Title": $("#Title").val(),
"Creator": $("#Creator").val(),
"StatusID": $("#StatusID").val(),
"Description": $("#Description").val(),
"newComment":$("#txtAddComment").val(),
Cat:
{
"CatID":$("#ddCurrTickCat").val()
}
}
//var newcomment = $("#txtAddComment").val();
var conv = JSON.stringify(currenttick);
$.ajaxSetup({cache:false});
$.ajax({
url: '#Url.Action("UpdateTicket", "HelpDesk")',
data: JSON.stringify({ticket:currenttick}),
type: "POST",
dataType: "json",
contentType: "application/json",
success: function (data) {
$("#loadpartial").html(data);
},
error: function (data){alert("turd")}
});
});
});
My controller:
[HttpPost]
public PartialViewResult UpdateTicket(Tickets ticket)
{
////Tickets.UpdateTicket(currenttick);
if (ticket.newComment != "")
{
Comments.addCommentToTicket(ticket.TicketID, ticket.newComment,UserPrincipal.Current.SamAccountName.ToString());
}
Tickets model = new Tickets();
ViewBag.CategoryList = Category.GetCategories();
ViewBag.StatusList = TicketStatus.GetStatusList();
model = Tickets.GetTicketByID(ticket.TicketID);
model.TicketComments = new List<Comments>();
model.TicketComments = Comments.GetCommentsForTicketByID(ticket.TicketID);
//model.TicketComments = Comments.GetCommentsForTicketByID(ticketID);
//ViewBag.TicketComments = Comments.GetCommentsForTicketByID(ticketID);
return PartialView("TicketDetails", model);
}
Your controller is returning a view instead of json. You should be returning a JsonResult instead. Try this:
[HttpPost]
public JsonResult UpdateTicket(Tickets ticket)
{
////Tickets.UpdateTicket(currenttick);
if (ticket.newComment != "")
{
Comments.addCommentToTicket(ticket.TicketID, ticket.newComment,UserPrincipal.Current.SamAccountName.ToString());
}
Tickets model = new Tickets();
ViewBag.CategoryList = Category.GetCategories();
ViewBag.StatusList = TicketStatus.GetStatusList();
model = Tickets.GetTicketByID(ticket.TicketID);
model.TicketComments = new List<Comments>();
model.TicketComments = Comments.GetCommentsForTicketByID(ticket.TicketID);
//model.TicketComments = Comments.GetCommentsForTicketByID(ticketID);
//ViewBag.TicketComments = Comments.GetCommentsForTicketByID(ticketID);
return Json(model);
}
If you want to return Partial view from ajax call then modify ur ajax request as :
$.ajax({
url: '#Url.Action("UpdateTicket", "HelpDesk")',
data: JSON.stringify({ticket:currenttick}),
type: "POST",
dataType: "html",
success: function (data) {
$("#loadpartial").html(data);
},
error: function (data){alert("turd")}
});
Now "data" in ur success function will have html returned from PartialViewResult().

django request.user.is_authenticated() isn't returning true after page refresh (sometimes)

I have a registration form. After it is submitted, the page refreshes and I get some information back based on request.user. Sometimes request.user.is_authenticated() is returning True and everything works fine.... and sometimes False seemingly randomly.
I appreciate any insight into why this might be happening.
Registration form code
$('#reg_form').submit(function(e) {
e.preventDefault();
e.stopPropagation();
var serializedData = $(this).serializeArray();
var names = serializedData.map(function(r) {
return r.name;
});
var index_user = names.indexOf("regusername");
var index_pass = names.indexOf("regpassword1");
var index_email = names.indexOf("regemail");
var data2 = {};
data2["username"] = serializedData[index_user].value;
data2["password1"] = serializedData[index_pass].value;
data2["password"] = serializedData[index_pass].value;
data2["password2"] = serializedData[index_pass].value;
data2["email"] = serializedData[index_email].value;
console.log(data2);
var serializedFormData = $(this).serialize();
$.ajax({
url: window.url_root + '/accountsjson/register/',
type: 'POST',
dataType: 'json',
data: data2,
success: function(data) {
console.log(data); //remove
if (data.hasOwnProperty('success')) {
console.log("successful registration detected!!");
utils.loginAfterRegister(data2);
$('.register').slideUp();
$('.frame').hide();
} else {
utils.showRegister();
}
},
error: function() {
console.log("ERROR posting registration request. Abort!");
},
});
Function called from loginAfterRegister which has the refresh
function sendRating(rating, reload_on_return) {
$.ajax({
type: "POST",
dataType: 'json',
url: window.url_root + "/savecommentrating/1/" + rating.cid + "/",
data: {
"rating": rating.r2 / 100.0
},
success: function(data) {
if (data.hasOwnProperty('success')) {
console.log("data was sent!");
if (reload_on_return) {
location.reload();
}
}
},
error: function() {
console.log("rating didn't get sent!!");
}
})
}
mobile function within views.py
def mobile(request):
create_visitor(request)
os = get_os(1)
disc_stmt = get_disc_stmt(os, 1)
return render_to_response('mobile.html', context_instance = RequestContext(request, {'url_root' : settings.URL_ROOT,
'loggedIn' : str(request.user.is_authenticated()).lower(),
'client_data': mobile_client_data(request),
'client_settings': get_client_settings(True),
}))
create_visitor()
def create_visitor(request):
# See if we need to create a visitor here
if not request.user.is_authenticated() and not request.session.get('visitor_id', False):
visitor = Visitor()
visitor.save()
request.session['visitor_id'] = visitor.id

Categories

Resources