This is my Function.
function GetData() {
try {
$.ajax({
type: "POST",
url: "CompanyOverAllReport.aspx/GetAllData",
data: '{date1: "' + $('#<%=this.txtDateFrom.ClientID%>').val() + '" , date2: "' + $('#<%=this.txtDateto.ClientID%>').val() + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
//console.log(JSON.parse(response.d));
var data = response.d;
//console.log(data['account']);
ExecuteGraph(data);
},
failure: function(response) {
// alert(response);
alert("f");
}
});
} catch (e) {
alert(e);
}
}
This is My Pageload
$(document).ready(function() {
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoaded);
});
function pageLoaded() {
alert("Testing");
//GetData();
}
This is my Button
<asp:LinkButton ID="btnok" runat="server" CssClass="btn btn-primary okBtn" OnClientClick="GetData()" >Ok</asp:LinkButton>
Your click event fires the function, but doesn't prevent anything from happening...
OnClientClick="GetData()"
A simple example of cancelling the default action would be to use:
OnClientClick="GetData(); return false;"
It is also possible to prevent the default and cancel bubbling using the event that is passed with the click, your GetData function would need to accept it as the first argument.
Related
I have a textbox (txtDescription) where the user can type a description when an event is canceled.
The problem is when the there is an apostrophe ' with in that textbox AJAX throws an error. Without the apostrophe it works and saves fine.
I have tried using JSON.stringify but this did not work.
This is my code:
$("#btnCancelEvent").click(function () {
var CencelDesc = $("#txtDescription").val();
var user = $("#lblFullName").html();
if (CencelDesc === "") {
alert("Please provide a reason why this schedule event is being canceled.");
return false;
} else {
$.ajax({
type: "POST",
url: "ScheduleOverview.aspx/CancelEvent",
data: "{'ScheduleID': '" + ScheduleID +
"','CentreID': '" + CentreID +
"','CencelDesc': '" + CencelDesc + //this is where the problem occurs
"','user': '" + user + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
swal("Information", "Schedule Event Cancelled.", "success");
$('#CancelSchedule').modal('hide');
}
});
return false;
}
return false;
});
Please assist how I can fix this issue.
Two issues:
JSON uses double quotes, not single quotes.
Never buld JSON strings by hand. Instead, build an object and let JSON.stringify handle the escaping, etc., for you.
So:
$.ajax({
type: "POST",
url: "ScheduleOverview.aspx/CancelEvent",
data: JSON.stringify({ScheduleID: ScheduleID
,CentreID: CentreID
,CencelDesc: CencelDesc
,user: user }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
swal("Information", "Schedule Event Cancelled.", "success");
$('#CancelSchedule').modal('hide');
}
});
Side note: There's no need for dataType: "json" in that code. You're not doing anything with the response. In fact, in general, using dataType is an anti-pattern. Instead, ensure that the server sends back the correct Content-Type header.
I wanted to apply bootstrap button to dynamically create buttons via Ajax Call.In my code without bootstrap css class it's working on just default buttons But i want to apply bootstrap button When i use bootstrap css class --> class=btn btn-large btn-primary,Then it's not working
My Code
function LoadSpecialFilesToUser() {
debugger;
var newurls = '<%= ResolveUrl("/WebMethods.aspx/GetSpecialFilesToUsers") %>';
$.ajax({
url: newurls,
type: "POST",
data: JSON.stringify({ Id: "<%=GetUserID()%>" }),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (Result) {
$.each(Result.d, function (key, value) {
$("#SpecialFiles").append("<button class=btn btn-large btn-primary><a href=" + value.FilePath + "/>" + value.Caption + "</button>");//<-- In here without class=btn btn-large btn-primary.It's working
});
},
error: function (e, x) {
alert(x.ResponseText);
}
});
}
The Form:
<form action="upload-document.aspx" onsubmit="sendAndClose();" method="post" enctype="multipart/form-data">
<input name="fileToUpload" id="fileToUpload" type="file" />
<input type="submit" name="submit" value="Send" />
</form>
The AJAX:
function sendAndClose() {
currentUrl = location.protocol + '//' + location.host + location.pathname;
var data = new FormData();
var file = $("#fileToUpload")[0].files[0];
data.append("name", file.name);
data.append("size", file.size);
data.append("type", file.type);
data.append("file", file);
$.ajax({
type: "POST",
url: currentUrl + '/Persist',
dataType: 'json',
data: data,
cache: false,
contentType: false,
processData: false,
success: function () {
parent.$.fancybox.close();
},
error: function (request, error) {
alert("[" + error + "] - FAIL: " + request.responseText);
parent.$.fancybox.close();
}
});
}
The Code-Behind:
[WebMethod]
public static bool Persist(object data)
{
return true;
}
when the form is submitted, it runs the ajax and goes straight to the error callback before entering the webmethod. can anybody tell me why?
also, after the 'var file' I had an alert to show the files name, size, etc... so it gets the file, the problem is that ajax is refusing to comunicate with the code-behind.
I had a similar problem that was solved by adding this parameter in the ajax function :
traditional: true
So try this code for your AJAX call :
$.ajax({
type: "POST",
url: currentUrl + '/Persist',
dataType: 'json',
data: data,
cache: false,
contentType: false,
processData: false,
traditional: true,
success: function () {
parent.$.fancybox.close();
},
error: function (request, error) {
alert("[" + error + "] - FAIL: " + request.responseText);
parent.$.fancybox.close();
}
});
You cannot invoke a webmethod like http://localhost:40899/upload-document.aspx/Persist. The currentUrl is incorrect.
Following on from my question in the comments section I would add that your public static bool Persist... method MUST be in the page (ASPX) and not a user-control (ASCX).
This is because the page (ASPX) is "visible" to the outside world via a URL whereas a user-control (ASCX) is only used on the server to build up the page not a URI in its own right, and therefore not accessible to external callers.
If you need to call the method in the user-control you will need to move your Persist method (with WebMethod attribute) to your page (ASPX) and then make a call from that method into your user-control (ASCX).
I have a dialog in an ASP.Net,c# application.This dialog has a textbox.When I choose save I want to call a function from C# who makes some verifications in the database and then to get the result in javascript/jquery.If the inserted value is true I want to close the dialog other way to remain opened,but I can't succed to close the dialog box after i receive true from c# function.Below is the code:
ascx :
<div id="popup" title="Choose Delegate">
<label>Delegate<label><input type="textbox" value="" name="inputD" id=="inputD"/>
</div>
Javascript:
$('#btnAdd').click(function(e){
$('#divPopup').slow("show");
$('#divPopup').dialog({
height:150,
width:300,
modal:true,
buttons:{
"close":function(){$(this).dialog("close");}
"save":function(){
var obj=document.getElementid("inputD");
$.ajax({
type: "POST",
url: "add.aspx/check",
data: "{delegate: '" + obj.Value+"'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
rez= "OK";
$(this).dialog("close");
},
failure: function () {alert("FAIL"); }}); }
});
}
C#:
[WebMethode]
public static Boolean check(string delegate)
{
.....
return true;
}
C# methode returns corect value.
I try also this :
$('#btnAdd').click(function(e){
$('#divPopup').slow("show");
$('#divPopup').dialog({
height:150,
width:300,
modal:true,
buttons:{
"close":function(){$(this).dialog("close");}
"save":function(){
var obj=document.getElementid("inputD");
var rez ;
$.ajax({
type: "POST",
url: "add.aspx/check",
data: "{delegate: '" + obj.Value+"'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
rez= "OK";
},
failure: function () {alert("FAIL"); }
});
if (rez="OK")
$(this).dialog("close");
}
});
But it doesn't see the rez value in this case.
Thanks !
You can use an Ajax Call in your "save":function(e) and just check the returned value if true close dialog, else remain opened
Ajax calls are really simple to implement, I let you search that :)
You need a web-service on the server side. (preferably REST)
http://restsharp.org/ is an easy to use library for that.
Take a look at this question for more info.
In the front end you make an ajax call to you're REST api (I see you use jquery so it won't be that hard ;))
Currently I have this...
public void lnkTag_Click(object sender, EventArgs e){
...
}
Which is attached to the click() event of link buttons, but the problem is this requires a form resubmission when the user tries to back in the browser after clicking one.
I'd like to turn this into an ajax call that passes in the text value of the link. So to have a method like this in the code behind:
public void lnkTag_Click(string linkText){
...
}
Where this method is accessed via ajax on a
$('myLinkButton').click(function() {
$.ajax...
})
Any thoughts? Thanks.
Do the following for sending the parameter value:
$('myLinkButton').click(function() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "yourpage.aspx/lnkTag_Click",
data: "{'linkText': '" + linkTextValue + "'}",
dataType: "json",
success: function(data) {
//do something if it's successful
},
error: function(jqXHR, textStatus, errorThrown) {
//do something if there's an error
}
});
});