I have a simple set up.
Jquery:
$.ajax({
url: "/MyApp/MyHandler.ashx/MyMethod",
success: function(result) {
alert("sucess");
},
error: function() {
alert('Error');
}
});
and web method:
[System.Web.Services.WebMethod]
public static void MyMethod(){
new AnotherClass(null).AnotherMethod(null, null);
}
problem is success alert is called but break point is not hit inside MyMethod.
I had the same issue and this is what I ended up having to do:
$.ajax({
url: _url,
data: '',
dataType: 'json',
contentType: 'application/json',
type: 'POST',
success: function(result) {
alert("sucess");
},
error: function() {
alert('Error');
}
});
My first attempt left out the data, dataType and contentType; Only when I set contentType: 'application/json' with an empty string (data: '') did it end up working. What a headache - hope this helps someone else!
In my case, the issue was in RoutingConfig.So, sort that in App_Start folder, within RouteConfig,commented out the following line
//settings.AutoRedirectMode = RedirectMode.Permanent;
Related
This is my aspx page code
function grid(datas)
{
var datass = {datas: datas};
var myJSON = JSON.stringify(datass);
$.ajax({
url: 'EditCustomerBills.aspx/LoadGrid',
method: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: myJSON,
success: function (data) {
alert("Success");
},
error:function(error){
alert("failed");
}
});
}
and this is my behind code
[WebMethod]
public static string LoadGrid(string datas)
{
//GetCustomerBillDetail(data);
string datass = datas.ToString();
return datass;
}
I'm using code perfectly, but output is failed. I'm struggling for four days. please help me. thank you.
I don't know what is your "myJSON" is . according to me your code should be sometinhg like this.
[System.Web.Services.WebMethod]
public static string GetCurrentTime(string datas)
{
return "Hello " + datas + Environment.NewLine + "The Current Time is: "
+ DateTime.Now.ToString();
}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
<script type = "text/javascript">
function ShowCurrentTime() {
$.ajax({
type: "POST",
url: "CS.aspx/GetCurrentTime",
data: '{datas: "Your Data" }', // your data should be here.
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function(response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
</script>
below picture will give you a idea how we can call the server side method.
for more reference please see this.
edit as follows and share with f12 in console output?
error: function (error) {
console.log(error);
}
I write an application with speech recognition. All I want is to record some speech and send it to server where I will convert it into text. And I have a problem with sending that sound file. I record voice using p5.js library and when I try to download it there is no problem.
The problem is when I try to send it to server using ajax.
script.js
function toggleRecording(e) {
if (e.classList.contains("recording")) {
recorder.stop();
e.classList.remove("recording");
sendAudioToServer(soundFile)
} else {
e.classList.add("recording");
recorder.record(soundFile);
}
}
function sendAudioToServer(soundFile)
{
var data = new FormData();
data.append('fname', 'test.wav');
data.append('data', soundFile);
console.log(soundFile);
console.log(data);
$.ajax({
type: 'POST',
url: '/recognizeCommand',
data: data,
dataType: 'jsonp',
processData: false,
contentType: false,
success: function(data) {
alert("works!");
},
error: function() {
alert("not works!");
}
})
Java controller
#PostMapping("/recognizeCommand")
public #ResponseBody String recognizeCommand(#RequestParam MultipartFile mpf) {
try {
byte[] bytes = mpf.getBytes();
SpeechRecognitionApplication.logger.info(bytes);
} catch (IOException e) {
e.printStackTrace();
}
return "finish";
}
When I stop recording regardless to toggleRecording function it should stop recording and send it to server. And there is a problem with sendAudioToServer function. Here is the result from Chrome console:
I'm not sure but there is probably problem with FormData. As you can see when I printed it in console it's empty. Founded some similar questions here but there is no solution to solve my problem.
EDIT:
After add dataType: 'jsonp'
There is that error:
EDIT 2:
After adding csrf token:
Please add csrf tokens as this.
<meta name="_csrf" th:content="${_csrf.token}"/>
<meta name="_csrf_header" th:content="${_csrf.headerName}"/>
In header:
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
Set headers.
$.ajax({
type: 'POST',
url: '/recognizeCommand',
data: data,
dataType: 'json',
processData: false,
contentType: false,
beforeSend: function(xhr) {
// here it is
xhr.setRequestHeader(header, token);
},
success: function(data) {
alert("works!");
},
error: function() {
alert("not works!");
}
})
Try adding debug point here.
SpeechRecognitionApplication.logger.info(bytes);
Try adding dataType: 'jsonp' to your $.ajax call like,
$.ajax({
type: 'POST',
url: '/recognizeCommand',
data: data,
dataType: 'jsonp',
processData: false,
contentType: false,
success: function(data) {
alert("works!");
},
error: function() {
alert("not works!");
}
})
Hope this helps!
I'm attempting to trigger a code behind method from AJAX:
function onEnter(key) {
var lotTxt = document.getElementById("lotTxt");
if (key.keyCode == 13) {
alert("in if")
$.ajax({
url: 'Default.aspx/assEatinSzn',
type: "POST",
contentType: 'application/json; charset=utf-8',
data: { test: "testString"},
dataType: 'json',
success: function (data) {
alert("Success")
},
failure: function (data) {
alert("Failure")
}
});
}
}
All I am attempting to do in the code behind is update this text box with the value below:
Public Sub assEatinSzn(test As String)
productTxt.Value = "Success"
End Sub
Essentially I am asking why the ajax is not triggering the code behind method. I have put break points to see if the the code behind method is ever triggered, but nothing ever breaks. The ajax method will produce the complete function as well in a weird side effect. Thanks in advance
The problem is you are not passing a value for the test parameter.Hope the below code will solve your issue :
type: 'POST',
url: 'default.aspx/assEatinSzn',
data: JSON.stringify({ test: 'value here' }),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
}
......
And make sure to add [WebMethod] before your method :
[System.Web.Services.WebMethod]
Public Shared Sub assEatinSzn(test As String)
productTxt.Value = "Success"
End Sub
JS:
function showComments(couponId) {
var jsontxt = JSON.stringify({ couponId });
$.ajax({
type: "POST",
url: "<% =Page.ResolveUrl("~/Admin/UserCoupons.aspx/GetComments") %>",
data: jsontxt,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
//async:true,
success: function (result) {
alert("We returned: " + result.d);
},
failure: function (response) {
alert(response.d);
}
});
}
C#:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string GetComments(string couponId)
{
//will return precomipled generated html for display in div
return "Success";
}
The C# code is in page's code behind .cs file
i have solved this all before using stack over flow
thanks to experts here.
but this time there is some thing else
i am getting my debug pointer in page_load method then in master page's page load method. but debug doesn't enters to the GetComments
and getting exception
Unknown web method GetComments.
Parameter name: methodName
Below is the stackTrace
at System.Web.Script.Services.WebServiceData.GetMethodData(String methodName)
at System.Web.Script.Services.RestHandler.CreateHandler(WebServiceData webServiceData, String methodName)
at System.Web.Script.Services.RestHandler.CreateHandler(HttpContext context)
at System.Web.Script.Services.RestHandlerFactory.GetHandler(HttpContext context, String requestType, String url, String pathTranslated)
at System.Web.Script.Services.ScriptHandlerFactory.GetHandler(HttpContext context, String requestType, String url, String pathTranslated)
at System.Web.HttpApplication.MaterializeHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Your data in ajax should be JSON.stringify({ couponId:'123' }) //parameter name & value.
function showComments(couponId) {
var jsontxt = JSON.stringify({ couponId:'123' });
$.ajax({
type: "POST",
url: "<% =Page.ResolveUrl("~/Admin/UserCoupons.aspx/GetComments") %>",
data: jsontxt,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
//async:true,
success: function (result) {
alert("We returned: " + result.d);
},
failure: function (response) {
alert(response.d);
}
});
}
after a long google and all others and applying every possible solutions. finally, i found a solution. and that's
edit the file at ~/App_start/RouteConfig.cs
replace
settings.AutoRedirectMode = RedirectMode.Permanent;
with
settings.AutoRedirectMode = RedirectMode.Off;
this solved my problem. any ways thanks to all who took interest and showed their generosity.
I have a REST API and I am wanting to invoke it from my ajax javascript client.
I make the call and nothing happends. My mobile browser just indicates 'busy'.
No error is returned.
This is my code behind:
[HttpPost]
[Route("Services/Image/Validate")]
public byte Validate(string KeyCode)
{
return 1;
}
this is my JavaScript client:
$("#btnValidate").click(function () {
try {
var url = "http://MY_DOMAIN_NAME/api/Services/Image/Validate";
$.ajax({
type: 'POST',
url: url,
data: '{ "KeyCode" : "' + $("#KeyCode").val() + '" }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
$('#divStep1').hide();
$('#divStep2').show();
},
fail: function (a) {
$("#error").html(objRequest);
}
});
}
catch (ex)
{
$("#error").html(ex);
}
return false;
});
The catch function with throw an error only when the HTTP request fails. In Order to know wha'ts going wrong in the server side code you need to use the error function in the ajax request,
You also mentioned that the browser does nothing and this might happen due to
jQuery plugin not included in the page (check console for $ is not defined)
Add the jquery plugin above your javascript
If your server side code is on a different domain enable CORS
$("#btnValidate").click(function () {
var url = "http://MY_DOMAIN_NAME/api/Services/Image/Validate";
$.ajax({
type: 'POST',
url: url,
data: '{ "KeyCode" : "' + $("#KeyCode").val() + '" }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
$('#divStep1').hide();
$('#divStep2').show();
},
error: function (e) {
console.log(e.responseText); //Acutal error
console.log(e); //Get the entire error details
}
});
});
The settings object you are sending to $.Ajax() does not expect a fail parameter. Maybe you are confusing promises?
Anyway, it should probably be error.
eg.
$("#btnValidate").click(function () {
try {
var url = "http://MY_DOMAIN_NAME/api/Services/Image/Validate";
$.ajax({
type: 'POST',
url: url,
data: '{ "KeyCode" : "' + $("#KeyCode").val() + '" }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
$('#divStep1').hide();
$('#divStep2').show();
},
error: function ( jqXHR, textStatus, errorThrown) {
$("#error").html(textStatus);
}
});
}
catch (ex)
{
$("#error").html(ex);
}
return false;
});
Also, I'm not sure if you should have the data property as a string but maybe this is how you want it.
All documentation on this is HERE