url for ajax is not working - javascript

my ajax code is
$.ajax({
url: "http://www.web-tutor99.com/ajax/template0.php",
beforeSend: function() {
$('div#divLoading').show();
},
complete: function() {
$('div#divLoading').hide();
},
success: function(data) {
var menuStyleSheets = $("head .menuStyleSheets");
var i;
for (i = 0; i < menuStyleSheets.length; i++) {
//code
$(menuStyleSheets[i]).remove();
}
$('<link rel="stylesheet" type="text/css" class="menuStyleSheets" href="styleSheets/styleSheet' + index + '.css" >').appendTo("head");
$("#menuThm").remove();
$(".showMenu").append(data);
temp = Tempo.prepare('list');
createMenu();
},
error: function() {
alert("try another theme");
},
type: "GET",
})
and in the tamplate.php file i'm just echoing the html code but the ajax call is not fetching it showing the error alert, please help me, Thank you.

Ensure your Syntax is Correct / No Cross Origin Issues
Try removing the trailing , at the end of your AJAX call (after your type parameter). It's likely that your code is expecting another parameter that isn't there :
type: "GET",
Additionally, you will want to ensure that you are making this request from the same domain, otherwise you may encounter a cross-site "Access-Control-Allow-Origin" scripting error.
Use Your Developer Tools To Examine The Request
You may want to try using the Developer Tools (F12) within your browser and try examining the Request / Response content within the Network tab (seen below using Chrome) :
This should give you any specific server-side errors within the response if they are present.

Related

Loading gif not working in IE & Chrome

I have been searching and have found some similar questions about this problem but thing still doesn't work for me at all.
Here is my function :
function ajaxRequest(url, type, datatype, contenttype, data, displayLoadingImg){
var result="";
displayLoadingImg = (typeof displayLoadingImg === "undefined") ? 0 : displayLoadingImg;
if(displayLoadingImg == 1){
$("#loadingImgAging").css("display","block");
}
$.ajax({
url:url,
type:type,
dataType:datatype,
contentType: contenttype,
data : JSON.stringify(data),
success:function(res){
result = res;
if(displayLoadingImg == 1){
$("#loadingImgAging").css("display","none");
}
},
error:function(res){
result="";
},
async : false
});
return result;
}
How I call it :
setTimeout(ajaxRequest(url,"GET","json","application/json",0,1), 500);
I've tried using beforeSend() but it did not work neither.
Note : If I delete async : false or put it to true, I'll get error Cross-Origin Request Blocked.... in my browser console.
My guess is you cannot do an ajax request with local files. There are ways to do this, but i prefer these two methods
Create a simple server
I usually use python for creating a simple server. Type this in your terminal/console: "python -m SimpleHTTPServer 9081" (or any port number you want to). Then, just open your localhost referring to your specified port.
Open chrome in --allow-file-access-from-files mode
or create a batch file using this following code in Windows. Chrome must be restarted before the configuration takes place.
start "chrome" "C:\Program Files (x86)\Google\Chrome\Application\chrome" --allow-file- access-from-files
exit
I assume you are making a AJAX call to another domain file for which you have to use JSONP as your dataType. Doing this you then dont have to make async = false.
Try this:
before you do the ajax call set display to block, after the ajax call(success or error doesnt matter) - just before you return - set display to none. You dont need displayLoadingImg and the code to handle it. Or do I miss ssomething?

Safari caching my AJAX request

I want one of my pages to fire a javascript AJAX call every time the user loads the page, even if he is coming back to a page in the browser's history. So I've put this function in my jsp (I am using jQuery Mobile):
$(document).on(
"pageinit",
"#base-layout",
function() {
$.ajaxSetup({ cache: false });
myFunction(urlEndpoint);
});
With only this code, and the javascript function:
function myFunction(url) {
var currentTime = new Date();
var n = currentTime.getTime();
var epUrl = url + "?nocache" + n;
$.ajax({
url : epUrl,
dataType: "json",
method: "post",
headers : { "cache-control": "no-cache" },
cache:false,
}).done(function(data) {
//do something
});
}
I managed to get Chrome, Firefox and IE to actually fire the ajax call even when pressing the back button. But I can't manage to get Safari to show this behavior. No matter what I try, it's never going through my server side function.
As you can see, I tried disabling cache for the ajax call, and changing the endpoint url by appendind the current time, to no effect. I even tried to put
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
on my controller method, but it didn't work either. I can't get Safari to call this function when coming back to a page in history.

Google Hosted Libraries is unnecessarily using cache breakers

I am using the following code on our dashboard to refresh it constantly without flicker How can I refresh a page with jQuery?
:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
setTimeout(function() {
$.ajax({
url: "",
context: document.body,
success: function(s,x){
$(this).html(s);
}
});
}, 4000);
</script>
However, this is causing the javascript to reload each time too due to some cache breakers.
Google is sending with the following headers:
In the interest of not getting myself and my clients blocked from Google (might as well become a Mennonite at that point) is there a way use Google CDN without causing these extra requests?
Warning untested:
$.ajax({
url: "",
dataType: "text", //dont parse the html you're going to do it manually
success: function(html) {
var $newDoc = $.parseHTML(html, document, false); //false to prevent scripts from being parsed.
$('body').replaceWith(newDoc.find("body")); //only replace body
}
});
A better solution would be to template your body.

Javascript: Why sometimes alert() does not work but console.log() does?

From time to time, I face a very intriguing bug. My javascript code does not display an alert(msg) during execution, but if I use a console.log(msg) it does show up in the console. What could prevent alert() from displaying?
Thanks a lot
This is a very common problem, and everyone has faced this problem atleast once.
The reason alert() does not work is because previously you have checked "prevent this page from creating additional dialoug" checkbox.
lets take a look at this code.
<script type="text/javascript">
var js_name = ['elem1', 'elem2']
for (var i = 0; i < js_name.length; i++) {
alert(js_name[i]);
};
</script>
There will be two alert boxes if you run the code. If you check the "prevent this page from creating additional dialoug" checkbox and then refresh the page again you won't get alert box ever again.
Solution is you need to close that webpage and reopen again in the browser(don't need to close the entire browser).
I am assuming you are using chrome.
Internet Explorer or FireFox doesn't have this checkbox feature.
If you override alert function so it won't work
alert = function()
{
...
};
alert('hello') // won't show any alert
To my knowledge alert() is always shown unless it is repetitive in which case you are asked if you want to continue showing alerts.
I suppose the specifics on how this is handled depends on your browser. Care to share any more details? :)
This also happens in ColdFusion. If you use anywhere after the script tag a cflocation tag (instead of location.href) the alert will not show.
This can also happen in Firefox if you have Dev Tools open and Responsive Design Mode enabled. It sounds like it's a bug.
In Firefox: go to Options -> Content and uncheck "block pop-up windows" check box. Restart browser.
Another reason why alert, confirm, and prompt may be ignored by the browser, is if the document is in an iframe that has a sandbox-attribute without allow-modals in its value.
For example, Firefox silently ignores this, however Chromium shows a warning.
If you try to execute javascript alert function in a Chrome browser address URL, you will not get the message if the the tab has no page previously loaded.
You will get the alert box only if it is not a fresh tab.
If there exists a web page that is previously loaded, and then you try to run the javascript in the address bar, you will get the expected result.
Hope it clarifies this difficult to detect behavior in Chrome.
If you have a location.reload() after the alert() function as shown below, JavaScript somehow skips the alert and reloads the page.
$.ajax({
url:'xxx',
type : 'POST',
data : datavalues,
dataType: 'json',
contentType: 'application/json',
success: function(response){
if(response.status == '200')
{
alert("updated");
}
}
});
location.reload();
To tackle this situation, I moved the reload function into the if block and this solved the issue.
$.ajax({
url:'xxx',
type : 'POST',
data : datavalues,
dataType: 'json',
contentType: 'application/json',
success: function(response){
if(response.status == '200')
{
alert("updated");
location.reload();
}
}
});
I have a similar problem here, when I replace the console log with "alert" it is not working but console.log does work.
The not working code is :
request(options, function(error, response, body) { // Requesting API
var statusCode = response.statusCode;
if(statusCode === 200){
alert("Success");
} else {
alert(error);
}
and the working code is:
request(options, function(error, response, body) { // Requesting API
var statusCode = response.statusCode;
if(statusCode === 200){
console.log("Success");
} else {
console.log(error);
}

javascript / ajax querying

I currently have a web page that uses javascript, however; when I use my Ajax to move towards the DB my responseText is always empty.
js to make the flag and send query
objAjaxUpdates.main_flag = "getNames";
objAjaxUpdates.SendQuery(query);
next in the flow
(The url is an aspx file)
this.SendQuery = function(data) {
this.Initialize();
if (this.req != null) {
//alert(data);
//alert(this.url + " " + this.main_flag);
this.req.open("POST", this.url);
this.req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
this.req.onreadystatechange = this.processData;
this.req.send(data);
}
}
Next
this.processData = function() {
if (objAjaxUpdates.req.readyState == 4) {
if (objAjaxUpdates.req.status == 200) {
if (objAjaxUpdates.req.responseText == "") {
alert('No Return');
}
else {
...
Any help would be appreciated.
I don't know the library you are using. But the procedure looks correct to me. (There are libraries like jQuery which avoids you to work on the low-level AJAX API, checking response code and so on.)
I advise you to work with something like Firebug for Mozilla, or the Chrome Developer Tools to "debug" your AJAX machinery.
There still is that good old technique:
First test the requests to the server manually.
Then, do a dumb AJAX request.
At the end, test both components.

Categories

Resources