Ajax never calls my .NET method? - javascript

Hi I have the following AJAX which references a method in my .aspx page. I've done some console debugging and my data.d is always undefined. So I've put a breakpoint in the .aspx page on the first line of the method referenced and it never hits it.
I'm really stuck - so if someone could point me in the right direction that would be great.
AJAX:
var param = { "mySearchString": str };
$.ajax({
type: 'POST',
url: 'myForm.aspx/myMethod',
data: JSON.stringify(param),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
success: function (data) {
$("#MyResults").empty();
console.log(data);
console.log(data.d);
console.log(data.d.length);
for (i = 0; i < data.d.length; i++) {
$("#MyResults").append("<li><a href='#' onClick='SetName(this)'>" + data.d[i].title + "</" + " a>" + "</" + "li>");
}
if (data.d.length == 0)
{
$("#MyResults").empty();
}
}
});
The initial set up for my .NET method:
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[WebMethod(EnableSession = true)]
public static IEnumerable<MyItem> myMethod(string searchString)
{
I'm passing the right type across, and there are no errors on build or when I run it. So I'm a bit stumped!

Add this to your ajax call to see more about the error:
error: function (request, status, error) {
alert('Error: ' + error);
}
Is this an MVC application? Should the url actually be myForm.aspx/myMethod or just myForm/myMethod? What I am getting at is have you ever hit a breakpoint on the server side and is the path correct?

Try adding this as part of the signature
[HttpPost]

You can add the below attribute to the class, which enables the web method to be called from an ajax script.
[System.Web.Script.Services.ScriptService]

you have
var param = { "mySearchString": str };
but the parameter in you Method is
public static IEnumerable<MyItem> myMethod(string searchString)
Both parameters should have the same name.

You're passing a string as parameter, you should pass an object with a string attribute named searchString:
var param = { "mySearchString": str };
$.ajax({
type: 'POST',
url: 'myForm.aspx/myMethod',
data: param,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
success: function (data) {
$("#MyResults").empty();
console.log(data);
console.log(data.d);
console.log(data.d.length);
for (i = 0; i < data.d.length; i++) {
$("#MyResults").append("<li><a href='#' onClick='SetName(this)'>" + data.d[i].title + "</" + " a>" + "</" + "li>");
}
if (data.d.length == 0)
$("#MyResults").empty();
}
});

kindly remove the following properties, and remove the JSON.stringfy
contentType: 'application/json; charset=utf-8',
dataType: 'json',
and kindly don't remove the async because it will freeze your UI if you set it to false.
you can do it like this:
$.ajax({
type: 'POST',
url: 'myForm.aspx/myMethod',
data: param,
success: function (data) {
$("#MyResults").empty();
console.log(data);
console.log(data.d);
console.log(data.d.length);
for (i = 0; i < data.d.length; i++) {
$("#MyResults").append("<li><a href='#' onClick='SetName(this)'>" + data.d[i].title + "</" + " a>" + "</" + "li>");
}
if (data.d.length == 0)
{
$("#MyResults").empty();
}
}
});

I found my answer here: ASP.NET Calling WebMethod with jQuery AJAX "401 (Unauthorized)"
I was hitting this error:
Object {Message: Ajax error: "Authentication failed.", StackTrace:
null, ExceptionType: "System.InvalidOperationException"}
Turns out that I needed to do:
Inside ~/App_Start/RouteConfig.cs change:
settings.AutoRedirectMode = RedirectMode.Permanent;
To:
settings.AutoRedirectMode = RedirectMode.Off;
Hopefully this will help someone else!

Related

Unable to display results using jquery ajax

I am trying to implement a comment feature on my page. I have an itemID 123. on that page, I would like to display the comments that people have posted about itemID 123. However as of now, I am unable to display these comments on my page. There are no errors in the console.
Javascript:
function mywall() {
var url = serverURL() + "/viewwall.php"; //execute viewwall.php in the server
itemID = decodeURIComponent(getUrlVars()["itemID"]);
var JSONObject = {
"itemID": decodeURIComponent(getUrlVars()["itemID"])
};
$.ajax({
url: url,
type: 'GET',
data: JSONObject,
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (arr) {
_mywallresult(arr); //success. execute _mywallresult()
},
error: function () {
validationMsg();
}
});
}
function _mywallresult(arr) {
var i;
//for all the shouts returned by the server
for (i = 0; i < arr.length; i++) {
//append the following:
//<b>
//time of posting </b>
//<br/>
//the message
//<br>
//userid
$("#wallcontentset").append("<b>" + arr[i].timeofposting + "</b><br/>" + arr[i].message + "<hr>" + arr[i].userid);
}
}
HTML:
<div data-role="content" class="ui-content" id="wallcontentset"></div>
Try the following :
success: function (response) {
_mywallresult(response.arr);
},

400 bad request for ajax call with GET request parameter passed to controller in spring

i'm showing a drop down list in a page based on the selection i have to show dependent drop down by passing the selected value in drop down list to the controller and return json data as response.please find below code and help me for resolving this .
Please find below ajax code
<script type="text/javascript">
jQuery(document).ready(function () {
$.ajax({
type: 'POST',
dataType : 'json',
contentType : "application/json",
url : "${home}getOPList",
cache: false,
success: function(response){
// var str = JSON.stringify(response);
var operatorList;
// alert("yes");
// alert(str);
for (var i = 0; i < response.length; i++ )
{
console.log(response[i].listOfOperators);
operatorList +="<option value =' "
+ response[i].sno +
" '>"
+ response[i].listOfOperators +
"</option>"
}
$('#opList').html(operatorList);
},
error: function(){
alert('Error while request..');
}
});
$("#opList").change(function(){
$.ajax({
type: 'GET',
dataType : 'json',
contentType : "application/json",
url : "${home}partnerDetails?operator =" +opList,
cache: false,
success: function(response){
// var str = JSON.stringify(response);
var partnerList;
alert("yes");
alert("oplist " + opList);
for (var i = 0; i < response.length; i++ )
{
console.log(response[i].campaignName);
partnerList +="<option value =' "
+ response[i].sno +
" '>"
+ response[i].campaignName +
"</option>"
}
$('#ptList').html(partnerList);
},
error: function(){
alert('Error while request in partners..');
}
});
});
});
</script>
above is the ajax code and when the code gest executed it is directly showing " Error while request in partners.. ".in console it says it is a bad request with 400 response code for the below url.
http://localhost/Promotions/partnerDetails
please suggest on this

How to correctly post data with ajax into div?

Script:
function buttonBuild(id, building, nick)
{
$("#BuildedBox").ajax({
type: "POST",
url: "BlockEditor/build.php",
data: 'block_id=' + id + '&building=' + building + '&nick=' + nick,
cache: false,
success: function(response)
{
alert("Record successfully updated");
$.load("#BuildedBox")
}
});
}
build.php:
include_once("$_SERVER[DOCUMENT_ROOT]/db.php");
$block_id = $_GET['block'];
$building = $_GET['building'];
$nick = $_GET['nick'];
echo"$block_id - $building - $nick";
index.php:
<a href=\"#\" onClick=\"buttonBuild(k152, digger, Name);\" >[BUILD]</a>
<div id="BuildedBox"></div>
seems my script wont work. what i have done wrong?
check this out
function buttonBuild(id, building, nick)
{
$.ajax({
type: "POST",
url: "BlockEditor/build.php",
data: 'block_id=' + id + '&building=' + building + '&nick=' + nick,
cache: false,
success: function(response)
{
alert("Record successfully updated");
/***************/
$("#BuildedBox").html(response);
/***************/
}
});
}
var weightd = $("#weight").val();
var user_id = 43;
$.ajax({
type: "POST",
url:"<?php bloginfo('template_directory')?>/ajax/insert.php",
data: { weight:weightd,user_ids:user_id},
success:function(result){
$("#result1").html(result);
});
<div id="result1">Result div</div>
change $.load("#BuildedBox") to $("#BulderBox").html(response).
When you ask the script for data via ajax, the data provided gets into the "response" variable. As you want to write this data into the div, you must use the ".html" method.
Easier using "load" in this way:
function buttonBuild(id, building, nick)
{
$("#BuildedBox").load("BlockEditor/build.php?block_id=" + id + "&building=" + building + "&nick=" + nick);
}
The "load" method loads data from the server and writes the result html into the element: https://api.jquery.com/load/
EDIT:
As #a-wolff says in the comment, to use POST in load, you should construct like this:
function buttonBuild(id, building, nick)
{
$("#BuildedBox").load("BlockEditor/build.php",{
block_id:id,
building:building,
nick:nick
});
}

$find doesn't work in external javascript file

I have a jQuery code that when click on a button in page, show some information (from database) in a asp:RadEditor.
My code work properly when it's inserted internally in page inside tag , but not working in .js file!
function setShowRow(btn, url) {
$.ajax({
type: "POST",
url: "../" + url + "/EditMessage_JQ",
data: "{ 'key':" + "'" + btn + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (Data) {
if (Data.d[0] != null) {
$("#MainContent_TextBoxMain").val(Data.d[0]);
}
if (Data.d[1] != null) {
$find("#MainContent_TextRadEditorAbst").set_html(Data.d[1]);
}
if (Data.d[2] != null) {
$find("#MainContent_RadEditorText").set_html(Data.d[2]);
}
$("#insert").css("display", "none");
$("#DiveditBtn").css("display", "block");
$("#DivcancelBtn").css("display", "block");
}
});
}
$ is an object, so you have to use the dot-notation: $.find(...)

Trying to convert json to xml but shows error

I'm trying to convert the json result into xml type. However, it doesn't seems to work. Couldn't find out what's wrong. Please help.
The code is:
<script src="../Jquery Autocomplete/jquery-1.7.2.min.js" type="text/javascript"></script>
<script src="../Jquery Autocomplete/jquery.json-2.2.min.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function()
{
$(".openModalLink").click(function()
{
var start=$(this).parent().parent().find(".start").val();
var end =$(this).parent().find(".end").val();
$.ajax(
{
type: "POST",
url: "frmCollegeExamScheduleMst.aspx/ServerSideMethod",
data: "{'paraml': '" + start + "','param2': '" + end + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success:function(result)
{
var xmlDoc = $.parseXML(result);
var xml = $(xmlDoc);
var customers = xml.find("Table");
var data = new Array();
var i =0;
$.each(customers, function ()
{
//do something
});
},
error: function(err) {
alert('Error:' + err.responseText + ' Status: ' + err.status);
}
});
});
});
When you specify dataType: "json" the response is converted to a JSON object and does not remain a string.
Try removing the parameter.
Try like this:
success: function(result) {
var xmlDoc = $.parseXML(result.d);
...
}
Notice the result.d. I guess your ASP.NET PageMethod looks like this:
[WebMethod]
public static string ServerSideMethod(string param1, string param2)
{
DataSet ds = ...
return ds.GetXml();
}
This string is JSON serialized. In order to retrieve it on the client the ASP.NET infrastructure adds the d parameter:
{"d":"some xml here"}
Another thing that you should absolutely change in your code is replace:
data: "{'paraml': '" + start + "','param2': '" + end + "'}"
with:
data: JSON.stringify({ param1: start, param2: end })
to ensure that your request parameters are properly JSON encoded. Think for example what will happen if start = 'foo\'bar'. You will end up with:
data: {param1: 'foo'bar', param2: 'baz'}
which as you can see completely breaks your JSON.
If the response from your AJAX request is xml then you should set it accordingly.
$.ajax({
data: {paraml: start, param2: end},
dataType: "xml",
success:function(result) {
var $xml = $(result);
}
});
No need for contentType nor concatenating in data.

Categories