I am updating a field using Ajax. Once the update is done, the field is still dirty causing the javascript alert "Are you sure you want to leave this page..you have unsaved changes" message. It's a simple ajax method:
function Save() {
var name = $("#Name").val();
$.ajax({
url: "/Controller/Method",
data: { "firstname": name },
type: 'POST',
async: false,
cache: false,
success: function (result) {
$("#messageToUser").find("label").html("Updated successfully");
},
error: function(xhr, textStatus, errorThrown) {
alert("in error");
}
});
}
From my googling, I found that I cannot block that message using the onbeforeunload, as that may have other effects on ajax functions etc.,. So what are my options?
Related
I am working on page when user submits data and retrieves html data which contains hyperlinks.
Now when the user clicks on the link, he will be navigated to another page and when the user clicks on browser back button, I want to show earlier displayed html data.
In order to achieve this, I tried to store the value in session and retrieve it when user clicks back browser button.
But I am facing issues
I tried to capture browser back button and display the session stored variable and I am not sure why this is not getting triggered.
$(window).on('hashchange', function () {
$("#spanId").html("test");
});
Html data stored in session variable is not displaying properly like "<" is showing as "<" and all the data is showing as string instead of html content.
$(document).ready(function () {
$("#spanId").html("#Session["Data"]");
$("#btnSubmit").click(function () {
var data = {
"Date": $.datepicker.formatDate("mm-dd-yy", DateVal),
"Type": $('#type').val(),
}
$.ajax({
type: 'POST',
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data),
url: '#Url.Action("GetReportdata", "Reports")',
success: function (result) {
$("#spanId").html(content);
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
});
});
Please let me know if there is any other way to handle this and help me resolves this issue.
There might be another way of solving this on the server side, but this should work.
$(document).ready(function () {
$("#spanId").html(decodeHtml("#Session["Data"]"));
$("#btnSubmit").click(function () {
var data = {
"Date": $.datepicker.formatDate("mm-dd-yy", DateVal),
"Type": $('#type').val(),
}
$.ajax({
type: 'POST',
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data),
url: '#Url.Action("GetReportdata", "Reports")',
success: function (result) {
$("#spanId").html(decodeHtml(content));
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
});
});
function decodeHtml(encodedHtml) {
return encodedHtml.replace(/&/g,'&')
.replace(/</g,'<').replace(/>/g,'>');
}
I found an event to handle browser back button:
if (window.performance && window.performance.navigation.type ==
window.performance.navigation.TYPE_BACK_FORWARD) {
$("#spanId").html("#Session["Data"]");
}
This can be used to repopulate data.
I'm working with someone else's code trying to get an alert to come up to notify the user if the operation was unsuccessful. I put an "if (true)" statement in front of the function and then an "else" statement after the function, thinking that IF the function ran successfully, it would alert the user with "success" otherwise it would alert "operation failed". Did I do this right? I'm completely new to Javascript.
$("#assignBtn").on("click", function () {if(true){
$.ajax({
type: "GET",
url: $SCRIPT_ROOT + '/_parse_checklist/assign_checklist',
data: {
username: $("#assignChecklistTo").val(),
id: $clientSelect.val()
},
dataType: "json",
beforeSend: function () {
},
complete: function () {
alert("Success!");
}
});}
else {alert("Operation unsuccessful...")}
});
Instead of if/else you can use ajax methods:
success: function(data) {
// success
},
error: function(data) {
// error
}
I am new to ajax and javascript.
I have the following web method in a page called people.aspx in the root of my web porject:
[System.Web.Services.WebMethod]
public static string RenderDetails()
{
return "Is it working?";
}
I'm attempting to access the web method via an Ajax call from the people.aspx page. I have the following ajax call on the click event of a div:
$("div.readonly").click(function (e) {
e.stopPropagation();
$.ajax({
type: "POST",
async:false,
url: "people.aspx/RenderDetails",
dataType: "json",
beforeSend: function () {
alert("attempting contact");
},
success: function (data) {
alert("I think it worked.");
},
failure: function (msg) { alert("Sorry!!! "); }
});
alert("Implement data-loading logic");
});
I'm not receiving any errors in the javascript console, however, the ajax call also does not hit the web method. Any help will be appreciated.
Thanks!
Try change the type to GET not POST (this is probably why your webpage isn't getting hit). Also your failure parameter is incorrect, it should be error. Expand it to include all parameters (it will provide more information). In short, change your entire AJAX query to this:
$.ajax({
type: "GET",
async:false,
url: "people.aspx/RenderDetails",
dataType: "json",
beforeSend: function () {
alert("attempting contact");
},
success: function (data) {
alert("I think it worked.");
},
error: function (jqXhr, textStatus, errorThrown)
alert("Sorry!!! "); // Insert breakpoint here
}
});
In your browser, debug the error function. The parameters (particularly jqXHR) contain a LOT of information about what has failed. If you are still having more problems, give us the information from jqXHR (error string, error codes, etc).
Hello everyone and thanks for your time.
Here is my javascript:
$('.sender').click(function (e) {
$.ajax({
type: "POST",
url: "fHandler.ashx",
data: { firstName: 'stack', lastName: 'overflow' },
// DO NOT SET CONTENT TYPE to json
// contentType: "application/json; charset=utf-8",
// DataType needs to stay, otherwise the response object
// will be treated as a single string
dataType: "json",
success: function (response) {
alert('success');
},
error: function (response) {
alert('error: ' + response);
console.log('err: '+response);
}
});
});
And here is the code in my .ashx handler:
public void ProcessRequest(HttpContext context)
{
context.Response.AppendHeader("Access-Control-Allow-Origin", "*");//to fix the allow origin problem
context.Response.ContentType = "text/plain";
string json = new StreamReader(context.Request.InputStream).ReadToEnd();
context.Response.Write(json);
}
public bool IsReusable
{
get
{
return false;
}
}
While the click event is working, my Ajaxrequest doesn't seem to get any response as the alert at success doesn't popup. I've debugged using the browser's network console and it return the expected response but it doesn't seem to reach the success function in the JavaScript code. Any insights or suggestions are welcome. Thanks.
In case you are still interested in the answer, try this before doing the request
var data = { firstName: 'stack', lastName: 'overflow' };
var jsonData = JSON.stringify(data);
and change your AJAX request to
$.ajax({
type: "POST",
url: "fHandler.ashx",
data: jsonData,
dataType: 'json',
contentType: 'application/json; charset-utf-8'
})
.done(function (response) {
// do something nice
})
.fail(function (jqXHR, textStatus, errorThrown) {
console.log("request error");
console.log(textStatus);
console.log(errorThrown);
});
Explanation
You are trying to send the plain data object. You must transform it into a Json string using JSON.stringify(object).
Changing the dataType isn't really a solution but a workaround.
Additional Notes
Also, I think you should use .done() and .fail(). See here for further details.
Can you help me with this code?
function blub() {
$.ajax({
type: 'GET',
url: 'blups1.php?rid=10',
async: true,
cache: false,
dataType: 'json',
success: function(data){
var name = data[0].name;
alert('ok = '+name);
},
error: alert('nix gefunden')
});
}
In case of success it shows me what I want, but the alert from error always pop up at first. Where do I have to place that error alert so that it will only appear if there is no database?
I'm really not sure why one would just place the alert statement singularly as the callback. Put the alert in a function:
error: function(xhr, status, error) {
alert('nix gefunden');
}