I am trying to build a search page where the user inputs text into a search box and the page is generated based on the search. I am having timing issues because the blank search page is loading after the JS tries to edit the values on the page.
$.ajax({
type: 'GET',
url: '/index.php/content/generate_search',
data: {
search: input.val()
},
beforeSend: function() {
window.location.href = '/index.php/content/search';
},
success: function() {
$('.hero h1').text(input.val());
}
});
To check that the DOM is completely loaded, many steps have to be done taking all the browsers into consideration. (I cannot find the implementation in the jQuery source, but I will come back with a link).
The easiest and probably best way of doing it, since you're already using jQuery is by:
$( function() {
// your code here
} );
which is a shorthand for
$( document ).ready( function() {
// your code here
} );
EDIT
Ok, so as I promised, I came back with the implementation of document.ready. You can find it here, on GitHub. Here is a permanent link to the current version of the file.
Try this:
$(document).ready(function(){
//Your code
});
onload is used for executing code on pageload
window.onload = function() {
// your code
};
This code:
beforeSend: function() {
window.location.href = "/index.php/content/search";
},
… is causing the browser to leave the page and load a new one before it sends the Ajax request.
Consequently, the Ajax request gets cancelled. If it didn't, then there would be no JavaScript waiting to receive the response.
If you want to visit /index.php/content/search and then initiate an Ajax request, then the JavaScript to initiate the Ajax request has to be on /index.php/content/search. A page you've just left can't run JavaScript on the next page.
Related
I am using ASP.Net MVC and jQuery 1.8.2
I have a form with a button that calls this javascript when it is clicked:
$(function () {
$('#SearchButton').click(function () {
var data = $('#FilterDefinition :input').serialize() + "&PageNumber=1";
$.post('#Url.Action("Search")', data, LoadContentCallback);
$("#SearchResults").show();
});
});
This calls an MVC Controller Action which returns a PartialViewResult
On the Layout page I have the following JavaScript code:
//Add a custom header to all AJAX Requests
$(document).ready(function () {
$.ajaxSetup({
beforeSend: function(xhr) {
debugger;
if ($('[name=__RequestVerificationToken]').length) {
var token = $('[name=__RequestVerificationToken]').val();
xhr.setRequestHeader('__RequestVerificationToken', token);
}
}
});
});
When the button is clicked for the first time, the beforeSend function is called correctly. However, if the button is clicked more than once (for example they change the search criteria and search again) then the beforeSend function never gets called again and the validate anti-forgery fails.
I tried using the ajaxSend event instead and I got the same results.
Any help is solving this problem would be greatly appreciated.
Thanks!
It turns out the problem was that the partial view that was being rendered was referencing a different version of jQuery. I removed this reference and everything started working correctly.
Thanks!
I would avoid using $.ajaxSetup if possible. I would just setup your beforeSend in the actual POST request.
before we start apologies for the wording and lack of understanding - I am completely new to this.
I am hoping to run a php script using Ajax - I don't need to send any data to the php script, I simply need it to run on button press, after the script is run I need to refresh the body of the page. What I have so far:
HMTL Button with on click:
<font color = "white">Next Question</font>
JS Ajax call:
function AjaxCall() {
$.ajax({
url:'increment.php',
type: 'php',
success:function(content,code)
{
alert(code);
$('body').html(content);
}
});
}
this runs the php script but doesn't stay on the current page or refresh the body - has anyone got any ideas - apologies if this is completely wrong I'm learning - slowly.
Many thanks in advance.
**As a small edit - I don't want a user to navigate away from the page during the process
How about using load instead of the typical ajax function?
function AjaxCall() {
$(body).load('increment.php');
}
Additionally, if you were to use the ajax function, php is not a valid type. The type option specifies whether you are using GET or POST to post the request.
As far as the dataType option (which is what I think you mean), The Ajax doesn't care what technology the called process is using (like ASP or PHP), it only care about the format of the returned data, so appropriate types are html, json, etc...
Read More: http://api.jquery.com/jquery.ajax/
Furthermore, if you are replacing the entire body content, why don't you just refresh the page?
your ajax should be
function AjaxCall() {
$.ajax({
url:'increment.php',
type: 'post',
success:function(data)
{
console.log(data);
$('body').html(data);
}
});
}
if you want to learn ajax then you should refer this link
and if you just want to load that page then you can use .load() method as "Dutchie432" described.
If you are going to fire a javascript event in this way there are two ways to go about it and keep it from actually trying to follow the link:
<font color = "white">Next Question</font>
Note the return false;. This stops the following of the link. The other method would be:
<font color = "white">Next Question</font>
Note how this actually modifies the href to be a javascript call.
You can study about js and ajax here http://www.w3schools.com/ajax/default.asp will help a lot. Of course all js functions if called from internal js script should be inside <script></script> and if called from external you call the js gile like <script src"somejs.js"></script> and inside js there is no need for <script> tags again. Now all those function do not work by simply declaring them. So this:
function sayHello(){
alert("Happy coding");
}
doesn't work because it is just declared and not called into action. So in jQuery that you use after we declare some functions as the sayHello above we use:
jQuery(document).ready(function($){
sayHello();
});
Doing this we say that when everything is fully loaded so our DOM has its final shape then let the games begin, make some DOM manipulations etc
Above also you don't specify the type of your call meaning POST or GET. Those verbs are the alpha and omega of http requests. Typically we use GET to bring data like in your case here and POST to send some data for storage to the server. A very common GET request is this:
$.ajax({
type : 'GET',
url : someURL,
data : mydata, //optional if you want to send sth to the server like a user's id and get only that specific user's info
success : function(data) {
console.log("Ajax rocks");
},
error: function(){
console.log("Ajax failed");
}
});
Try this;
<script type="text/javascript">
function AjaxCall() {
window.location.reload();
}
</script>
<body>
<font color = "white">Next Question</font>
</body>
using ASP .Net MVC 4.0 , vs10 , MSSQL 2008
I have a stored procedure, which is executed in one of my page. it generally takes 30 to 50 second to execute. I want to show a alert dialogue where an gif image will be loaded during this process time. I am executing stored procedure with sqlcommand. The process started on clicking Process button. after finishing the process, the page returns another view.
I have poor knowledge of javascript, so please show me a simple way.
EDIT:
Is it possible to show an image on buttonclick an do other codebehind process?
Like:
<script type="text/javascript">
function showImage() {
document.getElementById('Processing').style.visibility = visible;
}
</script>
<div id="progessbar">
<img alt="Processing" src="../../Images/Processing2.gif" id="Processing" style="visibility:hidden"/>
</div>
It will be difficult to accomplish what you're trying to do in a traditional MVC fashion since the request takes a long time. This is better accomplished using AJAX which processes your request asynchronously. I recommend also using jQueryUI dialog or any modal to show a progress indicator, or even any custom JS.
I like jQuery BlockUI personally to create the modal for me but that's just a preference.
/** Using a wrapper to show/hide the progress indicator.
Swap the blockUI with any library or custom JavaScript for displaying the progress indicator.
*/
var showProgress = function() {
$.blockUI({ message: '<img src="progressImage.gif" />' });
};
var hideProgress = function() {
$.unblockUI();
;}
/** Trigger to submit the form */
$('#submit').click(function() {
/** Show an indicator before making an AJAX request*/
showProgress();
$.ajax({
url: '/someEndpoint',
data: $.toJSON({/* some JSON param */}),
type: 'POST',
dataType: 'json',
timeout: 50000 /** Override timeout in ms accordingly */
}).done(function(data){
/** Remove the indicator once the request has succeeded and process returned data if any. */
hideProgress();
});
return false;
});
Use ajax for your process. It ll make the parallel processing for "showing gif" and completing your desired code.
You can use JQuery-AJAX with page methods this way: [1]: http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
The success callback contains a parameter with the returning data.
or you can try simply this
var actionURL = "(Your disired action e.g /index.jsp)"
$.ajax({
cache:false,
url: actionURL,
beforeSend: function( xhr ) {
xhr.overrideMimeType( 'text/plain; charset=UTF-8' );
$("#progessbar").show();
//Here you can write any code to execute before the action like gif loading etc
},
success: function( data ) {
alert("Success Conditions");
//"data" is what u gets from your target. You can see by alert(data); here
//Here you can write any code which you want to execute on finding the required action successfully
},
complete: function(){
alert("Complete Conditions");
$("#progessbar").hide();
//Here you can write any code which you want to execute on completion of the required action you given in actionURL
},
error: function(){
alert("Error Conditions");
}
});
NOTE: alerts are just for explanation, you can write your own code also
For this code you have to include jquery plugins. which can be downloaded from their official site [l]: http://jquery.com/
I have a web application which uses a lot of AJAX to display pages.
In my javascript I have a feature which gets all the elements that have a certain class (testClass). It does a bunch of stuff with these classes but that's not necessary for my problem.
At the moment my function runs when the DOM is ready and it works great. However, I need my function to run when AJAX returns a new page to the browser as it could contain elements with testClass.
Is there a way I can listen if a certain DOM element is added? I basically need a way to recognise a DOM change, when this change has happen run my function.
Or is there a way I can listen for the addition of elements with class testClass?
If it help here is a snippet of my code:
execute = function () {
var found = false;
$('.testClass').each(function () {
//bunch of code
});
}
$(document).ready(function () {
execute();
});
Try with ajax success method
$.ajax({
url: 'ajax/test.html',
success: function(data) {
$('.result').html(data);
alert('Load was performed.');
}
});
How can I fix the script below so that it will work EVERY TIME! Sometimes it works and sometimes it doesn't. Pro JQuery explains what causes this, but it doesn't talk about how to fix it. I am almost positive it has to do with the ajax ready state but I have no clue how to write it. The web shows about 99 different ways to write ajax and JQuery, its a bit overwhelming.
My goal is to create an HTML shell that can be filled with text from server based text files. For example: Let's say there is a text file on the server named AG and its contents is PF: PF-01, PF-02, PF-03, etc.. I want to pull this information and populate the HTML DOM before it is seen by the user. A was ##!#$*& golden with PHP, then found out my host has fopen() shut off. So here I am.
Thanks for you help.
JS - plantSeed.js
var pageExecute = {
fileContents:"Null",
pagePrefix:"Null",
slides:"Null",
init:function () {
$.ajax({
url: "./seeds/Ag.txt",
success: function (data){
pageExecute.fileContents = data;
}
});
}
};
HTML - HEAD
<script type="text/javascript">
pageExecute.init();
</script>
HTML - BODY
<script type="text/javascript"> alert(pageExecute.fileContents); </script>
Try this:
var pageExecute = {
fileContents:"Null",
pagePrefix:"Null",
slides:"Null",
init: function () {
$.ajax({
url: "./seeds/Ag.txt",
async: false,
success: function (data){
pageExecute.fileContents = data;
}
});
}
};
Try this:
HTML:
<div id="target"></div>
JavaScript:
$(function(){
$( "#target" ).load( "pathToYourFile" );
});
In my example, the div will be filled with the file contents. Take a look at jQuery .load() function.
The "pathToYourFile" cand be any resource that contains the data you want to be loaded. Take a look at the load method documentation for more information about how to use it.
Edit: Other examples to get the value to be manipulated
Using $.get() function:
$(function(){
$.get( "pathToYourFile", function( data ) {
var resourceContent = data; // can be a global variable too...
// process the content...
});
});
Using $.ajax() function:
$(function(){
$.ajax({
url: "pathToYourFile",
async: false, // asynchronous request? (synchronous requests are discouraged...)
cache: false, // with this, you can force the browser to not make cache of the retrieved data
dataType: "text", // jQuery will infer this, but you can set explicitly
success: function( data, textStatus, jqXHR ) {
var resourceContent = data; // can be a global variable too...
// process the content...
}
});
});
It is important to note that:
$(function(){
// code...
});
Is the same as:
$(document).ready(function(){
// code
});
And normally you need to use this syntax, since you would want that the DOM is ready to execute your JavaScript code.
Here's your issue:
You've got a script tag in the body, which is asking for the AJAX data.
Even if you were asking it to write the data to your shell, and not just spout it...
...that's your #1 issue.
Here's why:
AJAX is asynchronous.
Okay, we know that already, but what does that mean?
Well, it means that it's going to go to the server and ask for the file.
The server is going to go looking, and send it back. Then your computer is going to download the contents. When the contents are 100% downloaded, they'll be available to use.
...thing is...
Your program isn't waiting for that to happen.
It's telling the server to take its time, and in the meantime it's going to keep doing what it's doing, and it's not going to think about the contents again, until it gets a call from the server.
Well, browsers are really freakin' fast when it comes to rendering HTML.
Servers are really freakin' fast at serving static (plain-text/img/css/js) files, too.
So now you're in a race.
Which will happen first?
Will the server call back with the text, or will the browser hit the script tag that asks for the file contents?
Whichever one wins on that refresh is the one that will happen.
So how do you get around that?
Callbacks.
Callbacks are a different way of thinking.
In JavaScript, you perform a callback by giving the AJAX call a function to use, when the download is complete.
It'd be like calling somebody from a work-line, and saying: dial THIS extension to reach me, when you have an answer for me.
In jQuery, you'll use a parameter called "success" in the AJAX call.
Make success : function (data) { doSomething(data); } a part of that object that you're passing into the AJAX call.
When the file downloads, as soon as it downloads, jQuery will pass the results into the success function you gave it, which will do whatever it's made to do, or call whatever functions it was made to call.
Give it a try. It sure beats racing to see which downloads first.
I recommend not to use url: "./seeds/Ag.txt",, to target a file directly. Instead, use a server side script llike PHP to open the file and return the data, either in plane format or in JSON format.
You may find a tutorial to open files here: http://www.tizag.com/phpT/fileread.php