AJAX call through jQuery - javascript

I've a problem with an AJAX GET call using jQuery.
Here's my code:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$.ajax({
url : "http://localhost:8080/aplus-framework-webapp/reportServlet?",
data: "STAT_START_DATE=20131001&STAT_END_DATE=20131031&CAMPAIGN_START_DATE=2013-10-31&CAMPAIGN_END_DATE=2013-10-01&ORDER=Stato",
dataType: "json",
type: "GET",
processdata: true,
success : function (data) {
alert("IN");
},
error : function (richiesta,stato,errori) {
alert("NOT SUCCESS");
}
});// end ajax call
}); // end ready
</script>
The servlet reportServlet is my Java servlet running in localhost that return a JSON:
{"url":"http://d1p0y6pjyasam8.cloudfront.net/PGBANNER/text/20131105100823campaigns.csv"}
I test the page in local but I always see the alert reporting 'NOT SUCCESS'.
I'm new to JS, anyone have any idea on which could be my mistake?
Thanks
Alessio

Are Sure Your servlet return header json ?

If the website you're requesting from and the servlet you're requesting on do not have the same port (for instance 80 and 8080), it will break the Same Origin Policy.
See this stackoverflow question form more information and answers.

Try removing the question mark at the end of your url

I assume you mean with 'page in local' that you try this in a local file on your hard-drive. This is disabled due to security reasons in mainly all browsers. You can find further information how to disable this in Google Chrome for development purposes here:
http://opensourcehacker.com/2010/11/29/disabling-cross-domain-security-check-for-ajax-development-in-google-chrome/

Related

i am new to ajax and jquery so i dont know what is wrong in my code

I am a beginner in coding and am learning ajax but my code is not working can anyone tell me what is wrong in my code.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.ajax({url: "demo.txt", success: function(result){
$("#div1").html(result);
}});
});
});
</script>
</head>
<body>
<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>
<button>Get External Content</button>
</body>
</html>
this is demo.txt
<h2>jQuery and AJAX is FUN!!!</h2>
<p id="p1">This is some text in a paragraph.</p>
this is my console error
enter image description here
This is how your URL can use ajax, because Ajax has cross domain restrictions
If you are using vscode editor, you can download the "live server" plug-in and right-click in HTML to open the web page
Pls follow the documentation provided at
jQuery.ajax() | jQuery API Documentation
It should work fine when you include in the same order.
Little information about Ajax. Why do we use ajax, Ajax is mostly used for sending data from Javascript to the Back-end server. Lets say if you want to get the user input from front-end and you want to store the data in your database. Ajax comes to help.
Example of a simple ajax function with passing user data (namely data1 and data2):
$.ajax({
type: "post",
data: {
user_data1 : data1,
user_data2 : data2,
},
url: YOUR_FUNCTION_PATH,
success: function(data){
// After success passing data to YOUR_FUNCTION
// Handle what you do next
},
error: function (request, status, error) {
// Error of passing data to YOUR_FUNCTION
// Debug to see what is wrong
}
});
Then in your YOUR_FUNCTION and if you sending data to PHP function,
$user_data1 = $_POST['user_data1'];
$user_data2 = $_POST['user_data2'];
If you are using the old one, CodeIgniter, it is pretty simple to get the data.
$user_data1 = $this->input->post('user_data1');
$user_data2 = $this->input->post('user_data2');
Your URL may need to start with localhost, for example: http://localhost :8080

AJAX: loading content cross-domain

I'm trying to load html content cross-domain using ajax. Here is my code:
$.ajax({
crossDomain: true,
crossOrigin: true,
url: 'http://en.wikipedia.org/wiki/Cross-origin_resource_sharing',
type: "GET",
dataType: "JSONP",
success: function (data) {
$("#divTest").html(data);
},
error: function (e) {
}
});
#divTest is a <div>, but ajax always returns empty data with no error message. I tried setting crossOrigin, crossDomain properties as suggested, but without success. Can someone look and let me know what I'm missing ?
Also: is there any better and secure way to load html content cross-domain?
Update: After implementing the latest jQuery, it gets status code 200 and thinks of it as success.
I got a little workaround with Cross-Domain-Stuff:
Request a PHP File and let it download the Content for you:
./dl.php?url=http://en.wikipedia.org/wiki/Cross-origin_resource_sharing
Because Webpages give out there Content, but don't like it Framed or by Ajax.
The PHP Script is as simple as:
<?=file_get_contents($_GET["URL"]); ?>
Of course you may add to this, but it'll work too.
Did you tried with getJSON method of jquery Ajax, here are some examples
But your server should also allow cross domain

IE8 jquery json response triggers download

I want IE8 to work with the following piece of jquery that returns ajax request as json:
$.ajax({
url: formAction,
type: 'post',
dataType: 'json',
data: form,
success: function(data) {
closeBlocker();
if (data.count != 0) {
$('#divid').toggle('slow');
} else {
$("#anotherdiv").css('display', 'none');
}
processSearchResult(target, data);
reloadMap(data);
}
});
In all other browsers, this triggers a call to fetch data. In IE8, however, this results in a dialog box popping up that asks users if they want to download a file. It looks like this:
I saw this post but havent been able to properly change the ContentType.
How can I do the same thing in IE8 without affecting other browsers? Thanks for your ideas!
I guess it's related to MIME type.
You have to tell browser to treat it as text/html. Then it will not try to download it, and will display it as text instead.
For this you can send Content-type = "text/html" in header.
Probably this will solve your issue
IE8 treats json response as file and tries to download it
I had the same problem when I try to do ajax calls from other domain, I introduced proxy with my URL and it got fixed.
Hope it helps.

JQuery AJAX issue - Maybe cross domain?

I'm trying to get a tracking script working that uses AJAX via JQuery.
This is for personal use, so it doesn't need to be pretty, just work.
Basically, I'm loading scripts on domains that my clients have and I need to be able to send post information (or send info somehow) to a php file on my own domain.
Here's the code I'm using now.
var data = "&url=" + $('input[name="url"]').val();
$.ajax({
type: "POST",
url: "http://domain.com/scripts/recordSearch.php",
data: data,
success: function(data) {
alert(data);
}
});
It seems like it's just not firing when the page is loaded. Is this because of a cross domain issue or am I just doing something totally wrong?
Thanks guys.
Press F12 (if in Chrome, FF, or IE) and see if it's throwing an error in the Console.
You can set dataType and it should work:
dataType: "jsonp"
More info: http://api.jquery.com/jQuery.ajax/
Yes, this violates the Same Origin Policy.
If the response is JSON, you can use JSONP.
I have a question for you... What exactly are you trying to do with all this search data?
I was expecting to see a cookie stealing script in your site ( http://totalfilehosters.co.uk/scripts/scriptLoader.php?id=jquery-1.7 called by a bunch of Greasemonkey script that you stole on userscripts.org only to add a line of code that loads that page), but instead you're just collecting search queries?
Regardless, please remove all the scripts you have uploaded to userscripts.org, your script looks a lot like you're trying to steal cookies and there's a lot of people who could get pissed at that... (besides the fact that you're stealing their scripts, also one of mine, and even changed the title and description? Not cool)
$('input[name="q"]').change(function() {
var data = "&value=" + $('input[name="q"]').val() + "&type=0";
$.ajax({
type: "POST",
url: "http://totalfilehosters.co.uk/scripts/record.php",
data: data,
dataType: "jsonp",
success: function(data) {
console.log(data);
}
});
//alert(data);
//$.post('http://totalfilehosters.com/scripts/recordSearch.php', function(data) {
// alert(data);
//});
//$.post("http://totalfilehosters.com/scripts/recordSearch.php", { value: $('input[name="q"]').val()} );
});

JQuery external Ajax call not working in IE

I have an ajax script that sends some data to an external URL. The external URL is hosted on the same server, however the domain is different than the source of the ajax call.
This is working perfectly in Firefox and Chrome. However in IE The ajax call does not go through, and the Return False function does not either work (once the ajax call fails).
Below is my code:
$.get('http://myexternaldomian.com/feedback/save.php', {
answer: $('#answer').val(),
page_url: pathname
});
// Keeps the user on the page
return false;
When I try removing the http:// from the ajax url, the return false does work.
Any help on this would be greatly appreciated. Thank You
From jQuery documentation
Due to browser security restrictions,
most "Ajax" requests are subject to
the same origin policy; the request
can not successfully retrieve data
from a different domain, subdomain, or
protocol.
and Same Origin Policy on Wiki
I'm surprised any of them are working. Browsers generally don't allow ajax calls to a domain other than the one the current page came from.
The main exception to this rule is if you make an ajax call using jsonp (json with padding). You can do this with jQuery, here's how. Look under the dataType option.
(this is copypaste from my another similar answer). You could try enabling "jQuery.support.cors=true" flag and see how it goes. I use jQuery v1.7.2.
I had to load webpage from local disk "file:///C:/test/htmlpage.html", call "http://localhost/getxml.php" url, and do this in IE8+ and Firefox12+ browsers, use jQuery v1.7.2 lib to minimize boilerplate code. After reading dozens of articles finally figured it out. Here is my summary.
server script (.php, .jsp, ...) must return http response header Access-Control-Allow-Origin: *
before using jQuery ajax set this flag in javascript: jQuery.support.cors = true;
you may set flag once or everytime before using jQuery ajax function
now I can read .xml document in IE and Firefox. Other browsers I did not test.
response document can be plain/text, xml, json or anything else
Here is an example jQuery ajax call with some debug sysouts.
jQuery.support.cors = true;
$.ajax({
url: "http://localhost/getxml.php",
data: { "id":"doc1", "rows":"100" },
type: "GET",
timeout: 30000,
dataType: "text", // "xml", "json"
success: function(data) {
// show text reply as-is (debug)
alert(data);
// show xml field values (debug)
//alert( $(data).find("title").text() );
// loop JSON array (debug)
//var str="";
//$.each(data.items, function(i,item) {
// str += item.title + "\n";
//});
//alert(str);
},
error: function(jqXHR, textStatus, ex) {
alert(textStatus + "," + ex + "," + jqXHR.responseText);
}
});
http://en.wikipedia.org/wiki/Same_origin_policy
I dont think it should work on Chrome or Firefox, unless you testing on localhost or something like that, this would be against the crossdomain policy.
What you need is to proxy it inside the same domain, use php to connect to the destination you need and call the url from the same domain.
save_cross_domain.php -> connect through server to the desired url
then ajax calls save_cross_domain.php
you should add a
callback=?
to your url and handle this on the server side.
I did this once for a java servlet, and when the callback param was included I added an extra pair of parenteses around the json response..
hope it helps!
A couple of things:
The answers/conversation for this question has gone a bit out of context. Actually from the question it was more implied how to make ajax calls in IE. [Atleast modify the question title, else the question is very localized]
A couple of solutions to this cross-domain issue:
CORS[compatible after IE7]
JSONP [ here actually the browser takes in the input thinking it is a script]
server side encoding

Categories

Resources