How to get XMLHTTPRequest object on server side in asp.net c# - javascript

i want to send the json data from client side(javascript) to server side(ASP.NET,C#) using HTML5. i am using XMLHttpRequest Object to send data to the server by using the following javascript code. i am executing this code behind the html button click.
var xhr = new XMLHttpRequest();
var jsonString = JSON.stringify(jsonObj);
xhr.open('GET', '/HTML5_Crud.aspx?obj='+jsonString, true);
xhr.send();
on server side (ASPX.cs) file i am using the following code in Page_Load method to get data from client.
if (Request.QueryString["obj"] != null)
{
jsonStr= Convert.ToString(Request.QueryString["obj"]);
lblTest.Text = "the json is: "+ jsonStr;
}
but when i run the application and clicks the button my label is not updated with the latest data. it still the same as default text i set inline. please help me how can i resolve this issue.

In the second code snippet, the value of lblTest.Text only exists within the context of the request you made from javascript. There is no magic way to update the response originally sent to the browser. If you want that to be update you have to do either:
Use a postback instead of javascript and update the page
Use javascript to read the response from the Ajax request and then update the DOM client side.

You're trying to do two different things. the XMLHttpRequest is used for an AJAX request, and what you are doing in the back-end will only update your page when it is reloaded. But because you are sending an AJAX request, the page is never refreshed.
What you need to be doing is respond in your code-behind with a string or something, and in your javascript, use the string as appropriate.

Your label will not update this way.
Instead you should return the value to your request and handle it xhr's onreadystatechange event.
Or you can wrap the label in an UpdatePanel and add a button that will store the value in a hidden field for example and cause a postback. Then you could retrieve the value from this field and the whole panel would update to the new values.

Related

Alternate method for dojo.xhrGet() method

I am new to Dojo Framework.I created one button using dojo constructor and dojo.connect onclick event function i written url and load functions.This url navigating servlet and get the response back.
but i don't want response back i want to send request only.
how to do this..anyone help me.
thanks in advance.
are you looking to navigate to another page? if so, you can use window.location.href or other approaches to achieve that. See the foll url for other approaches:
JavaScript: Navigate to a new URL without replacing the current page in the history (not window.location)
if you do not want to navigate but just send some data to the server (and dont care about the response), you can just write an empty function for the callback
var deferred = dojo.xhrGet( {
url : "xxx",
load: function(data) {
//ignore
}
});
});
However, it is recommended to always check the response to ensure there were no errors on the server side.
You could also use dojo.xhrPost to submit your form

Using XMLHttpRequest to call a Rails method to update a value in the db

While on a html page, I'm using an asynchronous XMLHttpRequest request in my Javascript to update a value in my database for a Ruby on Rails application. This update needs to happen "behind the scenes" without the user's knowledge. Unfortunately, because there is no output html to this request (it is an asynchronous request), it's very hard to debug why the database value is not updating.
In the initial html.erb file, the javascript is as follows:
function NAME() {
var url = '/custom_path'; // this path points to the update method in my controller
var request = new XMLHttpRequest();
var params = null;
request.open("POST", url, true); // open asynchronous post request
request.send(params);
}
I don't actually pass any parameters because the only value that I need is stored in a cookie (you'll see in the excerpt my code for the method). My Routes file includes the following line:
match'/customer_path', :to => 'activities#update'
Finally, the code to my "update" method in the Activity table is as follows:
def update
#dummy_var = Activity.find(cookies[:activity_id])
#dummy_var.column_var = false
render :layout => false
end
I'm trying to update the value of "column_var" in my Activity table for the row with the :id column specified by the cookie. Any ideas where I'm going wrong? I have confirmed that the Javascript function is being called and that cookies[:activity_id] has been set properly.
Thanks in advance!
I think the answer is pretty simple here, try calling save on the #dummy_var instance variable.
To test this sort of thing out with ajax, you can use Rails.logger.debug, which accepts a string. You can then check the logs with debug outputs, see what happens. Also you can use something like firebug to see if the request responds with an error.

Pass client side value to server side

I need to use a javascript variable value in server side.
Example:
JavaScript
var result = false;
CS Code
if(result)
{
Console.Write("Welcome..")
}
else
{
Console.Write("plz try again..")
}
Note
I don't want to post a hidden field.
With each request, any server side code will run and then any client side code will run. You can't switch between them at will.
Your options are:
Provide all the data to the client in the first place, then use JS to decide which of them to keep/delete/show/hide/etc
Use Ajax to make a second request to the server with the data you get from JS, return content, and then do something with that content in the JS callback function.
Make a second request to the server and load a complete new page.
Remember to build on things that work.
best way to do this use hidden fields...

Partitioning a JSP page accessed through an ajax call

I have a page in which I am making an ajax call, which in turn gets forwarded to a jsp page and returns a table constructed in this jsp.
Till now this jsp used to return an html which the original page(table) used to append in a particular div. But now, we have a requirement that this jsp along with the table, returns some other info about the metadat of the query.
With this change, I would ideally not like to change the existing behaviour of some clients where they are just appending the html. But then, is there a way, in which the new pages which make this call can have both the html table(which can be appended) as well as metadata returned (which can be processed).
let me know if the question isn't clear enough.
Thanks!
The easiest and least destructive change would be to send it as response header.
In the servlet you can use HttpServletResponse#setHeader() to set a response header:
response.setHeader("X-Metadata", metadata);
// ...
(using a header name prefixed with X- is recommended for custom headers)
In JS you can use XMLHttpRequest#getResponseHeader() to get a response header:
var metadata = xhr.getResponseHeader('X-Metadata');
// ...
You can even set some JSON string in there so that (de)serialization is easy.

ajax sending request twice

Example URL: http://twitter.realgamingreview.com/index.php
Edit: forgot to mention: use the test sign in: test/test for username/password.
I am attempting to do a simple AJAX request to retrieve some data from a database. The target file, serverTime.php, seems to be working perfectly; it inserts the desired data and returns the desired responseText.
However, the request seems to be firing twice. This is clear when I step through the JavaScript using Firebug. This causes the page to 'reset' (not exactly sure), such that my cursor loses focus from its current textbox, which is a new problem. The URL also says, "localhost/twitter/index.php?message=", even if my message is not actually empty. I want to fix this fairly minor problem before something major comes of it.
The JavaScript is below. ajaxRequest is my XMLHTTPRequest object. Any help is appreciated!
//Create a function that will receive data sent form the server
ajaxRequest.onreadystatechange = function(){
if (ajaxRequest.readyState == 4){
document.getElementById('output').innerHTML = ajaxRequest.responseText;
}
}
// build query string
var message = document.myForm.message.value;
var queryString = "message=" + message;
//send AJAX request
ajaxRequest.open("GET", "serverTime.php" + "?" + queryString, true);
ajaxRequest.send(null);
Thanks,
Paragon
I've seen this many times, and for me it's always been firebug. Try TURNING OFF firebug and submit the request again. Use fiddler or some other means to verify the request only executed once.
When I write AJAX functions in Javascript, I usually keep around a state variable that prevents a new request from being dispatched while one is currently in progress. If you just want to ignore requests that are made before another one finishes, you can do something like this:
Initialize inProgress to false.
Set inProgress to true right before calling ajaxRequest.send(). Do not call ajaxRequest.send() unless inProgress is false.
ajaxRequest.onreadystatechange() sets inProgress to false when the state is 4.
In some cases, however, you'd like to queue the actions. If this is the case, then you can't just ignore the request to ajaxRequest.send() when inProgress is true. Here's what I recommend for these cases:
Initialize ajaxQueue to an empty global array.
Before calling ajaxRequest.send(), push the request onto ajaxQueue.
In ajaxRequest.onreadystatechange() when the state is 4, pop the array to remove the request just services. Then, if ajaxQueue is not empty (array.size > 0), pop again and call send() on the object returned.
My issue was completely unrelated to AJAX. Instead, it was a simple (but obscure) issue where with two textboxes in my form, I was able to hit enter and not have the page reload, but with only one, the page would reload for some reason.
I have since changed my event system such that I am not relying on something so unreliable (now using jQuery to listen for the Enter key being pressed for specific textboxes).
Thanks to those of you who took the time to answer my misinformed question.

Categories