I want to post data to a web service with ajax. there is my ajax code:
function Looping() {
var Grid = document.getElementById("<%= gvHastalar.ClientID %>");
var Row;
var Cell;
if (Grid.rows.length > 2) {
for (i = 1; i < Grid.rows.length - 1; i++) {
Row = Grid.rows[i];
Cell = Row.cells[3];
alert(Cell.innerHTML);
var html = $.ajax(
{
type: "POST",
url: "http://localhost:7753/HastaTahlilUyariServisi.asmx/f_HastaninAktarilacakAlislabTestleri",
data: "{_sTcKimlikNo:" + Cell.innerHTML + ",_iKlinikKodu:18001,_bAy:12,_iYil:2009}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: alert('success'),
error: alert('error')
}
).responseText;
Row.style.backgroundColor = "#D3EFD1";
}
}
}
And my webservice function's code is here:
[WebMethod]
[SoapHeader("_ticket", Direction = SoapHeaderDirection.In)]//SoapHeaderDirection.Out
public DataSet f_HastaninAlisLabTahlilleri(string _sTcKimlikNo, int _iKlinikKodu, byte _bAy, int _iYil)
{
try
{
string QSelect =
#"SELECT * FROM [V_EUCLID_SONUC]
WHERE MONTH(KAYITTARIHI) = " + _bAy + #"
AND YEAR(KAYITTARIHI) = " + _iYil +
AND TCKIMLIKNO = '" + _sTcKimlikNo + #"'";
return dbA.ExecuteDataSet(CommandType.Text, QSelect);
}
catch (Exception ex)
{
throw (ex);
}
}
There is a break point on function which is in the web service but debug never go that break point. I pasted webservice's url from browser but may be url is wrong. And when i run project, i have 3 alert.
First Cell's text its normal.Second alert is success and the last alert is error. I want to send parameters to f_HastaninAlisLabTahlilleri and user return dataset. How can i do this?
Thanks in advance
Here are a few remarks about your code:
success and error are callback functions, they should be defined like this:
success: function(data) { alert('success'); },
error: function(XMLHttpRequest, textStatus, errorThrown) { alert('error'); }
ASMX web services use SOAP by default unless you decorate them with ScriptServiceAttribute in which case JSON could be used to invoke a method. It is not clear from your code if the web service is decorated with this attribute.
When you pass parameters, you need to encode them, use JSON. stringify instead of concatenating strings:
data: JSON.stringify({_sTcKimlikNo: Cell.innerHTML,
_iKlinikKodu: 18001,
_bAy: 12,_iYil: 2009});
Use FireBug to inspect network AJAX requests and server responses and post them on StackOverflow to facilitate debugging.
You cannot put a break-point in the web-service code i.e. even the IDE would not let u debug the web-service code.... it is an old legacy the VS.Net IDE has since its inception... lets see if it is resolved in VS 2010.
The url that you have specified in the JQuery script is not equal to the name of the function in c# code. Isn't it the point. *f_HastaninAktarilacakAlislabTestleri* in url and *f_HastaninAlisLabTahlilleri* in c# code. Some reasons for such a problem can be wrong url or deference between argument list of client request and argument list of the server side method or action.
Related
This was working 2 days ago and now it's not and I cannot figure out why. I am submitting form data via ajax:
var mData = 'item=' + itemid + '&action=' + action;
$.ajax({
url: "/Admin/Home/Ajax",
type: 'POST',
contentType: 'application/x-www-form-urlencoded',
data: mData,
success: function (data) {
//Do Something
}
});
I have a method that process the incoming post:
if (HttpContext != null && HttpContext.Request.HasFormContentType)
{
foreach (var key in HttpContext.Request.Form.Keys)
{
QueryParams.Add(key, HttpContext.Request.Form[key]);
}
}
When the data is posted, HttpContext.Request.HasFormContentType is equal to true however, HttpContext.Request.Form.Keys.Count is equal to 0
I get no errors or anything. Any help or insight as to what is going on would be greatly appreciated.
This is a dotnet core 2.2 mvc web app.
Here is a working demo like below:
1.View:
<script>
var mData = 'item=' + 1 + '&action=' + "aaa";
$.ajax({
url: "/Home/Ajax",
type: 'POST',
contentType: 'application/x-www-form-urlencoded',
data: mData,
success: function (data) {
//Do Something
}
});
</script>
2.Action:
[HttpPost]
public void Ajax(int item,string action)
{
if (HttpContext != null && HttpContext.Request.HasFormContentType)
{
foreach (var key in HttpContext.Request.Form.Keys)
{
}
}
}
3.Result:
You are sending query data, not form data. Try sending it in a form like:
{
item: ...,
action: ...
}
Edit: Actually I was a bit surprised that it works while sending raw type of data and then passing in the query-like string. But the mearly fact that it works it doesn't mean it is a proper way of doing things. Foe example if You try to send API request from Postman (which I tried to reproduce Your error) I wasn't even able to perofrm such a thing as Postman asked me for key value pairs and interpreted a given query as a one key. Besides sending js object is more simpler that building a string.
I was also facing the issue of HttpContext.Request.Form.Keys is empty.
I just removed the .aspx extension from the request page and now the problem seems to be resolved for me.
I have a web application with a few cascading dropdown lists. So I use ajax to update the value of the next dropdown list. I put the javascript script in a separate file.
// Code that triggers when there is a change in Activity drop down.
$('#ActivityId').change(function () {
var activityId = $(this).val();
// Empty the Workstation.
$('#WorkstationId').empty();
$('.showhide-workstation').show();
var url = "~/WorkOrderSubmissions/GetWorkstationsByActivityJson";
// AJAX call that re-populate Workstation drop down depending on the Activity selected.
$.ajax({
type: 'POST',
url: url,
dataType: 'json',
data: { activityId: activityId },
success: function (codes) {
$('#WorkstationId').append('<option value=""></option>');
$.each(codes, function (i) {
$('#WorkstationId').append('<option value = "' + codes[i].Value + '">' + codes[i].Text + '</option>');
});
},
error: function (ex) {
$('#WorkstationId').append('<option value=""></option>');
}
}); // END $.ajax() on GetRejectCodesByActivityJson
}); // END $('#ActivityId').change()
The code works when I run it from inside Visual Studio. It does not work when I deploy it to my local web server. I deploy it to
http://localhost/mea
When I open Developer Tools in Chrome, I see the error.
POST http://localhost/~/WorkOrderSubmissions/GetLinesByWorkorderJson 404 (Not Found)
I tried to to change the url to
url = ~/WorkOrderSubmissions/GetLinesByWorkorderJson
url = /WorkOrderSubmissions/GetLinesByWorkorderJson
url = WorkOrderSubmissions/GetLinesByWorkorderJson
None of them work. I thought ~ is supposed to go to the root of the web application, which is http://localhost/mea.
The ~ syntax is only recognised by ASP.Net; it will be taken literally by any JS code. You need to provide the URL via your C# code to JS:
var url = '#Url.Content("~/WorkOrderSubmissions/GetWorkstationsByActivityJson")';
Or better yet:
var url = '#Url.Action("GetWorkstationsByActivityJson", "WorkOrderSubmissions")';
I have an ASP.NET application sending data through AJAX to a handler withing my application. This works as it should when debugging locally, but as soon as I deploy the solution to the server, the handler only receives an empty string. I tried fiddling around with contentType and dataType, but without luck.
Here is my code so far.
aspx of the sending page, while "myData" is a simple string:
$.ajax({
type: "POST",
url: "handlers/changeRiskGroup.ashx",
data: myData,
// tried all those content/dataTypes without any luck
//contentType: "text/plain",
//dataType: "text",
//contentType: "application/json; charset=utf-8",
//dataType: "json",
error: function (xhr, status, error) {
console.log(xhr.responseText);
},
success: function (msg) {
console.log(msg);
}
});
.ashx.cs of the receiving handler:
public void ProcessRequest(HttpContext context) {
//string data = new StreamReader(context.Request.InputStream).ReadToEnd();
var data = String.Empty;
context.Request.InputStream.Position = 0;
using(var inputStream = new StreamReader(context.Request.InputStream)) {
data = inputStream.ReadToEnd();
}
if (data != "") {
// doing something with my data here.
// this is never reached while on the server, but works fine locally!
} else {
context.Response.Write("Please supply data to the risk group service!");
}
}
public bool IsReusable {
get {
return false;
}
}
}
The data variable in the .ashx.cs file is filled when debugging locally, but always "" on the server. I have no clue why.
var para={};
para.myData="abcd"
$.ajax({
type: "POST",
url: "handlers/changeRiskGroup.ashx",
data: para,
error: function (xhr, status, error) {
console.log(xhr.responseText);
},
success: function (msg) {
console.log(msg);
}
});
from server side
string myData=contect.Request.Form["myData"].toString();
Easy, just took me ~20 hours to figure out. Found the answer here: Web service returns "301 error moved permanently" in production environment
In short, I created a blank page within my project to ensure no plugins etc were interfering with the jQuery execution. Further, I created a very simple mask to submit certain data to the handler URL. Within this mask I varied different ways to POST data, when I tried implementing the POST as a [WebMethod] I finally got a clue, as the response was "301 moved permanently" from the WebMethod. Therefore I could start investigating and found out that my server was lowercasing the urls, obviously jQuery/HTTP does not like that.
I hope this post helps others struggling with similar problems.
I want to get data from Webservice( Soap), but it not successfull. My service herehttp://icafe.ipos.vn/WSUitility/evsServiceUtility.svc?wsdl
I use jquery to request to service, code below
var soap = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
"<soap:Body>" +
"<Test xmlns=''>" +
"</Test>" +
"</soap:Body>" +
"</soap:Envelope>";
$.ajax({
url: 'http://icafe.ipos.vn/WSUitility/evsServiceUtility.svc?wsdl',
method: 'post',
data: soap,
contentType: "text/xml",
dataType: "xml",
beforeSend: function (xhr) {
xhr.setRequestHeader("SOAPAction", "urn:evsServiceUtility/Test1");
},
crossDomain: true,
success: function(SOAPResponse) {
alert('ok');
},
error: function(SOAPResponse) {
alert('no ok');
}
});
And my service:
public string Test()
{
try
{
return "Successfull!";
}
catch (Exception ex)
{
return ex.Message;
}
}
I spended many many times to search and try many solutions but it not working.
Can anyone help me?
I suppose your data type can be XML, not a problem there. Question is, how do you encode your data or parameters? Perhaps check the response in the POST request in the console of your browser.
I picked up a few things in c# to enable this automatically which is nicely documented here:
http://encosia.com/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax/
Then one thing left to do was to JSON.stringify() the data. So bhRequest is a json object right?
... and then cross browser you'll have to implement json2.js:
https://github.com/douglascrockford/JSON-js
I don't see where your var named soap is being used. It looks like it should be the "data: " that's being sent to the SOAP service, but there's something called bhRequest there instead.
Also make sure you're allowing Phonegap access to your remote server with
<access subdomains="true" origin="*" />
in your config.xml. When you get things working you can make it more restrictive by limiting it to your icafe.ipos.vn domain.
[I realise this might seem like a stupid question but I am lost.]
Using umbraco 4.9 I have a multi-lingual site where I have made an event handler to replicate content nodes to all languages as they are created in the back office to all languages. I am now trying to attach this to a custom context menu item(umbraco.interfaces.IAction) to give the creator a choice.
In the context menu item it is only possible to call a javascript function as a string. I shouldn't touch the umbraco code itself so how can I pass a value to a web service? Where do I include the reference?
This is what I have at the moment:
public string JsSource
{
get
{
return "function AddItem(){" +
"var multiLang = confirm('Create for all languages?');" +
//"$.ajax({" +
//"type: 'Post'," +
//"url: 'TryAgain.aspx/' + SendMultiVal" +
//"data: multiLang})" +
//"PageMethods.SendMulti(multiLang);}" +
string.Format("{0}.actionNew()", ClientTools.Scripts.GetAppActions)+"};";
}
}
Thanks in advance.
So the first thing that you need to do is to store the boolean value in a variable called boolvalue and then call the callservice function once you have the value.For eg:
CallService("POST", "YourServiceUrl",boolvalue,
function (data) {
alert("Service Call Success");
},
function (result) {
alert('Service call failed: ' + result.status + '' + result.statusText);
});
This will make a service call and get data from service if it returns some data.
CallService = function (method, serviceUrl, value, successHandler, errorHandler) {
$.ajax({
type: method,
url: serviceUrl,
contentType: "application/text; charset=utf-8",
dataType: "json",
data:JSON.stringify(value),
success: successHandler,
error: errorHandler
});
};
Modify the dataType and dataType fields depending upon the type of data that you send and receive from the service.
Look into this if you need more information:
http://api.jquery.com/jQuery.ajax/
Let me know if this works out for you.