I have this JSONP object displayed on a site that generates 3 random numbers. I am trying to access it using the following script embedded in a HTML document.
<script>
var url = 'http://dev.apalfrey.me/workspace/te2006-te2801/';
$.ajax({
type: 'GET', //uses GET function
url: url, //stored URL in var
data: {
'callback': 'randomNum'
},
jsonpCallback: 'randomNum',
contentType: 'application/jsonp',
dataType: 'jsonp'
}).done(function(response) {
console.log(randomNum.num1); //ERROR IS HERE randomNum.
});
</script>
The JSONP object looks like this:
Currently I am getting an error. "Can't find variable: randomNum" That tells me that I am not targetting the object correctly.
It is also important to note that the JSONP object does appear in my resources when I hit F12.
Any suggestions on how to target the remote JSONP object?
The issue is in your done() handler. You're attempting to use a variable named randomNum which doesn't exist. Instead you need to use the response variable as passed to the handler function.
Also note that response will be an array, so you need to access the required item by it's index, eg response[0].num1. Try this:
var url = 'http://dev.apalfrey.me/workspace/te2006-te2801/';
$.ajax({
type: 'GET',
url: url,
jsonpCallback: 'randomNum',
dataType: 'jsonp'
}).done(function(response) {
console.dir(response);
console.log(response[0].num1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Also note that if your intention is to simply generate a random number then AJAX is huge overkill. You can just use Math.random().
Related
I have this script as an informer to display a list of hotels. I want to change the limit with JS and get the result. If I try to use fetch() I got No 'Access-Control-Allow-Origin' and it returns some code. Is it possible somehow to get the results of this informer into a variable?
<script async src="//www.travelpayouts.com/blissey/scripts.js?iata=PAR&type=full¤cy=rub&host=search.hotellook.com&marker=77410.&limit=10" charset="UTF-8"></script>
If you want to get the list of hotels from TravelPayouts you have another endpoint for that which is: https://engine.hotellook.com/api/v2/lookup.json.
In your case you can try with this URL:
https://engine.hotellook.com/api/v2/lookup.json?query=moskow&lang=en&lookFor=both&limit=[your-limit-number]
You can make a .ajax request and it's should look like this:
$.ajax({
type: 'GET',
crossDomain: true,
dataType: 'jsonp',
url: 'https://engine.hotellook.com/api/v2/lookup.json?query=moskow&lang=en&lookFor=both&limit=10',
success: function(jsondata){
console.log(jsondata);
}
});
JSONP is a method for sending JSON data without worrying about cross-domain issues.
For more information you can found on:
https://support.travelpayouts.com/hc/en-us/articles/115000343268-Hotels-data-API#3
So i am not sure if i am doing this right.
I want to send markup over HTML (i am trying to create a widget)
Here is the mocky response that i am expecting
so I create a simple jquery get like this
var jsonp_url = "http://www.mocky.io/v2/5c9e901a3000004a00ee98a1?callback=myfunction";
$.ajax({
url: jsonp_url,
type: 'GET',
jsonp: "callback",
contentType: "application/json",
success: function (data) {
$('#example-widget-container').html(data.html)
},
error: function (data) {
alert('woops!'); //or whatever
}
});
then created myFunction
function myfunction(data) {
console.log(data);
}
The problem being that while, i get the response it comes as a string instead of a json or function. i am not sure how to extract the json from this (unless i do string manupulation).
Any pointers would be helpful.
JSFiddle here
P.S. Per https://www.mocky.io/ ,
Jsonp Support - Add
?callback=myfunction to your mocky URL to enable jsonp.
Delete function myfunction.
In the URL, replace callback=myfunction with callback=?.
jQuery will generate a function (your success function) and a function name for you.
A jQuery function receives a string from a database using GET, after that I would like to inject that string into HTML in place of a div. Pretty standard stuff so it seems.
However I am not quite managing it.
Here is what I have going on:
<h1>Whatever</h1>
<div id="replace_me">
</div>
<a id="click_me" href="#">Click Me</a>
<script>
//AJAX
var brand_id = 8
var dataX = {'brand': brand_id, 'csrfmiddlewaretoken': ""};
$(function(){
$("#click_me").click(function(){
$.ajax({
type: 'GET',
url: '/ajax_request/',
data: dataX,
datatype: "json",
success: function(data) {
alert(data);
$("#replace_me").load(data);
},
error: function() {
alert("Nope...");
}
});
});
});
</script>
When the alert is set off I receive my string which shows everything is working fine, but how can I input that string I just received into the div "replace_me" without having to load from another url?
You have an error in your success function. Check documentation on jQuery load(). Instead, you should do
success: function(data) {
//alert(data);
$("#replace_me").html(data);
},
or, slightly better style
success: function(data) {
//alert(data);
$("#replace_me").empty().append($(data));
},
Also note, that you specified "json" in your datatype option. As a consequence, if your server responds in proper JSON, your data will be a JavaScript object, as jQuery will parse the JSON format for you. If you really want to see the object, you will need to use, e.g. JSON.stringify():
$("#replace_me").empty().append($(JSON.stringify(data)));
If your server does not produce valid JSON, your success method will not be called in most cases.
load() is a convenience method to do the two steps of calling the ajax url, then putting the data into the element all in a single function. Instead of calling .ajax(), just call .load()
i.e.
var brand_id = 8
var data = {'brand': brand_id, 'csrfmiddlewaretoken': ""};
$("#replace_me").load('/ajax_request/', data);
So I am trying to do a post using jQuery.ajax instead of an html form. Here is my code:
$.ajax({
type: 'POST', // GET is available if we prefer
url: '/groups/dissolve/$org_ID',
data: data,
success: function(data){
$('#data_box').html(data);
}
});
Here is my problem:
When this was in an html form, the $org_ID that was part of the URL would actually pull the variable and send it as part of the URL. Now that this is in jquery, its just sending $org_ID as text. How can I get this to figure out what the variable, $org_ID is? I tried declaring it in the javascript but I am brand new to jquery/javascript and don't really know what i'm doing.
Thanks!
Are you rendering this in PHP? In that case you need to do:
url: '/groups/dissolve/<?php print $org_ID; ?>'
Otherwise, you need to do something like
var org_id = 'foo';
// or
var org_id = '<?php print $org_id ?>';
$.ajax({
type: 'POST', // GET is available if we prefer
url: '/groups/dissolve/'+org_ID,
data: data,
success: function(data){
$('#data_box').html(data);
}
});
Unlike PHP, you can't interpolate variables in javascript, you have to concatenate them with the string.
If you're trying to POST a variable (org_id) then you should put it in data:
data['org_id'] = org_id;
$.ajax({
type: 'POST', // GET is available if we prefer
url: '/groups/dissolve/',
data: data,
success: function(data){
$('#data_box').html(data);
}
});
While you can concatenate params onto your url to send them in an HTTP request, putting them in a data object not only lets jQuery do more work for you & escape HTML entities etc (and keep your code cleaner), but also allows you to easily debug and play around with ajax() settings.
It's not clear in the question where your data comes from, but you can use something like:
url: '/groups/dissolve/'+orgId,
or:
url: '/groups/dissolve/?orgId='+orgId,
Short answer, concatinate
url: '/groups/dissolve/' + $org_ID
I have a mobile application and I have a lot of data that I am putting in to a JSON object to store in localStorage. I need to get this data to PHP to process it. I have chosen to use jQuery.ajax to send the data as a JSON object to PHP. However, when I run the function, it gives a success message, but does not go to the url specified. I have a lot of PHP experience but this is my first JS intensive project.
Here is my JS code:
function sendToPHP() {
jQuery.ajax({
type: "POST",
url: "email.php",
data: { "json" : ATRdataJSON},
success: function(data){
console.log("Data Sent!");
},
});
};
ATRdataJSON is a JSON object that has several JSON objects nested inside.
The URL may not be pointing where you think it's pointing. Try:
function sendToPHP() {
jQuery.ajax({
type: "POST",
url: "/email.php",
data: { "json" : ATRdataJSON},
success: function(data){
console.log("Data Sent!");
},
});
};
i'm afraid you cannot send the json object without stringifying it, it may be sent but as a string [object] try to check it first then you may make sure of the url is absolute to make sure it goes to the right controller.