Hi
I want to know How to make the page reload asynchronous, for example if someone has received a message , the last message will appear without refreshing the page. just like facebook. thank you.
You would have to use something like JQuery & Javascript to poll the server for changes and display them on the page in a div.
setInterval('someFunc()', 1000)
function someFunc()
{
$.ajax({
async: true,
type: "GET",
url: "www.domain.com/url",
data: data,
success: function (html) {
$("#myDiv").html(html);
}
});
}
This will update the div with ID myDiv every second with the data from www.domain.com/url passing in data is a param (you will have to define 'data')
well there is alot of approaches
but the basics is that you call an ajax function every second or so that
checks with external php/asp or whatever file if any changes has been made to your
database/text if so
append it to the chatbox.
p.s. using libraries such as jquery simplifies things alot
Or you can use Comet model, it doesn't stress the network so much and does not fill the web servers access logs so much. The responses are also faster. Commet means that the HTTP server pushes the data to you immediately when they appear.
Related
If I want to use Google analytics and at the same time make my site SEO friendly in React, what is the best way?
At the moment I use react-router and a flux pattern where I change the route and then in componentDidMount I fire an action that loads my data through ajax and then updates the store which emits the change and finally I re-render the components that are affected. During the ajax loading I dispatch an event so that my store knows ajax is loading and render a spinner in my component.
I have noticed that when I send my tracking data to Google the ajax has not finished loading and I only send the new page URL not the title or any other data which I load through ajax (I guess this is bad from an SEO perspective and it's definitely bad for my GA data).
This is my GA setup (I use react-ga):
Router.run(routes, Router.HistoryLocation, function(Handler, state) {
ga.pageview(state.pathname);
React.render(<Handler />, document.body);
});
Typical component setup (which allows me to render the correct data based on the URL):
componentDidMount: function() {
ItemStore.addChangeListener(this._onChange);
if(itemSlug) {
ItemActions.loadItemBySlug(this.props.slug);
}
}
I want to be able to have a single point of GA tracking if that is possible. I also want the SEO handling to be correct for the page:
Page title
OG data
H1
etc ...
What is the best approach to solve this?
Should I use the willTransitionTo option in react-router for this? (is it possible to use a loading spinner if I opt for this solution?)
statics: {
willTransitionTo: function (transition, params, query, callback) {
// LOAD AJAX HERE ?
callback();
}
}
How would I go about the willTransistionTo solution in a proper way, can't seem to find any good examples that relate?
Should I add more code, or is it clear what I'm trying to achieve?
Trigger the ga.pageview after the store gets the new data and renders.
The appropriate way to handle SEO in react is to render at the server side isomorphically with React.renderToString, so that any search engine will see the page in its complete state, rather than just Google's spider and only on those occasions when you manually call it.
This was one of the original design criteria of React.
Hi I am using a third party plugin. That if I pass it a url manually it returns a value as expected, when I use AJAX in Jquery it returns nothing, I have no idea how to debug this or how to attempt to sort, any help much appreciated.
The url that works
http://192.168.0.34:81/tenHsServer/tenHsServer.aspx?t=ab&f=DeviceStatus&d=C5
The Jquery code that doesn't
$.ajax({type: 'Get', url: 'http://192.168.0.34:81/tenHsServer/tenHsServer.aspx',
data: {t: 'ab', f: 'DeviceStatus', d: 'C5'},
success: function(data) {
alert(data);
},
error: function (request, status, error) {
alert(request.responseText);
}
});
You might need something like JsonRequestBehavior.AllowGet
return Json(dataset, JsonRequestBehavior.AllowGet);//(C# MVC)
...
//Not your aspx page// try changing your get to a post to see if responds differently.
Open up your page that runs this code in Chrome, hit f12 to bring up chrome tools.
Click "Sources"
Set a break point on the lines your'd like to break on, I'd suggest where you put those "alerts()". You set a breakpoint by clicking the number for the line number in the Sources tab. You'll see a little blue icon where the break point is.
After you do the ajax request and break inspect your request and status objects. Check out the responseText, status and also poke around the other fields and see what you find.
Another Thing you can do:
Download http://fiddler2.com/
This is an HTTP debugging tool that is a critical tool for any dev.
HTH.
just need tips on how to make forms where request are submitted via AJAX with a loading progress image. I am using update panels with AJAX framework. I would like to know about the recommended approach. Through JQuery or AJAX toolkit ?
Please advice, examples would be an added bonus for me.
1- Prepare a client side div with "display:none" style property. put your loading image inside.
2 - when the user or page submits a request, change that divs display property to "block".
3- Add some kind of "information received" sign to the response and check this response from the client side and then change that divs display property back to "none"
I would like to know about the
recommended approach
Well, that depends on what you are doing, what parts of the form are you updating, how big is the form, what values are you sending to the server.
Generally speaking, if you want to update something simple (dropdownlist, listbox, etc), youd generally use JavaScript (or jQuery) to call an AJAX-enabled web service. This way, you're only sending to the server the data it needs, things like ViewState/cookies are not sent over the wire. You also have full control over the pre/post execution events (so you can add your loading images, call the WS, then clear them).
However, if you want to asynchronously update an entire form (which has a lot of controls), you're probably right in using an UpdatePanel. Things like a GridView are a good case for an UpdatePanel (as you usually need to handle editing, binding and paging all asynchronously).
The progress image is made easy with the following code:
<ProgressTemplate>
<img src="someloadingimage.gif" alt="Loading" />
</ProgressTemplate>
Stick that inside your UpdatePanel, and whenever an AJAX call is made, the loading image will be shown.
HTH
If you use JQuery for AJAX request then you can use the following events -
$.ajax({ url: "test.html",
type: "GET",
beforeSend: function(){
-----load your loader here-----
});,
success: function(){
------remove your loader here -----------
Remaining code
}});
You can also use POST. in above example i have used GET.
For detailed documentation you can refer - http://api.jquery.com/jQuery.ajax/
Create a small plug-in for your loader like so.
$.fn.ShowLoader = function(on){
switch(on)
{
case true:
$(this).show();
break;
default:
$(this).hide();
break;
}
}
then use the following:
$('form').submit(function(){
var Form = $(this);
$('.loader',Form).ShowLoader(true);
//Gather some params
Location = Form.attr('src');
Data = Form.Serialize();
$.post(Location,Data,function(result){
result = result || false;
if(result)
{
$('.loader',Form).ShowLoader(false); //Disable the loader
//Process result
}
});
})
html would just be a regular form, with an image / div inside with the class of loader
I'm having a serious issue with Internet Explorer caching results from a JQuery Ajax request.
I have header on my web page that gets updated every time a user navigates to a new page. Once the page is loaded I do this
$.get("/game/getpuzzleinfo", null, function(data, status) {
var content = "<h1>Wikipedia Maze</h1>";
content += "<p class='endtopic'>Looking for <span><a title='Opens the topic you are looking for in a separate tab or window' href='" + data.EndTopicUrl + "' target='_blank'>" + data.EndTopic + "<a/></span></p>";
content += "<p class='step'>Step <span>" + data.StepCount + "</span></p>";
content += "<p class='level'>Level <span>" + data.PuzzleLevel.toString() + "</span></p>";
content += "<p class='startover'><a href='/game/start/" + data.PuzzleId.toString() + "'>Start Over</a></p>";
$("#wikiheader").append(content);
}, "json");
It just injects header info into the page. You can check it out by going to www.wikipediamaze.com and then logging in and starting a new puzzle.
In every browser I've tested (Google Chrome, Firefox, Safari, Internet Explorer) it works great except in IE. Eveything gets injected just fine in IE the first time but after that it never even makes the call to /game/getpuzzleinfo. It's like it has cached the results or something.
If I change the call to $.post("/game/getpuzzleinfo", ... IE picks it up just fine. But then Firefox quits working.
Can someone please shed some light on this as to why IE is caching my $.get ajax calls?
UPDATE
Per the suggestion below, I've changed my ajax request to this, which fixed my problem:
$.ajax({
type: "GET",
url: "/game/getpuzzleinfo",
dataType: "json",
cache: false,
success: function(data) { ... }
});
IE is notorious for its aggressive caching of Ajax responses. As you're using jQuery, you can set a global option:
$.ajaxSetup({
cache: false
});
which will cause jQuery to add a random value to the request query string, thereby preventing IE from caching the response.
Note that if you have other Ajax calls going on where you do want caching, this will disable it for those too. In that case, switch to using the $.ajax() method and enable that option explicitly for the necessary requests.
See http://docs.jquery.com/Ajax/jQuery.ajaxSetup for more info.
As marr75 mentioned, GET's are cached.
There are a couple of ways to combat this. Aside from modifying the response header, you can also append a randomly generated query string variable to the end of the targeted URL. This way, IE will think it is a different URL each time it is requested.
There are multiple ways to do this (such as using Math.random(), a variation on the date, etc).
Here's one way you can do it:
var oDate = new Date();
var sURL = "/game/getpuzzleinfo?randomSeed=" + oDate.getMilliseconds();
$.get(sURL, null, function(data, status) {
// your work
});
Gets are always cacheable. One strategy that may work is to edit the response header and tell the client to not cache the information or to expire the cache very soon.
If you are calling ashx page you can also disable caching on the server with the following code:
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
context.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
this is what i do for ajax calls:
var url = "/mypage.aspx";
// my other vars i want to add go here
url = url + "&sid=" + Math.random();
// make ajax call
it works pretty well for me.
NickFitz gives a good answer, but you'll need to turn the caching off in IE9 as well. In order to target just IE8 and IE9 you could do this;
<!--[if lte IE 9]>
<script>
$.ajaxSetup({
cache: false
});
</script>
<![endif]-->
The answers here are very helpful for those who use jQuery or for some reason directly use the xmlHttpRequest object...
If you're using the auto-generated Microsoft service proxy its not as simple to solve.
The trick is to use Sys.Net.WebRequestManager.add_invokingRequest method in the event handler change the request url:
networkRequestEventArgs._webRequest._url = networkRequestEventArgs._webRequest._url + '&nocache=' + new Date().getMilliseconds();
I've blogged about this: http://yoavniran.wordpress.com/2010/04/27/ie-caching-ajax-results-how-to-fix/
Just wrote a blog on this exact issue only using ExtJS (http://thecodeabode.blogspot.com/2010/10/cache-busting-ajax-requests-in-ie.html
)
The problem was as I was using a specific url rewriting format I couldn't use conventional query string params (?param=value), so I had write the cache busting parameter as a posted variable instead..... I would have thought that using POST variables are a bit safer that GET, simply because a lot of MVC frameworks use the pattern
protocol://host/controller/action/param1/param2
and so the mapping of variable name to value is lost, and params are simply stacked... so when using a GET cache buster parameter
i.e. protocol://host/controller/action/param1/param2/no_cache122300201
no_cache122300201 can be mistaken for a $param3 parameter which could have a default value
i.e.
public function action($param1, $param2, $param3 = "default value")
{
//..//
}
no chance of that happening with POSTED cache busters
If you are using ASP.NET MVC, it is enough to add this line on top of the controller action:
[OutputCache(NoStore=true, Duration = 0, VaryByParam = "None")]
public ActionResult getSomething()
{
}
IE is within its rights to do this caching; to ensure the item isn't cached, the headers should be set accordingly.
If you are using ASP.NET MVC, you can write an ActionFilter; in OnResultExecuted, check filterContext.HttpContext.Request.IsAjaxRequest(). If so, set the response's expire header: filterContext.HttpContext.Response.Expires = -1;
As per http://www.dashbay.com/2011/05/internet-explorer-caches-ajax/:
Some people prefer to use the Cache - Control: no - cache header
instead of expires. Here’s the difference:
Cache-Control:no-cache – absolutely NO caching
Expires:-1 – the browser “usually” contacts the
Web server for updates to that page via a conditional
If-Modified-Since request. However, the page remains in the disk cache
and is used in appropriate situations without contacting the remote
Web server, such as when the BACK and FORWARD buttons are used to
access the navigation history or when the browser is in offline mode.
I have an ASP.NET 2.0 Web application.I want to show a progress indcator when user saves some data (Ex : Editing profile).I have already used jQuery in my application for some client side effects. How can i do this ? any jquery trusted stuff to use along with ASP.NET ? Thanks in advance
Do you want to show actual progress or just a busy indicator while the action is happening? If the former, you'll need to have some mechanism to record the save progress in the session and a method to check the state of the progress via AJAX. You'd submit the form via AJAX then periodically call the check method to get reports of the progress and update whatever client-side indicator (usually switch from one to another of a series of canned images or increase the width of some filled "bar"). This, of course, is complicated.
If you want to do the latter, just display an animated GIF that's a busy indicator while you submit the form via AJAX from jQuery using the beforeSend callback, then hide the indicator using the ajax method's complete handler.
$('form').ajax( {
url: '/updateprofile.aspx',
type: 'POST',
data: function() { return $('form').serialize(); },
beforeSend: function() { $('#indicator').show(); },
complete: function() { $('#indicator').hide(); },
success: function(data,status) { alert('Update complete'); }
});
The above code would be in the function invoked from whatever handler invokes the submission or hooked to the form's submit event -- though you'd have to prevent the default action from taking place, too.
An alternative to showing a meaningful progress indicator is to show an animated gif whilst the data is being saved, e.g. the spinning 'daisy' pattern used in Firefox.
This shows the user that something is happening and is usually well received.
Progress indicators which show % complete are often meaningless anyway unless they really have an idea how long the first '50%' will take compared to the last '50%'. Other progress indicators are more meaningful, e.g. those showing record count increments, etc.