Recently we encountered an issue when we were trying (unsuccessfully) to update a link outside an Ajax UpdatePanel using jQuery.
We wrote the change events and we noticed that they only fired once and no more. Clicking on the tickbox proved to be futile. Not even 317 clicks seemed to work.
After a bit of research, we found out that the Update Panels only subscribe to the page load event once and afterwards they drop the events, unless you rebind them once more.
To rebind them, you need to call the PageRequestManager and connect to the endRequest method.
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function () {…});
$('#ctl00_ContentPlaceHolder1_chkLinkedSuppliers').on('change', function () {
if ($('#ctl00_ContentPlaceHolder1_lnkAuditReport2').length > 0)
{
var href = $('#ctl00_ContentPlaceHolder1_lnkAuditReport2').attr("href");
///Reports/AuditReport2.aspx?ID=21074&ShowAll=0&ShowAllSystems=0&ShowAllCompanies=0&ShowAllLinked=1
href = href.replace("&ShowAllLinked=1","").replace("&ShowAllLinked=0","");
if($(this).is(":checked")) {
href = href + "&ShowAllLinked=1";
}else{
href = href + "&ShowAllLinked=0";
}
$('#ctl00_ContentPlaceHolder1_lnkAuditReport2').attr("href", href);
}
});
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function () {
// re-bind your jQuery events here
$('#ctl00_ContentPlaceHolder1_chkLinkedSuppliers').on('change', function () {
if ($('#ctl00_ContentPlaceHolder1_lnkAuditReport2').length > 0) {
var href = $('#ctl00_ContentPlaceHolder1_lnkAuditReport2').attr("href");
///Reports/AuditReport2.aspx?ID=21074&ShowAll=0&ShowAllSystems=0&ShowAllCompanies=0&ShowAllLinked=1
href = href.replace("&ShowAllLinked=1", "").replace("&ShowAllLinked=0", "");
if ($(this).is(":checked")) {
href = href + "&ShowAllLinked=1";
} else {
href = href + "&ShowAllLinked=0";
}
$('#ctl00_ContentPlaceHolder1_lnkAuditReport2').attr("href", href);
}
});
It worked like a charm!
"text/javascript">
function BindControlEvents() {
//jQuery is wrapped in BindEvents function so it can be re-bound after each callback.//Your code would replace the following line:
$('#').limit('100', '#charsLeft_Instructions');
}
//Initial bind
$(document).ready(function () {
BindControlEvents();
});
//Re-bind for callbacksvar prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function() {
BindControlEvents();
});
If you’re a user of our design applications such as Photoshop and Illustrator, you know how you can create very cool effects with blend modes. An Amazon search returns many books and a Google search on ‘photoshop blending tutorial’ returns more than 200,000 results. This points to a very widely known and used feature.
To be able to blend to images together like Photoshop does, we will need to use the HTML5 canvas feature. The images are loaded dynamically using Javascript.
The easy way to blend two images together can be summarized into
// Might be an 'offscreen' canvas
var over = someCanvas.getContext('2d');
var under = anotherCanvas.getContext('2d');
over.blendOnto( under, 'screen', {destX:30,destY:15} );
Now how would you transform this into a POST string with JSON?
var myURL = "http://mywebservice/MyService.asmx/SendEmail";
var dataToUse = $.parseJSON('{"Username": "1234","Password":"1224!","EmailFrom":"no-reply@carra-lucia-ltd.co.uk","EmailTo":"carra_lucia@hotmail.com","Subject":"MySubject","Message":"' + msg + '"}');
$.ajax({
type: "POST",
url: myURL,
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
data: dataToUse,
crossDomain: true,
success: function (response) {
//email was sent
alert("Email has been sent successfully!");
},
error: function (jqXHR, error, errorThrown) {
if (jqXHR.status && jqXHR.status == 400) {
alert(jqXHR.responseText);
} else {
alert("Something went wrong. We could not send your email.");
}
}
});
One imprtant distinction is what I mean by a JSON object and JSON format. A JSON object is an object that can be used by javascript
var o = {data: 'value'};
alert (o.data); // this works as o is an object
JSON format is simply a literal string that can be turned into a JSON object if we parse it
var f = "{data: 'value'}";
alert (f.data); // this won't work as f is just a string and string doesn't have a data property
The following code calls a webservice that has three different SayHello functions.
[WebMethod]
public string SayHello(string firstName, string lastName)
{
return "Hello " + firstName + " " + lastName;
}
[WebMethod]
public string SayHelloJson(string firstName, string lastName)
{
var data = new { Greeting = "Hello", Name = firstName + " " + lastName };
// We are using an anonymous object above, but we could use a typed one too (SayHello class is defined below)
// SayHello data = new SayHello { Greeting = "Hello", Name = firstName + " " + lastName };
System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
return js.Serialize(data);
}
[WebMethod]
public SayHello SayHelloObject(string firstName, string lastName)
{
SayHello o = new SayHello();
o.Greeting = "Hello";
o.Name = firstName + " " + lastName;
return o;
}
“SayHello” returns a string
“SayHelloJson” returns a string that is an object in JSON format
“SayHelloObject” returns an object. The SayHello class is here
public class SayHello
{
public string Greeting { get; set; }
public string Name { get; set; }
}
I have added the comments inline on the code, but the examples cover calling all three types of webservice method, and they also cover getting simple text back and getting JSON objects back, and also sending parameters in form encoded formats and also JSON formats.
/*
SayHello returns a string
SayHelloJson returns a string that is an object in JSON format
SayHelloObject returns an object
[WebMethod]
public string SayHello(string firstName, string lastName)
{
return "Hello " + firstName + " " + lastName;
}
[WebMethod]
public string SayHelloJson(string firstName, string lastName)
{
var data = new { Greeting = "Hello", Name = firstName + " " + lastName };
// We are using an anonymous object above, but we could use a typed one too (SayHello class is defined below)
// SayHello data = new SayHello { Greeting = "Hello", Name = firstName + " " + lastName };
System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
return js.Serialize(data);
}
[WebMethod]
public SayHello SayHelloObject(string firstName, string lastName)
{
SayHello o = new SayHello();
o.Greeting = "Hello";
o.Name = firstName + " " + lastName;
return o;
}
public class SayHello
{
public string Greeting { get; set; }
public string Name { get; set; }
}
*/
$(document).ready(function () {
// SayHello returns a string we want to display. Examples A, B and C show how you get the data in native
// format (xml wrapped) as well as in JSON format. Also how to send the parameters in form-encoded format,
// JSON format and also JSON objects. To get JSON back you need to send the params in JSON format.
// Example A - call a function that returns a string.
// Params are sent as form-encoded, data that comes back is text
$.ajax({
type: "POST",
url: "MyWebService.asmx/SayHello",
data: "firstName=Aidy&lastName=F", // the data in form-encoded format, ie as it would appear on a querystring
//contentType: "application/x-www-form-urlencoded; charset=UTF-8", // if you are using form encoding, this is default so you don't need to supply it
dataType: "text", // the data type we want back, so text. The data will come wrapped in xml
success: function (data) {
$("#searchresultsA").html(data); // show the string that was returned, this will be the data inside the xml wrapper
}
});
// Example B - call a function that returns a string.
// Params are sent in JSON format, data that comes back is JSON
$.ajax({
type: "POST",
url: "MyWebService.asmx/SayHello",
data: "{firstName:'Aidy', lastName:'F'}", // the data in JSON format. Note it is *not* a JSON object, is is a literal string in JSON format
contentType: "application/json; charset=utf-8", // we are sending in JSON format so we need to specify this
dataType: "json", // the data type we want back. The data will come back in JSON format
success: function (data) {
$("#searchresultsB").html(data.d); // it's a quirk, but the JSON data comes back in a property called "d"; {"d":"Hello Aidy F"}
}
});
// Example C - call a function that returns a string.
// Params are sent as a JSON object, data that comes back is text
$.ajax({
type: "POST",
url: "MyWebService.asmx/SayHello",
data: { firstName: 'Aidy', lastName: 'F' }, // here we are specifing the data as a JSON object, not a string in JSON format
// this will be converted into a form encoded format by jQuery
// even though data is a JSON object, jQuery will convert it to "firstName=Aidy&lastName=F" so it *is* form encoded
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
dataType: "text", // the data type we want back, so text. The data will come wrapped in xml
success: function (data) {
$("#searchresultsC").html(data); // show the data inside the xml wrapper
}
});
// SayHelloJson returns a .net object that has been converted into JSON format. So the method still return a
// string, but that string is an object in JSON format. It is basically an object within an object. We still
// get the "d" property back as in Example B, but "d" is an object represented in JSON format itself.
// Example D - call a function that returns a string that is an object in JSON format.
// Params are sent in JSON format, data that comes back is a string that represents an object in JSON format
$.ajax({
type: "POST",
url: "MyWebService.asmx/SayHelloJson",
data: "{ firstName: 'Aidy', lastName: 'F' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var myData = JSON.parse(data.d); // data.d is a JSON formatted string, to turn it into a JSON object
// we use JSON.parse
// now that myData is a JSON object we can access its properties like normal
$("#searchresultsD").html(myData.Greeting + " " + myData.Name);
}
});
// SayHelloObject returns a typed .net object. The difference between this and Example D is that in Example D
// the "d" property is an object in JSON format so we need to parse it to make it a JSON object. Here the
// "d" property is already an actual JSON object so no need to parse it.
// Example E - call a function that returns an object. .net will serialise the object as JSON for us.
// Params are sent in JSON format, data that comes back is a JSON object
$.ajax({
type: "POST",
url: "MyWebService.asmx/SayHelloObject",
data: "{ firstName: 'Aidy', lastName: 'F' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var myData = data.d; // data.d is a JSON object that represents out SayHello class.
// As it is already a JSON object we can just start using it
$("#searchresultsE").html(myData.Greeting + " " + myData.Name);
}
});
});
</form>
</body>
</html>
I was trying to call a webservice method through the jquery ajax metod and guess what: I was always getting an xml response
$.ajax(
{
type: “POST”,
url: http://localhost:50080/ElearningWebApplication/ChatWebService.asmx/InserMessage,
data: “{}”,
contentType: “application/json; charset=utf-8”,
dataType: “json”,
crossDomain: true, success: function (response) {
//email was sent
alert(“Email has been sent successfully!”);
},
error: function (jqXHR, error, errorThrown) {
if (jqXHR.status && jqXHR.status == 400) {
alert(jqXHR.responseText);
} else {
alert(“Something went wrong. We could not send your email.”);
}
}
}
);
I included the correct attributes to both the service and the method
[WebService(Namespace = “http://www.action.gr/”)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)] // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService] publicclassChatWebService : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
publicstring InsertMessage(string text, int roomID, int userID, string color, int toUserID)
{
…..
}
}
Did you specify type: “POST” in the ajax request? A security feature of ASP.NET web services that are JSON serialized through the ASP.NET AJAX extensions is that they must be requested in a specific way. This is an important deterrent against your services being used in XSS attacks.
Did you specify contentType: “application/json; charset=utf-8” in the ajax request?
Did you specify dataType: “json”in the ajax request?
Does your .asmx web service include the [ScriptService]` attribute?
Does your web method include the [ScriptMethod(ResponseFormat = ResponseFormat.Json)] attribute? (My code works even without this attribute, but a lot of articles say that it is required)
Have you added the ScriptHandlerFactory to the web.config file in ?
Have you removed all handlers from the the web.config file in in ?