Get data from the ajax response - asp.net

For school, i have to develop a Twitter client with ASP.NET.
In the app, i have a list of tweets with a delete link. This link is created with the helper Ajax.ActionLink() and i specified a callback function for OnSuccess event.
This link is okay : the action is performed, the callback is triggered BUT i can't access data sent in the Ajax response.
The callback receive only one argument. Here is the dump of this object :
>> Sys.Mvc.AjaxContext
$0: 0
$1: null
$2: Sys.Net.XMLHttpExecutor
$3: Sys.Net.WebRequest
$4: null
Where is my responseText ? I know that the response has a content (according to Chrome developer tools) and i really want to access it.
Bonus : can Ajax client automatically parse the response as JSON (the action returns JSON properly with the JSON method) ?
Thanks ! ;)
The deadline of this school project is over.
I used get_data on the response.
I'm quite disappointed by the lack of documentation for this trivial need. Even now i know the way, i can't find that on MSDN… Such a pity. :(
Back to my precious Ruby on Rails, i feel better.
Good day and thanks for your help anyway ! :)

Try calling get_object() on your AjaxContext to get a javascript object or get_data() to get the text. An easier method though is to have your OnSuccess function take an argument which will be the object returned.
public ActionResult ReturnJson()
{
return Json(new { TestMessage = "Hello, world!" }, JsonRequestBehavior.AllowGet);
}
And the view...
<script type="text/javascript">
function AjaxSuccess(obj) {
alert(obj.TestMessage);
}
</script>
#Ajax.ActionLink("Say Hi", "ReturnJson", new AjaxOptions() { OnSuccess = "AjaxSuccess" })

If you want to access the responseText within your code you do not want to use AJAX(Asynchronous JavaScript And XML), you want to use SJAX (Synchronous JavaScript And XML).
When using AJAX your code will not wait for the responseText it will just continue to execute so if you try referencing it later in your code it may not work as it might not have processed yet.
When using SJAX your code will wait for the responseText before continuing to execute.
I don't use ASP.NET so I can't help with the code.
Here is how it is done in JavaScript: JavaScript - AJAX / SJAX - Submit Form Data to a Script

Related

ASP.NET Refresh page on timer; query database in between timer

'I have a solution in my head, but am unsure if it is possible in ASP.NET. I don't have a lot of experience with timers. My idea is as follows:
'Code Behind
'At the end of the timer(lets say 1 minute)
Dim qry = "SELECT ISNULL(Value, '') FROM Database.Schema.Table WHERE
Column = #Something"
'set up sql connection and execute query
Using sqlcon as new SQLConnection() 'Don't focus on this part
Using sqlcmd = New SQLCommand(sqlcon,qry) 'Don't focus on this part either syntax is probably incorrect
sqlcmd.Parameters.Add("Something", VarChar)
sqlcmd.Parameters("Something").Value = "Row Found"
'Refresh page; assign label control on .aspx page to value of returned query
'SafeToString() is a function that will safely return a string whether the value is some string, DBNULL, Nothing, or ''
lblString.Text = SafeToString(sqlcmd.ExecuteScalar())
End Using
End Using
I want to be able to do this while maintaining scrolls position as well. So I don't interrupt the work/browsing the user is doing.
Thank you all for your input!
Look up Page Methods. JS can call a code-behind method which can return a value to the js method which can then update the page. The code behind method cannot access the page directly, only return a value to the js method.
I had never used WebForms (which I assume this question is about) but regardless I think you're approaching the problem in a wrong way. A page refresh is destructive and distracting, when a page is refreshed the browser has to fetch the page again (this includes all assets and scripts) and re-render the page.
Client-side implementation
So the solution must be implemented at the client side and not require a full page refresh, this can be achieved using Javascript and ajax(from Wikipedia) requests.
In short ajax is a mechanism for issuing additional requests to a web server while the page is loaded and running. That way you can fetch new data in the background without interrupting the user.
When the page loads set up a timeout or an interval:
let intervalId = setInterval(updateFromServer, 1000);
This interval will call updateFromServer every 1 second (1000ms).
Define the function updateFromServer:
function updateFromServer() {
let newData = fetchData();
updateData(newData);
}
This function is call by the interval we've set up and does 2 things: it fetches new data from the server and pushes it to the DOM using updateData.
You can use ajax (for example with jquery) to fetch the data:
function fetchData() {
return $.ajax({
type: "GET",
url: remote_url,
async: false
}).responseText;
}
This is where ajax comes in, the above lines use jquery ajax api to send a GET request to the server at the url remote_url. The browser issues the request and waits for the server to respond.
And finally update the page (again I'm using jquery):
function updateData(newData) {
$('#data-el').text(newData)
}
Again we are using jquery here (you can use pure javascript though) to find an element with the ID data-el and setting its content to newData.

Recaptcha - Invalid Operation Exception: Http request context does not exist

Well, recaptcha is used twice on site (both in process of registration). First time it works perfect, but second i got exception above (When GetCaptchaVerificatoinHelper method is called).
Also: first time recaptcha is located in form (page) which is loaded synchronously, second time recaptcha is located in PartialView, which is updated via ajax. How to fix this? Also, it would be nice if anybody gave me a reasons this happening. Thanks in advance.
This is problem method:
public Task<ActionResult> SendSmsAgain(CaptchaStubViewModel viewmodel)
{
viewmodel.NotificationMessage = null;
return Task<ActionResult>.Factory.StartNew(() =>
{
if (!HttpContext.Request.IsAjaxRequest())
return null;
var val = WebConfigurationManager.AppSettings["recaptchaPrivateKey"];
RecaptchaVerificationHelper helper = this.GetRecaptchaVerificationHelper(val);
viewmodel.CaptchaValue = helper.Response;
if (string.IsNullOrEmpty(helper.Response))
{ ModelState.AddModelError("CaptchaValue", "You should insert Captcha value to get an SMS");}...}
Update
Has rewritten logic without ajax verification, but this doesn't still work.
Btw: Second captcha is used after redirection. Can anybody help me? I still get the same error.
According to recaptcha.codeplex, recaptcha hasn't supported verification through ajax yet.

How to get the array in ajax success function

I have passed array as return array($posts,$count) from my ajax file.
now in success function i wnat both this array
How to get this array in my success function
I have written as below but i dont get any this in my console :(
in my ajax_post.php
return array($posts, $count);
jQuery.ajax({
url: 'http://localhost/abc/wp-content/themes/directory/Templates/ajax_post.php',
data: {
'action':'example_ajax_request',
'city' : city
},
success:function(data,count) {
// This outputs the result of the ajax request
console.log(data,count);
//loadPopup(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});
If your success function is not logging anything at all in your console, then it probably isn't getting called at all.
What do you see in your console? Do you get an error message after your ajax call? What if you try to just copy / past your jQuery.ajax call directly in the console, what happens then?
It's a bit hard to answer here without details of your function on the PHP side and without error messages, but I suggest you try to first return a simple data type from PHP (just a mock value) to make sure your function is indeed getting called and returns properly when called. If that works then you know your problem is with the data type your are returning. If it doesn't, then the problem is with your AJAX call.
You might very well be having problems with AJAX requests because you are doing them on localhost and that might be causing Cross-Domain request problems.
This question / answer actually explains the concept and the solution to that very well. I think you should at least get a reply to your request if you do that : Make cross-domain ajax JSONP request with jQuery

SignalR generate multiple executions

I'm building a search engine using SignalR to deliver partial responses in real time to the client.
The problem occurs when the first search is not over, and the client modifies the value of the textbox (txtTab) and click the button (btnSearch) again. The results of the two queries are mixed because the server keeps the two concurrent executions.
I need that when the client clicks the search button the previous execution is canceled.
Tried using hub.stop () and hub.disconnect (), but I can not.
Sorry my bad english :)
var busca = $.connection.hubBusca;
busca.client.atualizaResultados = function (arr) {
oTable.fnAddData(arr);
};
$.connection.hub.start().done(function () {
$('#btnSearch').click(function () {
if ($('#txtTab').val() != '') {
busca.server.iniciar($('#txtTab').val());
}
});
});
Thanks!
Luiz Fernando
I would suggest creating an additional server and client method to handle the final search (which happens when #btnSearch is clicked).
Instead of invoking busca.server.iniciar invoke something like busca.server.terminar.
I would also suggest setting some sort of boolean flag before calling busca.server.terminar to disable busca.client.atualizaResultados so no preliminary search results interfere with the final search results.
Then in HubBusca.Terminar you could call Clients.Caller.finalesResultados which would not be disabled unlike Clients.Caller.atualizaResultados.
In this way you can ensure that your final search results which are sent to the finalesResultados method will not be replaced by results sent to the atualizaResultados client method.
Sorry for my bad Spanish method names. I used Google Translate.

Ajax function throwing WebServiceFailedException

I am using same asp.net page to edit and add data, only with some fields disabled and enabled accordingly. Now when I call webmethod from the add page, it's working fine, but when I call it from edit page, it is not. Though I am using the same javascript function to call the server side method. Please see the code:
.aspx:
function KeyCheck()
{
var KeyID = event.keyCode;
if(KeyID==46)
{
PageMethods.Delete_files(CurrentObj.id);
}
Now when I try to call this same method through edit, its generating following error :
Microsoft JScript runtime error:
Sys.Net.WebServiceFailedException: The
server method 'Delete_files' failed
with the following error:
If you look here they discuss a similar problem. Although the last answer wasn't selected I would still recommend doing what he says. After your first parameter you can pass two function callbacks; one for a successful Ajax call and one for a failure.
Your function should look more like this:
var onDeleteSuccess = function(result) {
//Successfully deleted files, maybe display confirmation to user.
};
var OnDeleteError = function(result) {
//Deleting files unsuccessful, display error to user.
};
PageMethods.Delete_files(CurrentObj.id, onDeleteSuccess, OnDeleteError);
Try adding the "missing" (although they should be optional) parameters to your PageMethod call and see if that solves it.
Edit:
I found a closed bug at connect.microsoft.com about this problem. Have you tried using the page only in IE7? If so, test it in other browsers and see if it works. If it does your only option may be to upgrade IE7 to a newer version or re-open the issue.
Edit after comments:
Try placing this code before your PageMethods.Delete_files function call:
PageMethods.set_path("PageYouAreTransferringto.aspx");
I think the handler you're calling is confused about which server-side page method to call since it appears (to the browser and JavaScript) that you're on a different page.

Resources