I have the following jQuery AJAX request:
function sendUpdate(urlToSend) {
var code = AccessCode;
var url = urlToSend;
var options = { error: function(msg) { alert(msg.d); },
type: "POST", url: "webmethods.aspx/UpdatePage",
data: "{ accessCode: " + code + ", newURL: '" + url + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function(response) { var results = response.d; } };
$.ajax(options);
}
And the corresponding ASP.NET WebMethod:
[WebMethod]
public static bool UpdatePage(string accessCode, string newURL)
{
bool result = true;
try
{
HttpContext.Current.Cache[accessCode + "l"] = newURL;
}
catch
{
result = false;
}
return result;
}
That all used to work correctly with "async:false", however I have to get rid of it as it freezes the browser until the response is received. Now the AJAX request above returns "undefined".
Could anybody tell me why it happens and where the problem is?
Thanks.
You should really make sure to properly encode this JSON. JSON.stringify is the most reliable method:
data: JSON.stringify({ accessCode: code, newURL: url })
This ensures that even if the code and url variables contain some dangerous characters that will break your string concatenations in the resulting JSON at the end everything will be properly encoded. The JSON.stringify method is natievly built into modern browsers but if you need to support legacy you could include json2.js.
Also because you code is no longer blocking you should make sure that if you call this sendUpdate from some button click or form submit you cancel the default action by returning false.
My way works correctly:
[System.Web.Services.WebMethod()]
public static string getHello(string str)
{
//do some things with str
return str;
}
In file .js, I define this function to call webmethod in file .cs:
function CallServerFunction(StrPriUrl, ObjPriData, CallBackFunction) {
$.ajax({
type: "post",
url: StrPriUrl,
contentType: "application/json; charset=utf-8",
data: ObjPriData,
dataType: "json",
success: function (result) {
if (CallBackFunction != null && typeof CallBackFunction != 'undefined') {
CallBackFunction(result);
}
},
error: function (result) {
alert('error occured');
alert(result.responseText);
window.location.href = "FrmError.aspx?Exception=" + result.responseText;
},
async: true
});
}
Then, call to use (call in file.js):
var text = $("#textbox_send").val();
var myresult;
CallServerFunction("Default.aspx/getHello", JSON.stringify({ str: text }), function (myresult) {
if (text != "")
$('#' + id).append('<p>' + $("#account_user").text() + ': ' + myresult.d + '</p>');
});
The "undefined" could be the result of a server error.If you use Firebug,Firefox(or any good client debugging tool), you can find the error returned by the server. Paste the error,if any.
Nevertheless, I also noted the the "data" for "accessCode" is not properly enclosed within quotes ‘ ’
The corrected data option would be :
data: "{ accessCode: '" + code + "', newURL: '" + url + "' }",
PS:
Since 'options' have a different meaning in Jquery, I would recommend changing the variable name as 'setting' . Change 'var options ' to 'var settings'. :)
Related
I'm working on an MVC C# web that has a "shared" project which has a Helper class called ImageUrlHelper that has a method called GenerateAzureUrl which returns a string, and I need to call this method through an ajax call.
I've tried:
$.ajax({
type: 'POST',
url: '/Helpers/ImageUrlHelper/GenerateAzureUrl',
data: '{ "path": "' + path + '"}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
}
});
But it's not working, and I'm guessing you can only call a controller method from Ajax. Am I right? Or maybe it should work and I'm doing something wrong in my call.
BTW, this is my Helper method:
public static string GenerateAzureUrl(string path)
{
var pathPartsFromI = Regex.Split(path, "/i/");
if (pathPartsFromI.Length != 2) return path;
var rightPathParts = Regex.Split(pathPartsFromI[1], "/");
if (rightPathParts.Length < 2) return path;
var id = rightPathParts[0];
var size = (rightPathParts.Length == 2 ? "ori" : rightPathParts[1]);
var slug = rightPathParts[rightPathParts.Length - 1];
var extension = slug.Split('.')[1].Split('%')[0];
string azureUrl = _urlAzureImageDomain + "/images/" + size.ToLower() + "/" + id + "." + extension;
bool imgExists = ImageExists(id, size.ToLower(), extension);
if (!imgExists)
{
if (size.ToLower() != "ori") imgExists = ImageExists(id, "ori", extension);
if (!imgExists) return "/Content/images/image_not_found.jpg";
azureUrl = _urlAzureImageDomain + "/images/ori/" + id + "." + extension;
}
return azureUrl;
}
What I'm receiving is a 404 Not Found.
Thanks.
As mentioned in the comments,
Create an action in a controller class that calls the GenerateAzureUrl() method.
[HttpPost]
[Route("get/azure/url/from/api/{path}")]
public string GetAzureUrlFromAPI(string path)
{
return GenerateAzureUrl(path);
}
In AJAX call:
$.ajax({
type: 'POST',
url: '../../../get/azure/url/from/api/' + path,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
}
});
You cannot use like that, as you already has answer with you "Controller". AJAX from Web browser take routing help to call the methods.
Check other reference: Ajax method call
Thanks
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.
my script code:
$('#btnSave').click(function() {
var pageUrl = '<%= ResolveUrl("~/TestPage.aspx/SystemEdit")%>';
var ip = $('#editIP').text();
var loc = $('#txtBay').val();
var team = $('#txtTeam').val();
var port = $('#txtPort').val();
var xcel = "", office = "", moni = "";
var parameter={ "ip": ip, "loc": loc, "team": team, "port": port, "excel": xcel, "office": office, "monitor": moni}
$.ajax({
type: 'POST',
url: pageUrl,
data: JSON.stringify(parameter),
contentType: 'json',
success: function(data) {
alert(data);
},
error: function(data,success,error) {
alert("Error:" +error);
}
});
});
my code behind c# code is:
[WebMethod]
public static string SystemEdit(string ip, string loc,string team, string port, string excel,string office, string monitor)
{
return "The Current Time is: "+ DateTime.Now.ToString();
}
my page name is : TestPage.aspx
While clicking the save button I'm getting 'undefined'. I'm not getting the current time from code behind c#.
You need to return json result as below:
return JsonConvert.SerializeObject("The Current Time is: "+ DateTime.Now.ToString());
also put below attribute above method:
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
And as you specified json format you should write:
contentType: "application/json; charset=utf-8",
By the way you should use a Webservice here!
I guess setting a json content type should be done this way:
contentType: 'application/json',
If you are using vs2013 then make sure you disable the below line in route.config to get things working.
'settings.AutoRedirectMode = RedirectMode.Permanent
My VB Code Behind:
<WebMethod()>
Public Shared Function GetReport(ByVal Data As String) As String
Try
Return "Hello" + Data
Catch ex As Exception
Return "Failed"
End Try
End Function
Js Script :
$('#btnSave').click(function () {
var char = $(this).text();
var SendData = {};
$.ajax({
type: "POST",
url: "TEST.aspx/GetReport",
data: JSON.stringify(SendData),
data: "{ 'Data': '" + char + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$('#lbl_test').text(data.d);
},
error: function (data, success, error) {
alert("Error:" + error);
}
});
});
when i add alert(file) line after ajax block code work but when i remove alert(file) code not work .
this is work fine :
function Delete(file) {
$.ajax({
type: "POST",
url: "Image.aspx/Delete",
data: '{file: "' + file + '" }',
contentType: "application/json; charset=utf-8",
datatype: "jsondata",
async: "true",
success: function (response) {
$("#statusBox").text("ok"); //alert(response.d);
},
error: function (response) {
$("#statusBox").text("error"+response.text);
// alert(response.status + ' ' + response.statusText);
},
complete: function () {
// $("#statusBox").text("completed");
}
});
alert(file);
}
if i remove alert(file) line code web method not work.
this my c# asp.net code web method :
[WebMethod]
public static string Delete(string file)
{
try
{
// int lastSlash=file.ind
// Lesson learnt - always check for a valid URI
if (Uri.IsWellFormedUriString(file, UriKind.Absolute))
{
Uri uri = new Uri(file);
file = (uri.LocalPath);
}
//file= file.Remove(0)
//File.Delete(file);
File.Delete(HttpContext.Current.Server.MapPath(#"~\" + file.Replace("/", #"\")));
}
catch (Exception ex)
{
return ex.Message;
}
return "ok";
}
You're sending the request asynchronously,try to make false asynchronous.
for more information take a look at this
I see three (3) errors in your code:
data: '{file: "' + file + '" }',
datatype: "jsondata",
async: "true",
You are not sending a js object to the server.
jsondata is not a valid datatype.
async is a boolean and you are instead assigning a string value.
So the solution from here is:
data: {file: file }, // send a object
datatype: "text", // change to text because you are returning "ok" string
async: true, // remove the quotes
Another suggestion is try with default headers:
contentType: "application/json; charset=utf-8",
Try removing this line and see.
html
<a onclick="testGetParametersDynamic2();">fill in names and check it out</a>
<br />
<p>Enter First Name</p>
<input id="myFirstName" type="text" />
<br />
<p>Enter Last Name</p>
<input id="myLastName" type="text" />
<div id="outputGET3"></div>
c#
[WebMethod(EnableSession = true)]
[ScriptMethod(UseHttpGet = true)]
public string testGetParametersDynamic(string firstName, string lastName)
{
string fullName = firstName + lastName;
return fullName;
}
I have tried multiple ways of entering data bc I think this is where the problem lies
attempt 1
function testGetParametersDynamic2()
{
$.ajax(
{
post: 'GET',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: '{"firstName":"' + $('#myFirstName').val() + '","lastName":' +
$('#myLastName').val() + '"}',
url: 'UtilitieService.asmx/TestGetParametersDynamic',
success: function (result)
{
var test = result.d;
var outputDiv = $('outputGET3');
outputDiv.html(test);
},
error: function ()
{
alert('Fail Test Get Dynamic');
}
});
}
attempt 2:
function testGetParametersDynamic2()
{
$.ajax(
{
post: 'GET',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: "firstName" + $('myFirstName').val() + "&lastName" + $('myLastName').val(),
url: 'UtilitieService.asmx/TestGetParametersDynamic',
success: function (result)
{
var test = result.d;
var outputDiv = $('outputGET3');
outputDiv.html(test);
},
error: function ()
{
alert('Fail Test Get Dynamic');
}
});
}
both times I get this error:
Invalid web service call, missing value for parameter: \u0027firstName\u0027
I hope that you use [ScriptMethod(ResponseFormat=ResponseFormat.Json)] attribute for the web method or set the same information in the web.config in case of the usage .NET 4.0.
It seems to me that your first attempt was almost correct, but you should replace
data: '{"firstName":"' + $('#myFirstName').val() + '","lastName":' +
$('#myLastName').val() + '"}',
to the
data: '{"firstName":"' + $('#myFirstName').val() + '","lastName":"' +
$('#myLastName').val() + '"}',
(the starting double-quote was skipped before the $('#myLastName').val()).
I strictly recommend you don't use manual serialization to JSON. For example if the text from $('#myFirstName').val() or $('#myLastName').val() will have '"' or '\' characters, that the characters must be escaped with additional backslash ('\') (see here). Instead of manual serialization you should use JSON.stringify function from the script json2.js which you can download from the http://www.json.org/js.html or here. In recent web browsers the function are native implemented and json2.js use the native implementation if it take place.
The data parameter of $.ajax could be rewritten as the following:
data: {
firstName: JSON.stringify($('myFirstName').val()),
lastName: JSON.stringify($('myLastName').val())
}
or in some situation even as
data: {
firstName: function() { return JSON.stringify($('myFirstName').val()); },
lastName: function() { return JSON.stringify($('myLastName').val()); }
}
For more information see this old answer and probably also this.
UPDATED: Sorry the correct version without the usage JSON.stringify could be without the data usage:
url: 'UtilitieService.asmx/TestGetParametersDynamic?firstName=' +
encodeURIComponent('"' + $('#myFirstName').val() + '"') +
'&lastName=' + encodeURIComponent('"' + $('#myLastName').val() + '"')
I strictly recommend you to use always only the JSON.stringify version which I described above.
Your first attempt is passing the paramaters as a json string.
Your second attempt is missing = signs.
You can pass a object to data, and jQuery will serialize it properly.
$.ajax(
{
post: 'GET',
data: {
firstName: $('myFirstName').val(),
lastName: $('myLastName').val()
},
...
Pass multiple parameters using json
data: "{'RecomendeeName':'" + document.getElementById('txtSearch').value +
"'," + "'tempdata':'" +"myvalue" + "'}",