pre-load screen after searching? - javascript

i have a search box flight search in my home page (similar to http://www.travelpack.com/)
When you search in http://www.travelpack.com/ you will see a "We are searching for flights that meet your requirements.
Please wait...
" screen i didn't have it and i want a similar screen in my site.
the problem is that when i click search from my home page
i am using javascript to submit the form
document.flight_search.action = 'php/flt-show-availability.php?&s=1&Sort=P';
document.flight_search.method = 'post';
document.flight_search.submit();
how can i create a loading screen similar to that in the travel pack.

in jQuery one would show the screen, and forward after the ajax call (which tells the appilcation to generate a result) is completed, much like that:
$('.search').click(function(event){
event.preventDefault();
$('#loadAnimationWrapper').show();
$.ajax({
cache: false,
async: false,
type: 'GET',
url: '/your/callback/url',
success: function(data) {
// your forwarding code
}
});
});
But in My Opinion, the example page you give has the Problem that the content shown does is not represented in the url, so, for example you can't give the url to somebody else to let him have a see at the results.
So, ajax magic - sure, but be careful.

You could redirect to the result page, hiding the list of results behind a div that contains the loading message. Then you receive the results via javascript (ajax or similar) and build up the list in background.
When the server is finished searching your request finishes and you can hide the div that contains the loading message (for example in the callback function).

well, you can send your form via ajax-request and wait for the answer.
while waiting display the loader.
if the request succeeds you can react differently:
- replace the content
- goto the generated output page

Related

ASP.NET MVC/jQuery/AJAX: link fails to work first time, but works second time (after page reloads)

Preface
For this question, I have a MVC partial view. The view has a section which displays a list of documents. Each document has a hyperlink: when clicked, the hyperlink takes the user to a second page view displaying additional information.
The link is inside an unordered list:
<a style="text-decoration:underline;" onclick="sendToDocketSearch('#currentDocument.DktYear','#currentDocument.DktSequence','#currentDocument.DktSubActionID');">#currentDocument.DktYear.ToString().PadLeft(2, '0') - #currentDocument.DktSequence.ToString().PadLeft(5, '0')</a>
When the user clicks the link, it takes them to a sendToDocketSearch javascript function (to prepare to search for the document):
var sendToDocketSearch = function (yearOfDocket, sequenceOfDocket, dktSubActionIDOfDocket) {
jQuery.ajax({
type: "POST",
url: "#Url.Action("DocketSearchOnDemand")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ docketYear: yearOfDocket,
docketSequence: sequenceOfDocket,
DktSubActionID: dktSubActionIDOfDocket,
userIsAuthorized: '#Model.userIsAuthorized' }),
success: function (data) {
alert(data);
},
failure: function (errMsg) {
alert(errMsg);
}
});
submitForm();
}
Note that the page/view/form is submitted after the following controller method is run:
public ActionResult DocketSearchOnDemand(string docketYear, string docketSequence, decimal DktSubActionID, bool userIsAuthorized, PortalIndexView viewmodel)
{
System.Web.HttpContext.Current.Session.Add("userIsAuthorized", userIsAuthorized);
string docketSearch = docketYear + "-" + docketSequence;
System.Web.HttpContext.Current.Session["DocketSearchOnDemand"] = docketSearch;
if (DktSubActionID > 0)
{
System.Web.HttpContext.Current.Session["DktSubActionID"] = DktSubActionID.ToString();
System.Web.HttpContext.Current.Session["searchingCustomID"] = true;
}
else
{
System.Web.HttpContext.Current.Session["DktSubActionID"] = "1";
System.Web.HttpContext.Current.Session["searchingCustomID"] = false;
}
return View(viewmodel);
}
The above controller method runs; then, because the form is submitted, the HttpPost action for the page takes place. When running it on my local PC, the link is clicked and the next page is loaded without drama.
Problem
The problems start when I upload the code to the dev/test server. I don't know how to use breakpoints while troubleshooting an active website, so I follow along with the browser developer tool to monitor network traffic.
When clicking the link when running the website on my localserver, the process continues:
the hyperlink takes me to a method where I pass information to be searched
the page/view/form is submitted
the controller redirects where I have to go.
When I click the link on the site and it's on the server, the first click is completely ignored - network traffic shows that it tries to navigate to the controller via the javascript function above, but the failure happens so fast I can't even take a screenshot of it. The page reloads a second time at this point.
When I click on the same link a second time, it works without fail.
I believe the view/javascript/controller code works because it works the second time (and on subsequent attempts). It just flagrantly fails the first time on the server; after that, the user is fine. I'd like to prevent that "first-time" failure, however, and I'm wondering what the problem could be...
Bad timing
I may be passing the information too early (or too late for my website/server to process it properly). The page does it correctly the second time, so maybe I'm just "jumping the gun" by not waiting a little longer for page-loading processes to sort themselves out. (Maybe I can fiddle around with the $(document).ready() javascript portion of the first page to "delay" allowing people to click a link.)
Code error
I'll be glad to admit bad code if I'm genuinely messing something up. Maybe it's my javascript function, or maybe it's the code in my controller; at any rate, something is making the first pass of that function call be rejected. Maybe my code is bad because the problem doesn't happen the second time, and I'm getting a false sense of security (i.e. there are problems with my code that the system is willing to forgive after the page has thoroughly loaded).
Server problem/miscellaneous
I'm wondering if I missed something when I uploaded my latest changes, or if I should have contacted my network team in case there are permissions that need to be activated for the site to work smoothly. I'm already in touch with them regarding something else, so I might take advantage of the opportunity today.
There is an alternative in place that could help me prevent this problem from happening, but I want to find out why the "first-time" failure happens. Other similar actions fail the first time on the site, and I'd like to apply the insights from fixing this issue to them.
Thank you for looking at this issue. Have a great day.
Are you sure you want to call submitForm(); before your jQuery.ajax has finished? your ajax call is async so it will hit submitForm(); before it has had time to finish. should submitForm(); be in your success event instead?

How do I run my own userscript function after the host site completes an ajax request? [duplicate]

This question already has answers here:
Fire Greasemonkey script on AJAX request
(2 answers)
Closed 3 years ago.
I'm using greasemonkey with Firefox to alter what content is displayed when I visit a particular domain. One of the pages contains a dropdown with two elements, let's call them element0 and element1. Whenever it detects a switch from one to the other, it performs an ajax query that alters the page content depending on which one you've selected. So it looks something like this:
$(".dropdown").change(function(){
if($(this).val()=='element0'){
$.ajax({
// fetch some html
});
}
else{
$.ajax({
// fetch some other html entirely
});
I'm happy with what is displayed when element0 is selected - it's element1's associated content I want to alter. So I need a way to trigger my own userscript function only in the second case. I also somehow need it to execute only after the ajax query is complete of course. How do I do this?
I have some basic experience with programming, but know absolutely nothing about jquery, ajax, json etc etc. A friend helped me locate the above ajax for that page so that I could even post a meaningful question. Please bear my level of experience in mind, because I'd really really like to move forward with whatever knowledge/wisdom you guys can offer, but will only be able to do so if I understand it.
Many thanks!
EDIT: The above is javascript that the host is running. I accessed it by saving the page and looking around manually. I am writing userscripts on the client side to alter what my browser displays. So I want to write my own function that responds to their js in the way I described.
AJAX
In ajax you have a tow useful method,
success & compleate
success: with execute if ajax request are work truth
complete: are work when finished ajax function, so you can use this method
example:
complete: function(){
// call another ajax, hide somthing, do any somthing
},
another example:
var all_data = {'user':txtuser,'pass':txtpass};
$.ajax ({
url:"ajax.php",
type:"post",
data:all_data,
beforeSend:function(){
// do somting before send a data
},
statusCode:{
404:function(){
$("#ma").html("Page not found");
},
401:function(){
$("#ma").html(".....");
}
},
success:function (data) {
$("#ma").html(data);// if sucsess
},
complete:function(){ // when complete
$("#user").hide(2000);
$("#pass").hide(2000);
$(".q").hide(2000);
}
});

Altering the DOM with the Play! Framework

Hello again StackOverflow.
I've been tasked with modifying a website that runs on Scala's Play! framework and Twitter Bootstrap. I've hit a roadblock concerning altering the DOM. I need to accomplish the following:
(The page being talked about takes user input and passes the server a Form, which if
valid writes the mapped Data in the Form to a database.)
Have the user choose a category from a drop-down. This particular drop-down has nothing to do with the Form.
Based on their choice, query the database for all objects of a certain type that relate to the chosen category via a foreign key.
Alter the DOM (that is, show without reloading the page) to display those objects for the user to select them. Their selections are added to the Form.
Submit the Form, write to the database, etc.
Questions:
Is this a good way to go about what I'm trying to accomplish?
If so, is there a way to alter the DOM via Scala/Play HTML templates without reloading the page?
If that's not possible, what ilk of manually written Javascript is necessary?
Admissions:
I have very little experience with web development other than Play.
I have very little experience with Javascript.
Resources I've been looking at:
This SO post
Play docs on Javascript routing
Scala.js
Thank you!
For anyone who might come upon this in future, the short answer is Javascript.
Long answer:
To do any AJAX work, you'll need a method like the following in your top-level Controller to set up Javascript routing:
def javascriptRoutes = Action { implicit request =>
Ok(
Routes.javascriptRouter("jsRoutes")(
SomeOtherController.someMethod // Returns a JsValue!
)
).as("text/javascript")
}
Then in the HTML template (*.scala.html) which will contain some AJAXy Javascript:
<script type="text/javascript" src="#routes.ApplicationController.javascriptRoutes"></script>
And finally in your actual JS file (assuming you're using jQuery):
$("someSelector").click(function() {
// Notice that this matches the method name that exists in Scala!
// Make sure to pass `someMethod` what it needs.
var req = jsRoutes.controllers.SomeOtherController.someMethod(...)
$.ajax({
url: req.url,
type: req.type,
success: function(json) {
// DOM manipulation, etc., here.
},
error: function(xhr, status, errorThrown) {
console.log( "Error: " + errorThrown );
console.log( "Status: " + status );
console.dir( xhr );
}
}); // ajax
}); // handler

Show what I am listening to on Spotify

I am using this plugin to enable me to display what I am currently listening to live on my website: https://github.com/derekmartinez18/Simple-Ajax-Spotify-Now-Playing
A piece of JavaScript will run on page load, which connects to the PHP which via API checks what I am listening to, grabs the title etc, if successful sends back to the JavaScript and displays via HTML.
I've echoed out what the PHP is getting and can see it's correctly grabbing all the recent songs, names etc. Therefore because nothing is appearing on the page maybe it's the JavaScript. I've pasted it below with pastebin link to php too.
JavaScript
<script type="text/javascript">
function get_spotify() {
$.ajax({
type: 'POST',
url: '/Scripts/last.fm.php',
data: { request: 'true' },
success: function(reply) {
$('.now-playing').html("<p>" + reply + "</p>");
}
});
}
window.onload = get_spotify;
</script>
Pastebin of PHP - http://pastebin.com/eZUH6BNU
A snippet of the API output which is being past over to the PHP (it's huge so didn't paste it all.):
{"recenttracks":{"track":[{"artist":{"#text":"LMFAO","mbid":"ed5d9086-e8cd-473a-b96c-d81ad6c98f0d"},}
Live Link - http://bit.ly/1ewTe8l
Based on the example you have given below your question, the problem is that there is no element with a class of now-playing.
Your page seems to have been cut short, perhaps due to an error, but the ajax request fires and in the console I can see the response (the url is actually echoed before that as well):
I am currently listening to 01. Circles Around The Sun by Dispatch on Spotify.
Adding a <div class="now-playing"></div> should do the trick.
Edit: Note that your key is visible in the response as you are echoing the url you are making a request to. It might be a good idea to change the key when you have solved your problem.

How can I make an AJAX refresh like Gmail's inbox?

I'm making a messaging system and I am currently reloading the content of the div holding the messages every 10 seconds using jQuery's .load(), but I have a problem: When trying to make a "Select all" button, "Delete selected" button, etc. when that 10 seconds comes up it reloads the buttons and it reloads the messages, so the messages get deselected because of the reload.
What I would like to know is how to make it actually load in new messages, but not actually reload the whole div. I know that Gmail does not reload the whole div because it works properly.
This is my JavaScript function that reloads the div and changes the page title (that has inbox count) so it stays updated:
function title() {
setTimeout("document.title = $('#heading').text();", 500);
}
function ajaxStuff() {
setTimeout("$('#heading').load('/employee/message/inbox.php #h1_head'); $('#messages').load('/employee/message/inbox.php #messages_inner');title();ajaxStuff();", 10000);
}
ajaxStuff();
Here is how I have the inbox set up:
Basically what I want to do is load in new messages with AJAX but somehow not refresh the div. I tried looking at Gmail's source but there's too much to go through and they make it confusing with a bunch of random classes and IDs.
Note: I have searched this on Google for a while now and did not find anything.
In response to comments:
I don't think a tutorial is warranted here. Change your server code to return the "new" messages with a class="new" attribute, then use:
$.ajax({
url: "/employee/message/inbox.php",
success: function(result) {
$(result).find(".new").prependTo("#heading");
}
});
Of course, that code may need some modifications to fit your environment/return data.
When checking for new messages send an ID of the newest message in your request. Then your php will return only everything newer that you add to your existing data.
jQuery.ajax({
type: 'get',
dataType: 'text',
url: "/employee/message/inbox.php",
data: {
from_user : from_user,
to_user: to_user,
message_id: message_id,
something_else_you_need_to_send: its_value
t: Math.random()
},
success: function(data, textStatus){
// whatever you need to do with the result returned from php (server)
}
Then in your sql query you do
select * from table
where user_id=user_id_from_ajax
and message_id > message_id_from_ajax`
update
in your php you use
$from_user = $_REQUEST['from_user'];
$to_user = $_REQUEST['to_user'];
$message_id = $_REQUEST['message_id'];

Categories