304 not modified, Ajax is not working? - ajax

<script>
var xmlHttp =new XMLHttpRequest();
var url= "summary.txt";
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
var myArr = JSON.parse(xmlHttp.responseText);
myFunction(myArr);
}
xmlHttp.open("GET", url , true);
xmlHttp.send();
} function myFunction(arr)
var output="";
var i;
for(i=0;i<arr.length;i++){
output+='<p>'+arr[i].title+arr[i].image+arr[i].price+'</p>';
}
document.getElementById("proTab").innerHTML = output;
}
</script>
I stored all both the HTML and JSON in the htdocs folder, did xampp start and made sure Apache and mysql were running on the control panel. I then typed the link to the html using the "localhost/" to get to the html but the page was blank. Sorry for all the details.
Console says 304 Not modified. What should I do?

My guess is that you are using IE, which caches AJAX GET requests aggressively. I would suggest changing to using POST for the AJAX request.
Another alternative if you must use GET requests. You can add a unique querystring value to each GET request like this:
var url = 'summary.txt' + '?' + Math.random()*Math.random();

I used this for jQuery AJAX:
$.ajaxSetup({
// Disable caching of AJAX responses
cache: false
});
I think you can find how to use this for JS without jQuery. So the idea is to clear cache before sending the request, because server responds that nothing changed and sends 304 NOT MODIFIED instead of 200 OK. Namely, your summary.txt hasn't changed (not modified), so that's what server telling you.

Related

AJAX response returns current page

I was searching for a similar issue for a while now, but none of the solutions worked for me (and I couldn't find exactly the same issue).
First of all, the website I'm working on is running on Zend Framework. I suspect that it has something to do with the issue.
I want to make a pretty basic AJAX functionality, but for some reason my response always equals the html of the current page. I don't need any of Zend's functionality, the functions I need to implement could (and I'd prefer them to) work separately from the framework.
For testing purposes I made it as simple as I could and yet I fail to find the error. I have a page "test.php" which only has a link that triggers the ajax call. Here's how this call looks:
$('.quiz-link').click(function(e){
e.preventDefault();
$.ajax({
URL: "/quiz_api.php",
type: "POST",
cache: false,
data: {
'test': 'test'
},
success: function(resp){
console.log(resp);
},
error: function(resp){
console.log("Error: " + reps);
}
});
});
And this quiz_api.php is just:
<?php
echo "This is a test";
?>
When I click on the link I get the entire HTML of the current page. "This is a test" can't be found there. I'm also getting an error: "Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/."
I reckon it has to do with the JS files that are included into this HTML response, but I've also tried setting "async: true" and it didn't help.
I would like to avoid using Zend Framework functions for this task, because I'm not well familiar with it and even making a simple controller sounds rather painful. Instead I want to find out what's causing such behavior and see if it can be changed.
PS: I've also tried moving quiz_api.php to another domain, but it didn't change anything.
I know that it might be an older code but it works, simple and very adaptable. Here's what I came up with. Hope it works for you.
//Here is the html
Link Test
<div id="test_div"></div>
function test(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// This is the php file link
var url = "quiz_api.php";
// Attaches the variables to the url ie:var1=1&var2=2 etc...
var vars = '';
hr.open("POST", url, true);
//Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange =
function(){
if(hr.readyState == 4 && hr.status == 200){
var return_data = hr.responseText;
console.log(return_data);
document.getElementById('test_div').innerHTML = return_data;
}else{
document.getElementById('test_div').innerHTML = "XMLHttpRequest failed";
}
}
//Send the data to PHP now... and wait for response to update the login_error div
hr.send(vars); // Actually execute the request
}
you can change the whole page with a document.write instead of changing individual "div"s

Magento add to wishlist via ajax is not working with secure url (SSL installed)

I am using magento add to wishlist via ajax
it's working fine but after install SSL on server and make secure magento checkout pages from admin.
It give me not any response from ajax (302 Found).
But if i open this url in new tab then it's working fine.
When i use https in request url then it gives me the following html response "Reload the page to get source for: REQUEST URL" and without https there is no response to display.
here below the code which i used for :-
function additemtowishlist(wId,pId)
{
var wishlisturl = 'wishlist/index/ajaxadd/product/'+pId;
var wishlistparam = '/?wishlist_id='+wId;
var url = '<?php echo Mage::getUrl("",array('_secure'=>false))?>'+wishlisturl+wishlistparam;
new Ajax.Request(url, {
dataType: "json",
onSuccess: function(response){
if (typeof(response.responseText) == 'string') eval('data = ' + response.responseText);
if (typeof data.product_id != 'undefined') {
var htmltoshow = '<div class="messages successmessage"><div class="success-msg"><span>'+data.message+'</div></div>';
jQuery("#wishlistresulthome-"+data.product_id).html(htmltoshow);
jQuery("#customwishlist-"+data.product_id).css('visibility','hidden');
}
else {
alert(Translator.translate('Error happened while creating wishlist. Please try again later'));
}
}
});
}
Thanks in advance.
Hello Simranjeet you may try this :-
function additemtowishlist(wId,pId)
{
var wishlisturl = 'wishlist/index/ajaxadd/product/'+pId;
var wishlistparam = '/?wishlist_id='+wId;
var url = '<?php echo Mage::getUrl("",array('_secure'=>false))?>wishlist/index/ajaxadd/product/';
new Ajax.Request(url, {
method: 'post',
parameters: {'wishlist_id':wId,'product_id':pId },
onSuccess: function(response){
if (typeof(response.responseText) == 'string') eval('data = ' + response.responseText);
if (typeof data.product_id != 'undefined') {
var htmltoshow = '<div class="messages successmessage"><div class="success-msg"><span>'+data.message+'</div></div>';
jQuery("#wishlistresulthome-"+data.product_id).html(htmltoshow);
jQuery("#customwishlist-"+data.product_id).css('visibility','hidden');
}
else {
alert(Translator.translate('Error happened while creating wishlist. Please try again later'));
}
}
});
}
I discovered that ajaxToCart has ssl functionality built into it, but if the theme developer was lazy they may have neglected to include the code that tells ajaxToCart that ssl is enabled. I found it in the following code from ajax_cart_super.js.
function ajaxToCart(url,data,mine) {
var using_ssl = $jq('.using_ssl').attr('value');
if(using_ssl==1) {
url = url.replace("http://", "https://");
}
..
..
}
As you can see, ajaxToCart will replace the http with https, but only if there is an element with the class using_ssl and value=1. The developer who made my theme didn't include that element, so when the ajax request points to an unsecure page that should be secure, the ajax response won't work in jquery.
So for me, the quick fix was to just add this element onto my pages. I know this site will always have ssl enabled so I simply hard coded it into my template as shown below.
<input type="hidden" class="using_ssl" value="1" />
Once that was there, the javascript picked up the value and did the replacement. So now it works fine for me by just adding that into the template. If you are a theme developer and you want users to be able to switch this on and off, you may want to check against the settings in the admin. Although you may be on an insecure page, it will tell you if ssl is enabled in the backend, which would require this fix to be added.
I haven't tested the following but I think it would look something like this...
if(Mage::app()->getStore()->isCurrentlySecure()){
echo '<input type="hidden" class="using_ssl" value="1" />';
}
BTW, after years of appreciating stackoverflow solutions, I am making my first post here. Thanks to all contributors, the help is great and I'll try to pay it back now. :)
Try update your javascript url variable, by setting _secure to true value.
please try with below with your wishlist url just change instead of my custom action
Mage::getUrl('',array('_secure'=>true))
I think that gets you the base secure url, I believe.
Mage::getUrl('customer/account/login',array('_secure'=>true))
Will get you to the login page. In other words,
Mage::getUrl('module/controller/action',array('_secure'=>true))

Some code that i don't understand of the ajax

The variable xmlhttp=new XMLHttpRequest() is initialed. the following code :
function makerequest(serverPage,objID){
var obj=document.getElementById(objID);
xmlhttp.open("GET",serverPage);
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status ==200){
obj.innerHTML = xmlhttp.responseText;
}
}
xmlhttp.send(null);
}
i am sorry i am a new learner of ajax, in the if condition, why it add xmlhttp.readyState == 4. at the function's end there is using xmlhttp.send(null); could i delete them. thank you.
Well, you want to send the ajax request that you generate, so since you're using get, null is an acceptable argument. If you use post, you should pass the querystring in the send method. More here.
If you delete the readyState condition then you could end up with the ajax returning nothing since the page would not yet be ready. See more here.
EDIT: Sample argument for POST send method:
xmlhttp.open("POST","ajax_test.asp",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=Henry&lname=Ford");

Cross-Domain Requests with jQuery

For a project I need to get the source code of web page of different other domains.
I have tried following code:
$('#container').load('http://google.com');
$.ajax({
url: 'http://news.bbc.co.uk',
type: 'GET',
success: function(res) {
var headline = $(res.responseText).find('a.tsh').text();
alert(headline);
}
});
Still I am not getting any results but just a blank alert box.
By default all browsers restrict cross-domain requests, you can get around this by using YQL as a proxy. See a guide here: http://ajaxian.com/archives/using-yql-as-a-proxy-for-cross-domain-ajax
For security reasons scripts aren't able to access content from other domains. Mozilla has a long article about HTTP access control, but the bottom line is that without the website themselves adding support for cross-domain requests, you're screwed.
This code is Working Perfectly with the help of JQuery and YQL
$(document).ready(function(){
var container = $('#target');
$('.ajaxtrigger').click(function(){
doAjax($(this).attr('href'));
return false;
});
function doAjax(url){
if(url.match('^http')){
$.getJSON("http://query.yahooapis.com/v1/public/yql?"+
"q=select%20*%20from%20html%20where%20url%3D%22"+
encodeURIComponent("http://www.yahoo.com")+
"%22&format=xml'&callback=?",
function(data){
if(data.results[0]){
var data = filterData(data.results[0]);
container.html(data);
} else {
var errormsg = '<p>Error: could not load the page.</p>';
container.html(errormsg);
}
}
);
} else {
$('#target').load(url);
}
}
function filterData(data){
data = data.replace(/<?\/body[^>]*>/g,'');
data = data.replace(/[\r|\n]+/g,'');
data = data.replace(/<--[\S\s]*?-->/g,'');
data = data.replace(/<noscript[^>]*>[\S\s]*?<\/noscript>/g,'');
data = data.replace(/<script[^>]*>[\S\s]*?<\/script>/g,'');
data = data.replace(/<script.*\/>/,'');
return data;
}
});
The solution for your case is JSON with padding or JSONP.
You will need an HTML element that specified for its src attribute a URL that returns JSON like this:
<script type="text/javascript" src="http://differentDomain.com/RetrieveUser?UserId=1234">
You can search online for a more in-depth explanation, but JSONP is definitely your solution for this.
Do the following steps.
1: Add datatype:jsonp to the script.
2: Add a "callback" parameter to the url
3: Create a javascript function with name same as "callback" param value.
4: The output can be received inside javascript function.
Found one more solution for this :
function getData(url){
if(url.match('^http')){
$.get(url,
function(data){
process(data);
}//end function(data)
);//end get
}
}
This is really a pretty easier way to handle cross-domain requests. As some of the sites like www.imdb.com rejects YQL requests.

Spring MVC and Ajax Operation using JQuery

I have a JSP page called CreateProcessGroup.jsp and I use an annotation controller to map requests to CreateProcessGroup.htm to that page. But I'm having an interesting issue when I request the page from browser it works, when send a request using jQuery $.get method I get 404 (CreateProcessGroup.htm not found) is there a difference between two requests?
My JSP page just under WebContent dir and JS file under WEBContent/Jquery my function sending the request like below:
function SendCreateProcessGroupRequest()
{
var pid = $('#pid').val();
var description = $('#processGroupDescription').val();
var x = "/CreateProcessGroup.htm";
alert(x);
$.get(x, { pid: 62, description: description },
function(data){
alert("Data Loaded: " + data);
});
}
Do I need to give the URL as ../CreateProcessGroup.htm? Indeed I tried:
/CreateProcessGroup.htm
../CreateProcessGroup.htm
/../CreateProcessGroup.htm
../../CreateProcessGroup.htm
/../../CreateProcessGroup.htm
My guess is DispatcherServlet can not map Ajax requests to Controllers but this is stupid isn't it?
How can i get rid of the situation?
Thanks all.
Try this instead:
var x = "CreateProcessGroup.htm";
If the page you're requesting is beside the one making the request there's no need for a path in front, it will (by default) make a request to the same path just with that page/handler on the end.

Resources