I have a ajax post request, which dynamically loads some math content like below
// post comment
$post_comment.on("click", "[data-submit='post-comment']", function() {
$.ajax({
success: function(response) {
if(response.success) {
$('#comment-list').load(' ' + '#comment-list');
MathJax.Hub.Queue(["Typeset",MathJax.Hub, "comment-list"]);
}
},
});
});
The mathjax command above mentioned is unable to render the math script loaded dynamically.
While when I execute the same command on command-line, its working!!
It would be nice if someone explains why this is happening and how to fix
The load() method uses ajax which executes asynchronously meaning after the request is sent to the server the statements after that will continue executing without waiting for the response from server comes back.
In this case when the load request is sent, before #comment-list is populated with the response the MathJax.Hub.Queue(["Typeset",MathJax.Hub, "comment-list"]); statement will get executed, thus it is not rendering anything.
The solution is to use a callback provided by load to run the statements which has to work on elements loaded by the ajax request
Ex
$('#comment-list').load(' ' + '#comment-list', function(){
MathJax.Hub.Queue(["Typeset",MathJax.Hub, "comment-list"]);
});
Related
I read in w3schools that there are several ways an external script can be executed:
If async is present: The script is executed asynchronously with the rest of the page (the script will be executed while the page continues the parsing)
If async is not present and defer is present: The script is executed when the page has finished parsing
If neither async or defer is present: The script is fetched and executed immediately, before the browser continues parsing the page.
So, if i understood correctly, since i have the following script in the head section of my html file
without using async or defer it should first be executed and then the browser will continue parsing.
<script type="text/javascript" src="js/display.js"></script>
display.js
$.ajax({
url:"fetch_items.php"
});
fetch_items.php fetches some items from the database and puts them in an array $_SESSION("my_array").
So inside the body section of the html folder i use the values that reside in $_SESSION("my_array") to show some content.
<?php
if(isset($_SESSION["my_array"]))
{
?>
<!-- html code echoing values from session -->
<?php
}
?>
but $_SESSION["my_array"] isn't set yet so the content doesn't appear. (if i reload the page the content will appear correctly)
Why is this happening? How can i ensure that the script has completed it's execution before the body loads? is the following refers only to scripts :
If neither async or defer is present: The script is fetched and executed immediately, before the browser continues parsing the page.
AJAX stands for "Asynchronous JavaScript and XML". So it makes asynchronous request from your browser by running your javascript code. Your current code makes request from browser to server. Then server saves your array to session by using your PHP code and not reloads the page. That is why your array not printing immediately.
Bad solution: Refreshing page on success method of your ajax request.
Better solution: Don't keep your array in session if it is not really necessary. Return your array in the method at "fetch_items.php". Then print the array using success callback of the ajax request.
Here is an example for usage of success and print method: Ajax response inside a div
For more information you can read jquery api documentation: http://api.jquery.com/jquery.ajax/
Try putting async : false in your ajax call parameters.
This is because of asynchronous calls. I encountered similar issue and fixed it by adding async:false in AJAX. You may see the below code fragment I used.
$.ajax({
type: "GET",
url: "fetch_items.php",
data: {},
async : false, // make it false
success: function (html) {
alert (html);
}, error: function (error) {
alert (error);
}
});
I'm trying to work on a clickable DIV from some vertical tab panel. What I want is when clicking on a specific DIV call a static method to do some tasks, so I did this:
<div class="tabbable tabs-left">
<ul class="nav nav-tabs">
<li onclick="myEvent()">Tuttle</li>
then, my JavaScript code:
<script>
function clickEvet() {
alert("alert test message");
#MyProject.myMethod()
}
</script>
Calling the function "clickEvent()" works. The problem is that #MyProject.myMethod() is called no matter what, in other words, #MyProject.myMethod() is being executed as soon the page loads. I want it only when I click on my div.
This is from a cshtml file and I'm using .net 4.5
SOLUTION:
I'm editing my question to post the answer for future references...:
Thanks to other comments I finally understood how to work with Ajax and make it work. Here is the solution:
<script>
function vaxGUID() {
$.ajax({
type: 'POST',
url: "/VAXBean/bmx",
data: '{"Name":"AA"}',
contentType: 'application/json; charset=utf-8',
dataType: 'html',
success: function (data) {
bmx = "http://www.vitalbmx.com";
$('a.varURL').attr('href', bmx);
GUID = data;
alert("Good response - " + data + " - " + bmx);
},
error: function (data, success, error) {
alert("Error : " + error);
}
});
return false;
}
</script>
With this Ajax method I'm making the call to some static method in the background
I want it only when I click on my div. <= When you click on the DIV that is being done in the browser after the request has been sent. There is no way for the browser to call directly back inside a method in your application. The HTML has already been generated and sent by the server in the request to the client and that is where that communication cycle stops.
If you want a click (or any other event) to do something specifically on the server you need to do one of these standard actions that are used to communicate back to the server.
Create an AJAX request back to your MVC Controller to get data (or whatever).
Create a link (standard url)
Create a form post back
And of course the #MyProject.myMethod() executes every time your page is rendered because your razor view is a code file that is being interpreted line by line so it can be rendered and sent to the client that requested it. What would be valid here is if myMethod output some javascript or something that the browser could understand and do something with, that is what would be expected.
You can't do it. All # (Razor) expressions is resolved during page rendering on server. That's why you method is called.
Probably, you need to make an Ajax call.
Look for a more detailed explanation here:
How do I call a static method on my ASP.Net page, from Javascript?
I am visiting a site that emits a (large) JSON response. A click triggers the request:
casper.then(function li10() {
casper.click(SEARCH_BUTTON_CSS);
});
But according to my web proxy, the client closes the connection before receiving the entire response. I've tried waiting for the URL to appear. It waits for the URL as expected, but that doesn't appear to be sufficient:
casper.then(function li11() {
casper.waitForUrl(/\/search-results\/p\?/,
function() {
var search_url = casper.getCurrentUrl();
console.log('found search results, url = ' + search_url);
},
function() {
console.log('failed to find search results');
casper.exit();
},
10000);
});
So: what is something dependable that I can wait for that will guarantee that the JSON code has completely loaded before proceeding to the next step?
I'm assuming that you would fill a search field, click a button and the JavaScript makes an Ajax request to receive a JSON response to then parse it and display the results.
casper.waitForUrl() is used to wait for the page URL to change to the specified one. It has nothing to do with resources that are loaded separately such as AJAX responses.
You either need to
find out the specific URL that is requested for the search action and use casper.waitForResource() to wait for that specific resource or
devise a specific selector that appears when the search data is parsed and injected into the page with casper.waitForSelector().
Well I would like to check answer from server every 5 seconds. But my success function inside $.ajax just does not work. Although ajax sends requests and gets response. Time limit is not exceeded since function is run every 5 seconds and response is received within 1 second.
If i put something inside checkMyCreatedGame function after $.ajax it does work but success function does not.
var checkMyGame;
checkMyGame =setInterval(checkMyCreatedGame,5000);
var checkMyCreatedGame = function(){
$.ajax({
url :'../cgi-bin/lobby.py',
type :"GET",
cache :false,
data {
"checkMyGameId":createdGameId,
"player":playerName
},
dataType:"json",
success:function(jsonData){
console.log(jsonData)
}
});
};
Here is my firebug console logs when I run this code (do not pay attention to what is above those gets):
Here is same screenshot but not resized by stackoverflow: https://i.stack.imgur.com/e9HBa.png
As you can see console.log inside success function is not executed.
In your AJAX call, you tell jQuery to expect JSON data:
dataType:"json",
Then your server returns non-JSON data:
waiting
jQuery then tries to parse it as JSON, and unsurprisingly, fails. If you tell jQuery to expect text instead, it will work fine:
dataType:"text",
The message of this is: if you are finding that an AJAX call is failing silently, put an error handler in. If you had, you would have received a message telling you that you had a parsererror.
This question already has answers here:
Sequencing ajax requests
(10 answers)
Closed 9 years ago.
I am working a script, I need to loop an array of AJAX requests:
$('#fetchPosts').click(function(){
for(var i=0; i < link_array.length; i++) {
settings = {
// some object not relevant
}
var status = main_ajaxCall(settings, i); // ajax call
}
});
function main_ajaxCall(settings, i) {
$.ajax({
type: "POST",
url: "../model/insert.php",
data:{obj_settings: settings},
dataType: "json",
cache: false,
success: function (data) {
// some handeling here
return 0;
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
return 1;
},
};
Why does the AJAX requests fire instantly? It does not seem to wait for a response from model/insert.php, is there any way to force it to wait for a response before firing the next AJAX request?
EDIT 1:
It seems I wasnt clear, sorry, I dont want it to wait, I want to queue up the calls.
I cant make the call in one request, this is impossible in my current situation.
Set async to false if you want to wait for a response (default: true)
$.ajax({
async: false,
...
http://api.jquery.com/jQuery.ajax/
If you do not want blocking, you can set a success handler function using .ajaxComplete(), and you have to keep track of active AJAX connections if you want to wait for all to complete - How to know when all ajax calls are complete
The best solution would be to minimize the number of AJAX requests to one. If you have to make a loop of AJAX requests, the logic could be simplified somewhere (put that in the server perhaps?)
EDIT 1: (In response to OP edit)
If you want to queue the AJAX requests, this question has been answered before here:
Sequencing ajax requests
Queue ajax requests using jQuery.queue()
You could also use these libraries (all you needed to do was Google):
https://code.google.com/p/jquery-ajaxq/
http://codecanyon.net/item/ajax-queue-jquery/full_screen_preview/4903957
http://schneimi.wordpress.com/2008/03/10/multiple-ajax-requests-problems-and-ajaxqueue-as-solution/
It fires instantly and doesn't wait around because that's what AJAX does best (The first A stands for asynchronous).
The request to a server could take a long time to respond, and in most cases, don't want user's browser's freezing up or stopping them from doing anything else. If you do, you could probably just use a normal request.
This is the reason you give it functions for success error, so it can call them when the server responds.
If you want nothing to be able to happen in the browser while you're calling insert.php, you could drop an overlay (eg. dark div) over everything with a loading image and remove it on success.
Maybe replace the $('#fetchPosts') element with "loading..." text and then reverse it when done. Hiding visibility of the fetchPosts element and adding a different "loading.." element is a nice way.
Your AJAX call will wait for a response from the server, but wil do so asynchronously. That is, your script will continue to execute rather than block the browser while the server responds. When the server responds (or when the request times out - usually several seconds) your success: or error: functions will then execute.
The effect of your code here is to create several concurrent requests based on the link_array length.
You could specify async:false in your AJAX call, but this would freeze the browser while all the AJAX calls are made.
You should rewrite your code to execute all the handling as part of your success: function. I'd recommend you rewrite your code to assemble all your request into one, and make one AJAX call rather than several, and have the server return all the responses as one block. I can't suggest exactly how you do that - it's implementation dependent.
EDITED:
In response to your clarification, if you want them to be called in order, you'll need the success function to call the next one. You'll then have a chain of success calls the next, whose success calls the next, whose success calls the next.. etc until the last one which does the final processing. One way would be to pass the call number to the success function.