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.
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.
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);
}
});
});
I have a problem with this.
below are my jquery code and aspx.cs code.
I should send $('#UserID').val() to WebMethod as a parameter.
but in WebMethod it is always null.
if I change $('#UserID').val() to any string, it works well.
#UserID is correct. because I made a alert window with this value.
and.. I already changed data: '{userId: "' + $('#UserID').val() + '"}',
to data: JSON.stringify({ userId: $('#UserID').val() }).
but nothing works.
$.ajax({
url: "register.aspx/IsIdAvailable",
type: "post",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: '{userId: "' + $('#UserID').val() + '"}',
dataFilter: function (data) {
var msg = JSON.parse(data);
if (msg.hasOwnProperty('d'))
return msg.d;
else
return msg;
}
})
[WebMethod]
public static bool test(string userId)
{
System.Diagnostics.Trace.WriteLine("userId: " + userId +"!");
...
}
output is always userId: !
Try changing your data attribute to something like:
data: {'userId': $("#UserID").val()}
I am using the below code to call a ashx page. But it's not working for me. I have place my code here. I always got the error message message "Request Failed". Please help me..
<script type="text/javascript">
function CallLoginHandler(user, pass) {
alert(user);//Got value
alert(pass);//Got Value
$(function(){
$.ajax({
type: "POST",
url: "../handler/JQGridHandler.ashx?MainPage=GetUserDetails&Type=2&user=" + user + "&pass=" + pass + "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnComplete,
error: OnFail
});
return false;
});
}
function OnComplete(result) {
alert([result.Id, result.Name, result.Age, result.Department]);
}
function OnFail(result) {
alert('Request Failed');
}
</script>
remove these lines:
$(function(){ // <----remove this
return false; // and this
}); // and this too
Update to this function:
function CallLoginHandler(user, pass) {
$.ajax({
type: "POST",
url: "../handler/JQGridHandler.ashx", // updated url
data: { // pass your data like this since type is post
MainPage:"GetUserDetails",
Type:2,
user:user,
pass:pass
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnComplete,
error: OnFail
});
}
and also your url is not correct:
url: "../handler/JQGridHandler...... + pass + "",
// --here you have a blank `""` after pass-----^
and since your type: "post" so you can pass the data like this:
data: {
MainPage:"GetUserDetails",
Type:2,
user:user,
pass:pass
},
Separate your string into a javascript object to be encoded and sent to the server as JSON based on your content type. Also, get rid of $(function(){ in your function call, it's useless here.
$.ajax({
type: "POST",
url: "../handler/JQGridHandler.ashx';
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {
MainPage: 'GetUserDetails',
Type: 2,
user: user,
pass: pass
}
success: OnComplete,
error: OnFail
});
If this doesn't work, then the issue is likely one of the following:
The URL address is wrong
The server is evaluating a GET as opposed to a POST request
The server expects, application/x-www-form-urlencoded but you've declared it's json
You have a routing issue
Note: Do not send your user and pass in query string.
function CallLoginHandler(user, pass) {
$.ajax({
type: "POST",
url: "../handler/JQGridHandler.ashx",
data: {
MainPage: 'GetUserDetails',
Type: 2,
user: user,
pass: pass
},
// 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: OnComplete,
error: OnFail
});
});
}
Your handler.ashx file
using System;
using System.Web;
using Newtonsoft.Json;
public class Handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string user= context.Request.Form["user"];
//.....
var wrapper = new { d = myName };
// in order to use JsonConvert you have to download the
// Newtonsoft.Json dll from here http://json.codeplex.com/
context.Response.Write(JsonConvert.SerializeObject(wrapper));
}
public bool IsReusable
{
get
{
return false;
}
}
}
source
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'. :)