Jquery Ajax doesnt work - javascript

I have the following div in my html
<div class="result">loading</div>
And my javascript is as follows.
$(document).ready(function() {
$.ajax({
accept: 'application/rss+xml',
url: 'http://www.madhyamam.com/taxonomy/term/19/rss.xml',
success: function(data) {
$('.result').html(data);
}
});
});
But for some reasons.. it doesnt seems to work.
In jsfiddle
XML returned(firebug):
XML Parsing Error: no element found Location:
moz-nullprincipal:{9ec69805-af82-4f95-979a-f8e68d415124} Line Number
1, Column 1:
^
Solution
*I bye-passed the problem using yahoo pipe. And it worked fine.*

You can't make Ajax requests to URLs that have not the same domain, port and protocol as the current page. The Same Origin Policy forbids it.
The most common workaround is having a server-side script that pulls the content, and serves it through Ajax.

As Pekka mentioned, we guess your problem is that Ajax cannot make request on other domain URLs. You have to use server-side script for that.
Example of small php server-side script for testing (from Jquery Minime Feed library):
<?php
header('Content-type: text/xml; charset=utf-8');
$url = htmlspecialchars($_GET['url']);
echo file_get_contents('http://'.$url,0);
?>
Then you can call something like
$.ajax({
accept: 'application/rss+xml',
url: 'http://youserver/getfeed.php?url=http://www.madhyamam.com/taxonomy/term/19/rss.xml',
});
However, it seems you want to show rss feed in your page. I went to same issue and ended using Jquery Minime Feed library, which help you doing the job:
$('#test1').minimeFeed('http://index.hu/24ora/rss/');
Automatically use server-side script if needed, and produce quite nice output. See demo here

Related

PHP (or something else) adding unwanted HTML to my output [duplicate]

I've got a strange problem where I'm trying to write a PHP page that returns some JSON to a Jquery AJAX call. Problems is that despite setting the content type to application/json, the response always seems to include the HTML header.
Here's the PHP code:
// some code that generates an array
header("Content-type: application/json");
echo json_encode($return);
Then in Javascript:
$.ajax({
url: '/VAPHP/services/datatable.php',
dataType: 'json',
data:
{
type: 'invoices'
},
success: function(data)
{
// show a message saying it's been sent!
alert('Success!');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert('Error!');
}
});
The response always seems to be something like this:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html>
<head>
<title></title>
</head>
<body>
{"aaData":[["2007-08-01","91109507","Invoice","10.000000","AUD"],["2007-08-02","91110103","Invoice","5.000000","AUD"],["2007-08-02","91110122","Invoice","305.000000","AUD"],["2007-08-02","91110129","Invoice","320.000000","AUD"],["2007-08-03","91111146","Credit
for Returns","10.000000","AUD"],["2007-08-06","91111895","Credit
for Returns","320.000000","AUD"],["2007-09-03","91128486","Credit
Memo","5.000000","AUD"],["2007-09-03","91128487","Credit
etc, etc
And according to the response header it certainly thinks it's JSON:
HTTP/1.1 200 OK
Content-Type: application/json
Server: Microsoft-IIS/7.5
X-Powered-By: PHP/5.3.3
Whenever I run the code and it alert "Error!" gets fired every time, which is understandable...
Anyone got any ideas why the HTML is being included in the response?
Calling header() actually has nothing to do with HTML-code being returned in the response.
header() is used to set HTTP-headers, while HTML-code (<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">) is sent in the body of HTTP response.
So the line of code
header("Content-type: application/json");
does his job correctly because response contains correct content type:
Content-Type: application/json
So what's wrong? Probably you have code that is executed before the code that deals with json. You should send only json encoded message in your response without any HTML tags and terminate the script using exit or die. Try to locate the code that sends HTML tags and put your code before it.
Ok, I found my own answer, looks like I had tidyhtml turned on inside my PHP.ini file, and had a
ob_start("ob_tidyhandler");
inside one of my global packages. Commented that out and it all works fine. Thanks for your time everyone!
Have you tried commenting the whole "header(...)"-part? It should work without it. The AJAX-call gets everything the PHP-program outputs, in this case including the header.
I feel somepart of your code is emitting the HTML DTD and the head part automatically for all responses from the php codebase. Are you using a framework ? If so which one ? The fact that the json.txt works is indicative that nothings wrong with js, browser or any proxies in between.
I suggest you debug the php code flow to see where this part is getting added to the html response.
There is probably something posting headers before you do. Can you provide more of the php code for this?Remember that a single white space outside of the php tags forces the output of headers ( http by default).

Javascript view source html of another website

I'm currently working on a simple webcrawler that will show all of the links the given site has. For example, this is what I would like my program to do:
-you give it a url : http://www.example.com/
-then the program gets the html source and looks for all of the <a href=...></a>tags
-finally, all of the links are shown to the user
To do this, I am using simple javacsript with jQuery, and am currently stuck on a $.ajax() call:
$.ajax({
url:"http://example.com",
dataType : "jsonp",
crossDomain : true,
success : function(data){
console.log(data);
}
});
This throws Uncaught SyntaxError: Unexpected token < error and I don't know how to fix this.
Is this behavior actually possible? If it's not, how can web-browsers actually show source code of any site? And if this is not the right way of getting HTML source, what is the right way?
Thanks for your attention
You can set it up with php by creating a “proxy”. You can look it up on the web, but I recall it being something like:
PROXY.PHP
<?php
print file_get_contents($_POST[‘url’]);
?>
ON JQUERY
var yourURL = “your url here”;
$(“div”).load(“proxy.php?url=“+yourURL)
Feel free to ask for any doubt you may have
Hope it helps :D

ajax doesn't work on remote server

I have this part of ajax code on my windows8
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js "></script>
<script>
$(document).ready(function(){
$('#next_Button').click(function(){
var text = document.getElementById("textbox");
var query = text.value;
$('#response').html("<b>Loading response...</b>");
$.ajax({
type: 'POST',
url: 'http://192.168.92.131/search2/info.php',
data: { query : query }
})
.done(function(data){
$('#response').html(data);
alert("sent query");
})
.fail(function() {
alert( "Posting failed." );
});
return false;
});
});
</script>
and php code on my virtual Ubuntu machine
echo $_POST['query'];
IP address is correct and it's always fixed. But ajax always says 'posting failed'. when I put html code on server and just set url :'search2/info.php'
it works. but when it's remote server with http:// ipaddress / search2 / phpname it doesn't work. By the way my php code is in var/www/html/search2 hosted on apache.
Is this problem from ajax ? even when I click on this complete url it shows server page! but ajax can't use this direct url to .php !
Ajax has a cross domain protection, to prevent loading from domain others than then one you browse to.
This is a security feature.
I suggest you read about it a bit here:
jQuery AJAX cross domain
And there are many other questions on the subject.
I 'm really glad to find it myself !!
I 'v open .html by double click (it was really wrong and I never noticed) and now I understand open it on localhost or 127.0.0.1 !it works properly .
before , alert shows it works but there were no answer from server ...
And also it printed whole page!! see , I had lots of comments after the tag
so it echo all of comments :)

How to use `GET` parameters in a HTML document?

I have a HTML document and I want to send a parameter.
Let's name the document Categoty, and all it do it sends a request to the server (via Ajax) to get something on this categoty.
Suppose I'm using PHP, I would simply send the parameter:
localhost/Categoty.php?cat=somecat,
and read it in the PHP document: $_GET['cat'].
My question is if there's something similar in HTML (or Javascript)?
I though about hashtag (.i.e. categoty.html#somecat) , but I'm using jQuery mobile in my Android Hybrid application so it makes some issues.
Thanks in advance.
use the jQuery URL Parser in this link and then try:
jQuery.url().param('cat');
you can also access all other info we usually need in terms of dealing with GET parameters, like:
jQuery.url().attr('protocol');
returns the URL protocol like: http or https
jQuery.url().attr('host')
returns the host like stackoverflow.com
you can also get the segments of your URL like this:
jQuery.url().segment(1);//for instance in this very page's url it returns "posts"
at the end:
jQuery.url().param('cat') in javascript does the same as $_GET['cat'] does in PHP
jQuery ajax can do it , use $.ajax();
$.ajax({
type: 'GET',
url: 'http://localhost/Categoty.php?cat=somecat',
success: function(responseTxt,statusTxt,xhr){
}
});

partially download a file with Javascript

we're actually working on a Remote Music Library organizer using javascript and I'd like to know if there's a way to download using js the last 128bytes of an MP3 file in order to get its ID3 Tags. thanks.
You can't do that with just JavaScript. You'll need something on the server (what exactly depends on your server-side technology) to read the relevant part of the file. Then in JavaScript you can just call that server-side part.
Update 1
The HTTP protocol has support for downloading files in parts (which is what the). But of course HTTP knows nothing of MP3 files, so you'll have to know what range of the file contains the ID3 tag in your JavaScript.
Update 2
It seems way more feasible than I initially expected to download just a chunk of a URL in pure JavaScript:
xhr = new XMLHttpRequest();
xhr.open("GET", "http://<your domain>/");
xhr.setRequestHeader("Range", "bytes=-256");
xhr.send();
This requests the last 256 bytes of the remote file.
Note that of course your request is subject to the usual same-origin limitations, so you can only use it to retrieve files from the server that contains your original HTML/JavaScript.
Withouth using a server-sided programming language: no.
You could use Ajax and PHP (or any other programming language) to get the ID3 tag.
With jQuery it looks something like this:
function getInfo(func) {
$.ajax({
url: "mp3info.php?file=" + url,
dataType: "json",
ready: function(result) {
func(result);
}
});
}
And you use it like this:
getInfo(function(mp3info) {
alert(mp3info.id3);
});
Then your PHP file looks something like this:
<?php
$info = array(); //The MP3 info array
echo json_encode($info, true);
?>

Categories

Resources