AJAX: parameters is always null XML format - javascript

I have created a [WebMethod] in my server side as shown below:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Xml)]
public string ReadComments(string pagenum)
{
return pagenum;
}
and the ajax code:
function GetCommentItems() {
var pageTrack = $("input[id$='pageTrack']").val();
$.ajax({
url: "/_layouts/15/Load5MoreComments/CommentFetchSvc.asmx",
type: "POST",
dataType: "xml",
beforeSend: function (xhr) { xhr.setRequestHeader('SOAPAction', 'http://tempuri.org/ReadComments'); },
data: '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><ReadComments xmlns="http://tempuri.org"><pagenum>testStr</pagenum></ReadComments></soap:Body></soap:Envelope>',
contentType: 'text/xml; charset=utf-8',
success: function (msg) {
console.log(msg);
var newPageTrack = $("input[id$='pageTrack']").val();
$("input[id$='pageTrack']").val(parseInt(newPageTrack) + 1);
},
error: function (xhr, msg) {
console.log(msg + '\n' + xhr.responseText);
}
});
}
I am passing a testStr as a parameter but it goes always null.
I tried this processData: false, but did not work
Please help me!

Related

Ajax success event doesn't fire

Doing Okta Authentication on WebForms
The login works but the redirect part doesnt
I tried with void and to return json object/string but doenst work
if i delete contentType and dataType from ajax method the success event works but then i can't debbug the method and it wasn't doing what was suppose to do
My objective is at the end of the webmethod to redirect to SignedIn.aspx tried with this code but couldn't make it work either that's why im doing client side through ajax success method
HttpContext.Current.Response.Redirect("SignedIn.aspx");
Ajax:
function FormSubmit() {
$.ajax({
type: "POST",
url: "Example.aspx/Login",
data: "{hiddenSessionTokenField:'" + $('#hiddenSessionTokenField').val() + "'}",
dataType: "json",
async:false,
contentType: "application/json; charset=utf-8",
success: function (response) {
alert("Method Called Sucessfully" + response);
window.location.href = "http://localhost:8080/SignedIn.aspx";
},
error: function (response) {
alert("error " + response);
}
});
}
WebMethod
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static void Login(string hiddenSessionTokenField)
{
//var result = new { url = "http://localhost:8080/SignedIn.aspx" };
if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
var properties = new AuthenticationProperties();
properties.Dictionary.Add("sessionToken", hiddenSessionTokenField);
properties.RedirectUri = "~/SignedIn.aspx";
//Okta Authentication
HttpContext.Current.GetOwinContext().Authentication.Challenge(properties,
OpenIdConnectAuthenticationDefaults.AuthenticationType);
//System.Web.Script.Serialization.JavaScriptSerializer s = new System.Web.Script.Serialization.JavaScriptSerializer();
//return s.Serialize(result));
}
//return s.Serialize(result));
}
$('#test').on('click', function () {
$.ajax({
type: "POST",
url: "TEST.aspx/Login",
data: "{hiddenSessionTokenField:'" + $('#hiddenSessionTokenField').val() + "'}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
// alert("Method Called Sucessfully");
window.location.href = "http://localhost:8080/index.aspx";
},
error: function (response) {
alert("error " + response);
}
});
})
public static void Login(string hiddenSessionTokenField) {
int x = 0;
}

Unable to call controller method from js

[HttpPost]
[Route("mapchanged")]
public ActionResult mapchanged(string latitud, string longitud)
{
Session["Latitude"] = latitud;
Session["Longitude"] = longitud;
return RedirectToAction("search?what=&by=bnm");
}
$.ajax({
type: "POST",
async: false,
url: url, // '#Url.Action("mapchanged")',
data: {
latitud: map.getCenter().lat(),
longitud: map.getCenter().lng()
},
dataType: "json",
contentType: 'application/json; charset=utf-8',
cache: false,
success: function(data) {
alert('Success');
},
error: function(err) {
alert('error = ' + err.status);
}
});
The above code is not working - it's giving error 404. Also tried var url = '"Home/mapchanged/"' but it's also not working. The ajax code is in map.js file.
Do you have a view for that action? Plus it's an ajax post, you can't redirect to another action while doing ajax post. Try to return json from that action and see if it works.
return Json(new { true }, JsonRequestBehavior.AllowGet);
I tried to reproduce source code. It had some issues with current code.
Missed configure for Route attribute at RouteConfig class, without this configure [Route] annotation/attribute not work.
routes.MapMvcAttributeRoutes()
In ajax call did not use JSON.stringify for data
var data = {
latitud: map.getCenter().lat(),
longitud: map.getCenter().lng()
};
$.ajax({
type: "POST",
async: false,
url: '#Url.Action("mapchanged")',
data: JSON.stringify(data),
dataType: "json",
contentType: 'application/json; charset=utf-8',
cache: false,
success: function (data) {
alert('Success');
window.location.href = data.url;
},
error: function (err) {
alert('error = ' + err.status);
}
});
You should return Json object with url property instead of RedirectToAction
[HttpPost]
[Route("mapchanged")]
public ActionResult mapchanged(LongLat obj)
{
Session["Latitude"] = obj.latitud;
Session["Longitude"] = obj.longitud;
//return RedirectToAction("search?what=&by=bnm");
return Json(new {url = "search?what=&by=bnm"});
}
public class LongLat
{
public double latitud { get; set; }
public double longitud { get; set; }
}

Why does web service not return string properly?

I have ajax function that send some string to webservice.
Here is ajax:
var data = "wkt=" + wkt;
$.ajax({
url: "....some path",
type: "POST",
data: data,
crossDomain: true,
dataType: "text",
success: function (response) {
alert(response);
},
error: function () {
console.log('Request Failed.');
}
});
And here is web service:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class ValveService : System.Web.Services.WebService
{
[WebMethod]
public string ExecuteQuery(string wkt)
{
return "dummy!";
}
}
As response I get this string:
"<?xml version="1.0" encoding="utf-8"?><string xmlns="http://tempuri.org/">dummy!</string>"
While I expect to get as response "dummy!".
Any idea why I get this strange responce and how to get only string that was sent from service(in my case "dummy!") ?
I'm pretty sure web services only return xml or json. There might be a way around it, setting a response type in the service but I'm not sure. [Edit: I see Nerdi.org already hinted at this.]
When dataType: 'text', the response header is not just text, but Content-Type: text/xml; charset=utf-8, and you get xml.
Go for json (which is a string) and work with that.
//var data = "wkt=" + wkt;
$.ajax({
url: "/path to/ExecuteQuery",
type: "POST",
data: JSON.stringify({ wkt: wkt }),
contentType: "application/json; charset=utf-8", // this will be the response header.
crossDomain: true,
dataType: "json",
success: function(response) {
// response is a wrapper. your data/string will be a value of 'd'.
alert(response.d);
},
error: function() {
console.log('Request Failed.');
}
});
An alternative:
[WebMethod]
public void ExecuteQuery(string wkt)
{
Context.Response.Output.Write("dummy " + wkt);
Context.Response.End();
}

JavaScript POST falls when connect to MVC controller

I'm new in MVC and trying to create a site for training.
I need to call a POST method in my controller through JavaScript.
This is my JavaScript method:
function ActivateAddStarAndRoleWithCategories(sender, args) {
var discID = $('#DiscID').val();
var starID = $('#StarID').val();
var desc = $("#Description").val();
var strID = "";
$(':checkbox').each(function () {
strID += this.checked ? this.id + "," : "";
});
strID = strID.substr(0, strID.length - 1);
$.ajax({
type: "POST",
url: 'CreateCategoriesID',
contentType: "application/json; charset=utf-8",
data: {
discID: discID,
starID: starID,
description: desc,
catID: strID
},
dataType: "json",
success: function () { alert("success!"); },
error: function () { alert("Fail!"); }
});
}
And this is my method in the controller:
[HttpPost]
public ActionResult CreateCategoriesID(string discID, string starID, string description, string catID)
{
entities.AddStarAndRoleAndCategories(int.Parse(starID), description, int.Parse(discID), catID);
return Json("OK", JsonRequestBehavior.AllowGet);
}
The view that activates the JavaScript function is already connected to the controller.
I always get error 500 - the server responded with a status of 500.
What am I doing wrong?
Thank you in advance!
I would go with the examples from the jQuery docs.
Did you try something like...?
$.ajax({
method: "POST",
url: "CreateCategoriesID", // Insert your full URL here, that COULD be the problem too
// This contentType is the default, so we can just ignore it
//contentType: "application/x-www-form-urlencoded; charset=UTF-8",
// I would also ignore the dataType unless your backend explicitly sends a JSON response header
//dataType: "json",
data: {
discID: discID,
starID: starID,
description: desc,
catID: strID
}
}).done(function(msg) {
alert('Success with message: ' + msg);
}).fail(function(jqXHR, textStatus) {
alert('Failed with status: ' + textStatus);
});

GetCitiesByRegion is not defined?

I have a page, and i've got a link looking like:
<span>Nordjylland</span>
And in my Javascript file, i've got a function called GetCitiesByRegion(), however, when clicking the link, i get an error, saying that GetCitiesByRegion is not defined?
The function looks like this:
function GetCitiesByRegion(id) {
var params = '{"id":"' + id + '"}'
var request = {
type: "GET",
async: false,
cache: false,
url: "http://" + location.hostname + "/webservices/services.svc/GetCitiesByRegion",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: params,
success: function (result) {
alert("Data Loaded: " + result);
},
error: function (xhr, status, error) {
alert('Fejl ved webservice: error: ' + error);
}
};
$jq.ajax(request);
}

Categories

Resources