Sending $ajax via jQuery to C# codebehind not working - c#

I am having unexplained behavior when I post from jquery using ajax to C#.
1) The main page is called not the method I am requesting in jQuery.
To work around this I simply put an if in the page load so that if a particular item is in the querystring it will trigger a series of commands. It does hit that if statement and runs the code perfectly fine. There are some methods that do things like change a color on the map. These never actually happen. I can set a label and it will pass right over it but the label remains unset.
2) strangely enough.... my page has a timer with a refresh on it. It refreshes the page and now the changes are processed.
Here is the way I am calling my method in jQUery:
function mycmethod(param)
{
//alert(precinct);
$.ajax({
url: "myPage.aspx/someMethod",
type: 'POST',
data: "params=" + param,
success: function iGotData(responseJSON) {
// alert("Worked");
},
error: function (xhr, status, errorThrown) {
console.log("Error: " + errorThrown);
console.log("Status: " + status);
console.log(xhr);
alert("Didnt work:" + errorThrown);
},
})
};
It was originally set to async: true but that didn't make a difference.
The method its not calling on load is:
[WebMethod][ScriptMethod]
public Boolean someMethod(string param)
{
setFeatures();
GenerateMap();
return true;
}
I doubt its relevant but I am calling a jquery call with over mouse over of a specific element. That jquery calls a function which calls a asmx web service that returns some jSON. I am calling the mycmethod after the JSON is returned.
Why is my UI elements not responding until the page refreshes. If not, is there a way I can force a refresh like the timer does?

[WebMethods] methods should be declared as static.
I've also found that you might need to specify the content type in your ajax call:
contentType: "application/json; charset=utf-8"
Also, your data option looks suspicious. Maybe you should append it to the url option:
url: "myPage.aspx/someMethod?params" + parm
or, more ideally, send it as either a JSON object or a JSON string:
data: {
params: param
}
or
data: JSON.stringify({
params: param
})

If I understand you correctly, you're loading the page, then calling the server via ajax and expecting the server to change UI elements of the currently loaded page.
It doesn't work like that, unfortunately. Once you've served the page, the server itself cannot manipulate that page without doing a refresh/post back (or something along those lines).
If you want to update the UI without doing a refresh/post back you can have your WebMethod return HTML, and your jQuery success method can update the relevant controls.
Alternatively you could use jQuery's .get() to retrieve a fresh copy of the page via ajax, and update your current page like that. (although it's less efficient)

Related

Update the Page without refresh it

Goal:
When you click on the row (1), new data shall display (3.) without the whole webpage will be updated/refreshed.
Problem:
1.
I need advice and I don't know where to find the funciton to display the picture number 2 and how to display the data and new object (3.) without update/refresh the whole webpage?
And
2
How do you create an icon to display loading picture?
Information:
- The page is based on ASP.mvc with C#
Use ajax functionality of either jquery or MVC ajax helpers.
You can find jquery ajax here.
and MVC ajax helper lib here
and here
you can make an ajax call to the server's websevice and it can return one of the well known web format (for e.g. json or XML). When the webservice call returns you can then "inject" the data in your html page with either javascript (dom manipulation) or using MVC helpers.
Here's one that could help..
http://www.asp.net/mvc/tutorials/older-versions/javascript/creating-a-mvc-3-application-with-razor-and-unobtrusive-javascript
You Can use jquery ajax which would call async action method(function). Data is returned the form of Json. You can write code to deserilize data and display it using jquery.
Create a Action method which would return JsonResult as viewresult as
public JsonResult GetJsonData()
{
return Json(new
{ testDataResult =TestDataResultObj.Data
JsonRequestBehavior
}, JsonRequestBehavior.AllowGet);
}
and write following jquery code:-
if (GetDataAsyc()) {
$.ajax({
type: "GET",
data: { testData: testDataResult },
url: url,// url of action method to be called asynch
dataType: "json",
cache: false,
traditional: true,
contentType: "application/json",
success: function (data) {
// on success assign testDataResult to messages //line
$("#MessagesLines").html(testDataResult .Html);
}
},
error: function () {
//Display error message
$("ErrorMsg").html("There was error whey trying to process your request")
}
});
}
Use ajax+PartialViews to update some page sections

Is this possible through javascript?

I am currently working on asp.net project. I use oodle web service. Oodle provides result via URL. I use Link to get data from the URL.
From code behind I use following code to fetch the resultant string :
string url =
#"http://api.oodle.com/api/v2/listings?
key=TEST&region=chicago&category=vehicle&format=json";
var jsonString = new WebClient().DownloadString(url);
Now , My problem is I use button click event to run that code. But is this through JavaScript ? Because If I use Javascript it will be easier to access my resultant data.
It looks like this API returns JSONP which means that you could consume it directly from javascript. For example if you use jQuery you could use the $.ajax() method:
$.ajax({
url: 'http://api.oodle.com/api/v2/listings?key=TEST&region=chicago&category=vehicle&format=json',
type: 'GET',
dataType: 'jsonp',
jsonpCallback: 'jsonOodleApi',
success: function(result) {
alert(result.current.region.id);
}
});
Here's a live demo.
And if you don't use jQuery you could simply define a callback:
var jsonOodleApi = function(result) {
alert(result.current.region.id);
};
and then include a <script> pointing to this url:
<script type="text/javascript" src="http://api.oodle.com/api/v2/listings?key=TEST&region=chicago&category=vehicle&format=json"></script>
Here's a live demo.
Obviously you could inject this script tag dynamically into the DOM whenever you want to invoke the API call.
You can make Ajax requests to the page through Javascrypt.
here's a tutorial on that
If you are using some JavaScript frameworks, like JQuery, those requests would be easier to make, as the AJAX requests are kinda not cross-browser compatible.
the JQuery version
What you want is an AJAX request. It it certainly possibly to do without libraries, but due to crossbrowser issues I would recommend using a library. With jQuery for example it could look like this (in a document ready part of script):
$("#idOfButton").click(function() {
$.get('string url= #"http://api.oodle.com/api/v2/listings?key=TEST&region=chicago&category=vehicle&format=json', function(jsonString) {
alert('Data is now in variable jsonString!');
});
});

Saving changes to a jQuery sortable table

I have a table where the users are allowed to drag and drop rows in the order they want, and then save them. I have no problem with getting the drag and drop part to work. It's the saving I'm having issues with. I'm sending an Ajax call to a web service which will then make the save. I can't seem to actually catch the request in the web service though.
My JavaScript function looks like so:
$(document).ready(
function () {
$(".sortable").sortable({
update: function () {
serial = $('.sortable').sortable('serialize');
$.ajax({
url: "MyWebService.asmx/SortTable",
type: "post",
data: serial,
error: function () {
alert("theres an error with AJAX");
}
});
}
});
});
The JSON string looks fine from what Firebug is showing me. The web service function is like so:
[WebMethod]
public string SortTable(String[] rows)
{
//SaveChanges();
return "Called!";
}
When I put a breakpoint in there, it never gets hit. When there are no arguments in the function though, it will get hit. I've tried replacing "String[]" with "object" and it still doesn't get hit, which I find odd. What is going on here?
You might need to decorate your web service with the [ScriptService] attribute in order to allow client scripts to invoke it. Also if you are sending a JSON request you need to specify the content type. Another remark is about sending the request as an actual JSON object which could be achieved using the JSON.stringify method (maybe the $('.sortable').sortable('serialize') call already does this, I am not familiar, you just need to ensure that the POSTed value looks like this: [ 'row1', 'row2', ... ]):
$.ajax({
url: 'MyWebService.asmx/SortTable',
type: 'post',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify([ 'row1', 'row2', 'row3' ]),
error: function () {
alert('theres an error with AJAX');
}
});

jQuery does not load response

I normally use ASP.NET MVC 2, but there were some problems with it, so I began to work with ASP.NET MVC 2 + jQuery and everything works. But there is one problem, jQuery doesn't load my reponse. On the ASP.NET MVC side I'm redering a partial view and I also get the respone on the client, but nothing is rendered. How can I solve this?
Here is the jquery code:
function addCredential(state, id) {
var daten = getJson(state, id);
$.ajax(
{
type: "POST",
url: "/Account/SetCredential/",
data: daten,
dataType: "json",
success: function(partialView) {
$('#Credentials').replaceWith(partialView);
location.reload();
}
});
return true;
};
function getJson(state,id) {
var username = $('#username').val();
return {"username": username, "credential_id": id , "state": state };
};
The problem looks like location.reload();
That's reloading your page after you update it with AJAX, effectively returning it's state back to the way it was before you inserted the content with .replaceWith()
UPDATE: looks like you're using dataType: "json" and inserting that into the DOM? That's probably also a problem. If the view is being returned as HTML, you should replace that with dataType: "html"
#Konrad, try using the JSON2 library (http://www.json.org/js.html) to alert the "partialView" object in your success function to see what you're getting prior to reloading the page. Also, make sure $('#Credentials') is returning an object. When I run into issues when trying to select elements on the page, I usually check the length value of the jQuery object that is returned. If length = 0, then you're not getting the element.
UPDATE:
Also, if you're trying to inject HTML into $('#Credentials'), then partialView may not be the correct format. The success function accepts an object argument which comes from parsing of the responseText of the web method you called to get what you call partialView.
UPDATE:
Check http://encosia.com/2010/03/03/asmx-and-json-common-mistakes-and-misconceptions/ for more info using $.ajax. Lots of great info on this blog.
UPDATE:
This is how I use JSON lib to view the data that is returned.
alert(JSON.stringify(partialView));

ASP.NET: UrlReferer has wrong value, interrogating in a static (webmethod) page called from jquery

Can anyone help? I am trying to interrogate the UrlReferer whcih should contain Google.com but it contains my current site. My web page is a standard HTM page and jquery calls a static method like so
[WebMethod]
public static void ProcessTracking(string jsonString)
Inside this method i do a standard lookup on Request.UrlReferrer like so
string referrerDomain = HttpContext.Current.Request.UrlReferrer.Host ;
But it always contains my current domain, this was a little suspect so i created a standard asp.net page and did the same and it works 100% without issue..
So it appears that when my htm page calls via jquery my webmethod (static) and interrogates the UrlReferrer it return ALWAYS my current site which is wrong.
Does anyone know a work around?
I even tried doing something in session_start etc in global.asax but no fix.
EDIT: How i am calling the page from jquery in html
$.ajax({
type: "POST",
url: "MyService.aspx/ProcessTracking",
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function(msg) {
},
error: function(msg) {
alert(error);
}
});
That script is hosted on your page, right? In that case, the referrer will be your site.
If you want the referrer for the page itself, then you need to pass it as an argument with your Ajax call; it won't be present in the HTTP header.
You can read the referrer of the page from the document.referrer property.
Surely it should contain your current domain, as that is webpage doing the post?
If you want to retrieve the original callers page, you'll need to store that in the original webpage, before calling your ajax code, and then passing that through.
Resources called via AJAX requests will consider the calling page as the referrer, which is why your domain is showing up as the referrer.
You had the right idea to use the Global.asax, but try hooking in to the BeginRequest method:
void Application_BeginRequest(Object Sender, EventArgs e)
{
string referrerDomain = HttpContext.Current.Request.UrlReferrer.Host ;
}
This is working as intended. When you use AJAX to post, you are sending a request from your page (your domain!) to the target server.
One workaround would be to store the original referrer's host name in a javascript variable when constructing your page:
var referrerHost = '<%= HttpContext.Current.Request.UrlReferrer.Host %>';
Then package that into the jsonData variable you're sending to the ProcessTracking method in the ajax function's data parameter.

Categories