Cross-domain requests with jQuery Plug-In - javascript

i need to pull a small string from a diffrent site from a div with the class 'entry' (theres only one div with that class and the div doesnt have an id).
I learned about this plugin http://james.padolsey.com/javascript/cross-domain-requests-with-jquery/
But i somehow did not manage to install nor use the code to make it work.
I tried nothing but the code on the plugin page.
Where/How do i need to install the plugin? Where/How to implement the given code correctly?
Maybe a working fiddle sample would help :)
EDIT: I used this code
<script src="http://code.jquery.com/mobile/1.4.3/jquery.mobile-1.4.3.min.js"></script>
<script src="https://raw.githubusercontent.com/padolsey-archive/jquery.fn/master/cross-domain-ajax/jquery.xdomainajax.js"></script>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery.ajax({
url: 'http://news.bbc.co.uk',
type: 'GET',
success: function(res) {
var headline = jQuery(res.responseText).find('a.tsh').text();
alert(headline);
}
});
});
</script>
And i use phase5 HTML editor, so theres no error thrown, any recommandation for a different editor?
The code just doesnt produce any result, the page loads and functions as normal but no alert is shown.

OK i found a solution, here is what i did:
Added header('Access-Control-Allow-Origin: *');
in die functions.php of the wordpress site i want to acess then i used the following ajax request to pull the content:
jQuery.ajax({
url: 'http://www.somesite.wordpress.com/',
type: 'GET',
success: function(res) {
var data = jQuery.parseHTML(res);
jQuery(data).find('div.class').each(function(){
jQuery('#destination').append(jQuery(this).text());
});
}
});
I tried all of this: Getting specific element from external site using jQuery / ajax and the last answer worked for me (its the same code mentoined above).
Unfortunately i dont know why or how this works and if this is the best way, probably not - still it works somehow so thats fine by me.
If anyone sees through this and knows a better/sleeker solution, it would be very welcome!

Related

jQuery stops working after ajax loading

some info
I'm working on a webpage that can load data on multiple layouts, so user can choose which one is best. It can be loaded in a list or a cards like interface, and the data is loaded using ajax.
In this page I also have a notifier for new messages that the user received. The ajax function is new, and when page was loaded by the php scripts, the js script (that add a badge with the number of unread messages to a link on a menu item) was working ok.
I'm using HTML5, PHP, jQuery and a mySQL DB.
jQuery is imported onto the HTML using
<script src="https://code.jquery.com/jquery.js"> </script>
So it's a recent version.
the problem
Now, when I load the data onto the page using ajax, the js script won't work anymore. I had the same issue with another js script and I managed to solve it by using the delegate event binder.
But my unread messages updater runs on a time interval, using
<body onload="setInterval('unread()', 1000)">
the unread() js is quite simple:
function unread() {
$(document).ready(function(){
$('#menu_item').load('ajax_countNewMsgs.php');
});
}
it calls a php script which grabs the unread msgs count from the DB and echo into a element that jQuery will point. Hope I'm being clear.
The problem is that I cannot figure out how I would call a timed event using delegate. Without much hope I've tried
$(document).on('ready()','#menu_item', function () {
$(this).load('ajax_countNewMsgs.php');
});
That didn't work.
I read many posts about js stop working after changes in the DOM, but, again, I couldn't figure out a way to solve that, nor found a similar question.
Any help or tips would be highly appreciated.
EDITED to change second php script's name
2nd EDIT - trying to make things clearer
I tried the way #carter suggested
$(document).ready(function(){
function unread(){
$.ajax({
url: 'ajax_countNewMsgs.php',
type: 'GET',
dataType: 'html',
success: function(response){
$('#menu_item').html(response);
},
error: function(response){
//no error handling at this time
}
});
}
setInterval(unread(), 1000);
});
the ajax_countNewMsgs.php script connects to the DB, fetch the unread messages, and echoes the number of unread messages.
If I try to apply the ajax reponse to another element, say, the <body> the results are as expected: at each 1 sec , the body html is changed. So the function is working.
As I said, none of my JS changes the #menu_item. Actuallly this element is part of another php scritp (menu.php) which is imported to the top of the page.
the page structure is this way:
<html>
<head>
some tags here
</head>
<body>
<?php include (php/menu.html); ?>this will include menu with the #menu_item element here
<div id='wrapper'>
<div id='data'>
here goes the data displayed in two ways (card and list like). Itens outside div wrapper are not being changed.
</div>
</div>
</body>
</html>
Even though the elemente is not being rewritten js cannot find it to update it's value.
It's not the full code, but I think you can see what is being done.
$(document).on('ready()','#menu_item', function () {
is an invalid event listener. If you wanted to be made aware of when the DOM is ready you should do this:
$(document).ready(function () {
However I don't think that is actually what you want. Your function unread will fire repeatedly but it attaches an event listener everytime. Instead if you want to make an ajax call every so many seconds after initial page load, you should do something like this (dataType property could be html, json, etc. pick your poison):
$(document).ready(function(){
function makeCall(){
$.ajax({
url: 'ajax_countNewMsgs.php',
type: 'GET',
dataType: 'html',
success: function(response){
//handle your response
},
error: function(response){
//handle your error
}
});
}
setInterval(makeCall, 1000);
});
remove that on your unread function:
$(document).ready(function(){
WHY?
The Document is already "ready" and this document state will only fired 1x - After that the "ready state" will never ever called. Use follwing syntax:
jQuery(function($){

How to open an html page in and html div?

The question might be a little misleading as I don't want to know how to open a html document in a div ,but I asked the question as I am currently facing a problem where I can't replace the html file which I have already placed in a div
I have already placed a html file in a div using ajax like this:
$.ajax({
url: 'calender.aspx',//this is html.aspx file
cache: false,
dataType: "html",
success: function (data) {
$(".mainBar").html(data);//mainBar is the div
}
});
this file gets placed on page load i.e document.ready function ,till here everything is fine.....my trouble starts when I want to replace the file,what I do is call a javascript function say replaceFile() on button click and write the same code to replace the file (changing the url of course)
like this
function replaceFile()
{
$.ajax({
url: 'Another.aspx',
cache: false,
dataType: "html",
success: function (data) {
$(".mainBar").html(data);
}
});
}
but this doesn't work,please help me out!
I guess your binding is not working when you try to click on the content you loaded via ajax . So you might want to change the binding of onclick from
$("#someButtonId").click(function(){
replaceFile();
});
to
$(document).on("click","#someButtonId",function(){
replaceFile();
});
jQuery on works with current and future elements.
with this function you will load the page into the element named result
.load( url , data, complete(responseText, textStatus, XMLHttpRequest)] )
function replaceFile(url)
{
$('#result').load(url, function() {
alert('Load was performed.');
});
}
replaceFile('htmlfile.html');
You can load this in Firebug and set a break point at $(".mainBar").html(data); to make sure it's being called. You don't have a failure handler, so it's possible that it's actually receiving an HTTP failure code, not a success code.
I'd also look at the network traffic under the Net tab to see what the request/response looks like. That's an easy way to find out what is really going on with most AJAX calls. IE9 has similar developer tools if you want to use it and not Firefox or Chrome.

how can I handle the append() method in jQuery?

I have a page that called redirect.php, this page has several attributes that I want to send them to another page, actually I write this code :
<script type="text/javascript">
$.ajax({
url: "http://www.mysite.com/getdata.php",
context: document.body,
success: function(data) {
$('body').append(data);
}
});
</script>
But it does not work in firefox, in firefox not happens anything but in IE it worked.
when I write exact name of page for example url: "getdata.php" it work perfectly but with absolute address is not :( Why it doesn't work in firefix? any idea?
thanks for your help ...
It's a security restriction of Firefox not to allow cross-domain Ajax requests.

Javascript using ajax jquery and json not working with IE or chrome help!

I have this code that is being ignored by i.e. ive set alerts throughout the code and i've pin point the error being the ajax call
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Website</title>
<script type="text/javascript">
$.ajax({
url: "http://api.geonames.org/earthquakesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&username=demo",
success: function(data){
...code
}
});
</script>..body.. etc...
The code works perfectly on firefox.. however
the $.ajax({}); call is completely ignored in IE and Chrome.. Anyone know why? Thanks in advance...
Are you missing <script> tags, and, you know, jQuery? Also, since this is a cross-site request, make sure you're actually handling this as jsonp correctly.
Without posting your actual code I think that's the best we can do.
I can only add to what Michael Haren has already said that what you get from this URL is:
{"status":{"message":"the daily limit of 30000 credits demo has been exceeded. Please throttle your requests or use the commercial service.","value":18}}
As pointed out, you're missing the script tags as well as the actual path to the jquery file, and you need to wrap your ajax call in with document ready so...
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> // Latest jquery from google
<script type="text/javascript">
$(function() {
// -- Your Code Here
});
</script>
You have to tell add &callback=? at the end of the URL.
http://api.geonames.org/earthquakesJSON?...&username=demo&callback=?
One thing that will prevent the ajax from working in Chrome/Safari but still allow it to work in Firefox is leaving out the dataType field of the ajax command. For instance:
$.ajax({
type: 'Get',
url: "http://api.geonames.org/earthquakesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&username=demo",
success: function(data){
var jsonArray = jQuery.parseJSON(data);
alert(jsonArray.status.message);
}
});
will output the value element of the JSON array returned from that URL ONLY if ran in Firefox. To get this ajax to work in Chrome you must include the dataType field and remove the jQuery.parseJSON like so:
$.ajax({
type: 'Get',
url: "http://api.geonames.org/earthquakesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&username=demo",
dataType: 'json',
success: function(data){
var jsonArray = data;
alert(jsonArray.status.message);
}
});
If this is left out or you try to do it the other way it will appear as it is skipping over your ajax all together. I hope this fixes your problem.

Ajax fires only once,and the javascript file is loaded only once

Basically, I am trying to load the html and JavaScript file for each subpage on my website with ajax. However, the JavaScript file only loads for the first subpage that is clicked on. If I click on the next subpage, only the html document for that loads, but the javascript does not. This is from looking at the firebug console: Clicking on about first, then clicking on contact:
GET http:..../about.html?t=0.19504348425731444
GET http:..../about.js?t=0.8286968088896364
GET http:..../contact.html?t=0.8467537141462976
(!!!NO GET FOR contact.js!!!)
Anyways, I tried using live() to bind the click event but it still doesn't work.Here's the relevant snippets of my code:
$('.subpage').live('click',function(){
$('#main').css({'cursor':'crosshair'});
navsubpage = true;
subpage = $(this).attr('id');
$('.subpage').each(function(index) {
$('#'+$(this).attr('id')).fadeOut('500');
$('#'+$(this).attr('id')+'select').fadeOut('500');
});
$('#'+subpage+'h').css({'background-color':'#000','display':'block'});
$('#'+subpage+'h').animate({'width':'375px','top':'120px','left':'100px','font-size':'400%'},'500');
subtop = $('#'+subpage+'h').css('top');
subleft = $('#'+subpage+'h').css('left');
$('#pane').css({'border-left-width':'0px'});
$('#nav').css({'background':'url("images/'+$(this).attr('id')+'.jpg") no-repeat 0px 0px'});
$('#nav').animate({'left':'0px'},'4000','swing',function(){
$('#reload').show().delay(500).queue(function(){
alert("made it");
$.ajax({
url: subpage+".js?t=" + Math.random(),
dataType: 'script',
type: 'get',
});
});
});
reload(subpage);
});
$('#main').click(function(){
if(navsubpage==true){
$('#main').css({'cursor':'auto'});
$('#reload').hide();
$('#pane').css({'border-left-width':'10px'});
$('#'+subpage+'h').animate({'width':'150px','top':subtop,'left':subleft,'font-size':'200%'},'2000',function(){
$('#'+subpage+'h').css({'display':'none'})});
$('#nav').animate({'left':'415px'},'3000','swing', function(){
$('.subpage').each(function(index) {
$('#'+$(this).attr('id')).fadeIn('3000');
$('#'+$(this).attr('id')+'select').fadeIn('3000');
});});
navsubpage = false;
}
});
the reload function loads the html and is working correctly.
I am really new to ajax, javascript...etc. If any of you can help me out, that'll be great.
It's confusing that you have both the "?t=" + Math.random() combined with cache: true.
The practice of appending a timestamp to a URL is a common method to prevent caching, but then you explicitly tell it that you want it to cache. You might try removing the cache: true option, as it looks to be totally superfluous and can only cause problems (the likes of which would resemble what you're describing here).
I would reccomend trying out a jQuery ajax shortcut function $.get()
It is farly simple and might cut out a lot of uneccesary options you are setting using the full $.ajax() function
Thanks for the help guys - in the end I just decided to not mess with the queue stuff. I still don't understand why it works, but I just took out the ajax and placed it outside of $('#reload').show().delay(500).queue(function(){, eliminating the delay and queue stuff and making the ajax a separate snippet of code. now it loads correctly.

Categories

Resources