Jquery script not running ajax GET request - javascript

I've loaded jquery but as far as I can tell my script is not running, I don't believe its an issue with my ajax request, but rather with my loading of jquery?
I'm not getting any relevant error messages and console.log is not running.
<script src = "jquery.js">
$(document).ready(function(){
console.log('why wont my script run?')
$.ajax({
type: 'GET',
url: 'https://blockchain.info/ticker',
datatype: 'json',
success: function(data) {
window.alert('success',data)
},
error: function(error) {
window.alert('error')
}
});
});

You don't use the src attribute plus a script together within a <script> tag. It's one or the other.
If you use the src attribute then it needs to reference the .js file or the CDN.
The reason your variable isn't changing is because you need to make an AJAX call to your exchange rate API. You will then need to extract that value from the HTTP response and then update your DOM.

Related

Adding an external <script> with data parameters after ajax request

I need to add a < script > tag with external src and with data-*="" parameters inside a < form >. It is ok if you just add it in page. But if I do it after an ajax request, script reports it can't find data- parameters, and it is outside needed html elements.
I read that jQuery on .append() somehow rearranges < script > tags, and put them in the end (outside needed elements), and looses data- attributes.
Is there any other way to append a script after ajax request with needed data- parameters?
I tried
$('<script>').attr(/*all data params*/)
but it does not work.
Please help
You need to make sure you get the result from your Ajax request in the right place. As this is an asynchronous operation, it might be that you're data parameters are not populated at all.
The following code sends a request when you click the button and gets the result in the callback function :
function callback(data) {
// Got result from AJAX, play with DOM + jQuery here
console.log("callback called, data : ", data);
$("#callbackResultId").html(JSON.stringify(data));
}
$(document).ready(function(e) {
$("#textAjaxButtonId").click(function(){
$.ajax({
url: '/echo/json',
type: 'POST',
dataType: "json",
data: {
json: JSON.stringify({
'attr': 'value'
})
},
success: function(data, status, xhr){
callback(data);
}
});
})
});
http://jsfiddle.net/uemaft67/
The callback function is the place where you would get your Ajax response, and therefore build the DOM nodes along with the needed attributes.
Hope this helps!

External script not working (ASP.NET MVC) [duplicate]

I have a div element in my index.cshtml with id #myresults and i am trying to load data through jquery.load method by calling a mvc controller method. But i am not able to get the right syntax.
I am passing a custom object as a parameter as well.
var mycustomObject = {
obj1:value1,
obj2:value2,
..
}
The following does not work...(an i have tried other combinations as well..i get server not found error)
$("#myresults").load ('#Url.Action("MyActionMethod","Home")',mycustomObject);
while the following works
$("#myresults").load('/Home/MyActionMethod', mycustomObject);
While the last statement works, it works only on localhost.
Whats the right syntax to use for jquery load with Url.Action ?
#Url.Action() will always generate the correct url, so if your getting a 404, it means this code is in an external script file. Razor code is not executed in external scripts so your url would literally be the text "#Url.Action("MyActionMethod","Home")".
Options to solve this include
moving the code into the view or its layout
declaring a global variable in the view - var url =
'#Url.Action("MyActionMethod","Home")'; an in the external file use
$("#myresults").load(url, mycustomObject);
assign the url to an element as a data-* attribute, for example
<button type="button" id="loadSomething" data-url="#Url.Action("MyActionMethod","Home")">...</button>,and in
the external file
$('#loadSomething').click(function() {
var url = $(this).data('url');
$("#myresults").load(url, mycustomObject);
});
Define the div element as:
<div id="myresults" onload="loadMyData();"></div>
And make the ajax call in your method:
<script type="text/javascript">
function loadMyData() {
$.ajax({
cache: false,
url: '#Html.Raw(Url.Action(MyActionMethod","Home"))',
data: { obj1:value1, obj2:value2 },
dataType: "json",
type: 'post',
success: function (result) {
if (result.success) {
$('#myresults').html(result.data);
}
else {
alert("Failed to load data!");
}
}
});
}
</script>

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

Ajax's data parameter not making it to the server

Okay here's my problem.
I have an html page that has a javascript variable initialized in it.
<html>
<script>
MyVaribale = "Random Data";
</script>
<!-- Then I include an external js file to handle the processes in this html file -->
<script type="text/javascript" language="javascript" src="/scripts/some_random_script.js"></script>
</html>
Now, inside that script. I used the MyVaribalevarible in one of the ajax request there, like this :
$(document).ready(function() {
$.ajax(
url : '/some/random/url',
data : { MyVariable : MyVaribale }
etc ...
);
});
So, on page load, that ajax code is executed immediately.
In the url specified above, i checked for the existence of MyVaribale, then flag an error that it is a required value if it doesn't exist.
Backend code like this (in Perl):
my $MyVariable = trim_param('MyVariable'); # trim_param() is a function that gets the passed data from ajax.
if ( $MyVariable ) { # Test if it exists
# Display something
}
else {
# Flag an error, which is my problem
}
Now I am sure that in the html page, that variable is always populated (yes 100% sure). But I always get flag errors that that value doesn't exist in my backend code (url above).
So question,
Does ajax have some issue with document.ready, maybe it executes before the variable has finished assigning a value? Any idea why this happens? Because sometimes my ajax request is successful, sometimes it's not
Thanks
The syntax of your ajax call is not correct. Have a look here and then try this code (note the addition of {, } and ,):
MyVaribale = "Random Data";
$(document).ready(function() {
$.ajax({
url: '/some/random/url',
data : { myVariable : MyVaribale }
});
});
Did not you try out some complete ajax calls? Like this.Sometimes no need to use JSON.stringify for MyVariable.
$.ajax({
url: "/some/random/url",
type: 'POST',
dataType: 'json',
data: JSON.stringify(MyVaribale),
contentType: 'application/json',
mimeType: 'application/json'
}).done(function(data) {
}).fail(function(error) {
}).always(function(){
});

Cross Domain AJAX request return HTML (not jsonp)

I'm using this plugin: https://github.com/padolsey/jquery.fn/tree/master/cross-domain-ajax/
And this is my code:
$.ajax({
dataType: 'html',
type: 'GET',
url: 'http://www.google.com',
crossDomain: true
}).done(function(data) {
$("#box").html('').append(data);
});
From my understanding, even though I have dataType: 'html' I'm fairly sure this is still getting me a response in JSONP.
I want to be able to grab the entire html of the page, everything I need to display the page in full. Comparable to an iframe. The reason I need to do this through ajax is because eventually I am going to need to pass parameters to the URL I am using. What is the best way to return a page's content in full HTML, so that I may display the page? Do I need to do anything to return the pages scripts/stylesheets as well?
Basically, the URL that I am calling needs to be returned so that I can append the return to a div id, and that div id should then look exactly like the page I was calling, as if I were to load that page independently in a browser window.
Thanks!
You can try Ajax-cross-origin a jQuery plugin.
http://www.ajax-cross-origin.com/
$.ajax({
crossOrigin: true,
url: url,
success: function(data) {
console.log(data);
}
});
Plugin referenced uses Yahoo YQL service as a proxy to get remote page. YQL will return json and you should be able to access your data in data.responseText. This is per limted docs for plugin
To be sure you can log the data to console and see it's structure.
Could do same thing without plugin by using YQL console to create URL needed to meet your scraping needs using their XPATH syntax

Categories

Resources