Getting JSONP from Google Books API using jQuery .ajax and jQueryMobile example - web-services

Reading the Google Books API they have the documentation on how to use the REST API, and also they mention about using the API with a client javascript.
I am making a phonegap/JQueryMobile application, and I want to fetch data using ajax, and Google Books API but their API is hard for me to understand.
What I want to fetch is JSONP object using the $.ajax method.
Do you have any example code, that fetches data using Google Books API and using jQuery $.ajax that would work in a phonegap application.
Do I have excplicity to provide the callback method, or do I go for for this, is just to confusing...
In this code:
<body>
<div id="content"></div>
<script>
function handleResponse(response) {
for (var i = 0; i < response.items.length; i++) {
var item = response.items[i];
// in production code, item.text should have the HTML entities escaped.
document.getElementById("content").innerHTML += "<br>" + item.volumeInfo.title;
}
}
</script>
<script src="https://www.googleapis.com/books/v1/volumes?q=harry+potter&callback=handleResponse"></script>
</body>
from Google Books API they say you can get JSONP data, but I just cant seem to grasp how to do this with jQUery $.ajax and using jsonp as type.

Just to get you started, you can do this:
// Set the api variable
var googleAPI = "https://www.googleapis.com/books/v1/volumes?q=harry+potter";
// Make a ajax call to get the json data as response.
$.getJSON(googleAPI, function (response) {
// In console, you can see the response objects
console.log("JSON Data: " + response.items);
// Loop through all the items one-by-one
for (var i = 0; i < response.items.length; i++) {
// set the item from the response object
var item = response.items[i];
// Set the book title in the div
document.getElementById("content").innerHTML += "<br>" + item.volumeInfo.title;
}
});
FIDDLE DEMO

Related

What is the best approach of using django and ajax?

I'm now working on my first big project and can't understand how to use Django with ajax.
On my website there are several services which works separately and are written on javascript, but soemtimes I have to send some information to the server.
Also I have custom admin interface which contains of different changing database operations. All these actions should be done without reloading the page (using ajax post and get requests).
So, I think I have two ways of doing it:
Using ajax and classic Django views for each operation.
Using ajax and integrated into my website Django REST Framework API methods.
The stumbling block is that I wouldn't use this API methods from any other types of clients, just call them from users' browsers via ajax. What is the best approach in my situation? It seems to me that the second way is more "serious", but I don't have much experience of making projects like this and can't speak directly.
You don't need to integrate REST. You can do ajax call to normal view like you do with user interaction. The view can return http response or JSON or whatever you need. If you would like to change somethink in DOM without refreshing page I can sugest HTMX (https://htmx.org/)
standard ajax call to get some json:
let datas = {id: $(this).val(),};
$.ajax({
url: "{% url 'to_your_view' %}",
type: "POST",
data: datas,
success: function (json) {
console.log(json);
},
error: function (xhr, errmsg, err) {
console.log(xhr.status + ": " + xhr.responseText);
}
});
and in view:
def to_your_view(request):
if request.method == "POST":
id = request.POST.get('id', 0)
if id != 0:
return HttpResponse(json.dumps(100), content_type="application/json")

Does Safari's "Storage Access API" only work with iframes?

I am trying to use the Storage Access API in plain old JavaScript inside of a modal. I am not using an iframe. All of the docs that I see online for the Storage Access API reference iframes. Does this mean the technology only works with iframes or can I use it in a regular javascript file?
I've tried attaching it to an onclick event in html and also creating it programatically with javascript, but neither of these seem to be working. I cannot get the "Do you want to allow 'video.example' to use cookies and website data while browsing 'news.example.com'" to show.
<button onlick="showSafariMessage()" type="button">Show Safari Message</div>
<script>
var showSafariMessage = function () {
document.hasStorageAccess().then(hasAccess => {
if (!hasAccess) {
return document.requestStorageAccess();
}
}).then((result) => {
// Now we have first-party storage access!
// Let's access some items from the first-party cookie jar
document.cookie = "foo=bar"; // set a cookie
localStorage.setItem("username", "John"); // access a localStorage entry
}).catch((error) => {
// error obtaining storage access.
});
}
</script>
I expect to see the Safari popup, but I am not. Please help!

Create unique body request in postman for API-test

I want to create test request on postman with unique email property in the request body.
{
...
"email": "{{email_string}}.com",
...
}
I've set email_string with static string in enviroment, but is there any way that I can set email_string dynamically before request occured?
You can use Postman's built in support for the Faker library direct in the request body:
{
...
"email": "{{$randomEmail}}",
...
}
or, in a pre-request script:
pm.environment.set('user-email', pm.variables.replaceIn('{{$randomEmail}}'));
As an alternative to the previous answer, you could use the sendRequest function to get the value from a 3rd party API that is designed to return randomised data.
This can be added to the Pre-Request Script tab:
pm.sendRequest("https://randomuser.me/api/", (err, res) => {
// Get the random value from the response and store it as a variable
var email = res.json().results[0].email
// Save the value as an environment variable to use in the body of the request
pm.environment.set("email_address", JSON.stringify(email))
})
You could potentially create lots of randomised data using this API but it is a 3rd party API so you won't have any control over this changing. If you only need this in the short term, i'm sure it will be fine.
Something also worth remembering is that Postman comes with Lodash built-in so that gives you the ability to use any of that modules functions, to reduce down some of the native JS code.
There is tab in postman application named "pre-request script" near to "Test" tab. You can use this tab to set your environment variables.
Here is the trick:
var text = "";
var possible = "abcdefghijklmnopqrstuvwxyz";
for (var i = 0; i < 5; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
postman.setEnvironmentVariable('email_string', text + '#' + text);
I think this script could help you to set a random value in your environment.

QWebEngine: handling get and post requests when a runJavaScript is performed

I am looking for possibility of handling get and post requests made by running a java-script code after a website is loaded. Here is the description: a url could be loaded via QWebEnginePage::load and the page contains some buttons with javescript events bind to them. buttons do some get and post requests from internet. Is there anyway that I could signal my classes when the get and post requests are performed by that javascript events. If it is impossible with QWebEngine What are the other options in Qt to do job. I am looking for some options that would not be absolute in the future since it is part of long-term project.
Thanks
You can use QWebChannel that should work in your case.
CPP file
QWebChannel* webChannel = new QWebChannel();
webChannel->registerObject("foo", this);
webview->page()->setWebChannel(webChannel);
in HTML file
<script type="text/javascript" src="qrc:/Map/qwebchannel.js"></script>
<script type="text/javascript">
new QWebChannel(qt.webChannelTransport, function(channel) {
// all published objects are available in channel.objects under
// the identifier set in their attached WebChannel.id property
var foo = channel.objects.foo;
// access a property
alert(foo.hello);
// connect to a signal
foo.someSignal.connect(function(message) {
alert("Got signal: " + message);
});
// invoke a method, and receive the return value asynchronously
foo.someMethod("bar", function(ret) {
alert("Got return value: " + ret);
});
});
</script>

post data - ngResource AngularJS

Hello !
I develop a RESTful webapp with AngularJS, I use the ngResource module to send http requests. The webservice is developped with FuelPHP.
I'm having a problem to creating a resource with the $save method of ngResource. My web service doesn't receive post data.
When I check the http request with Firebug, I can see the post data.
I don't understand why the post data are not received by the webservice. So if you have an idea, it would be cool to help me.
Sorry for my bad level in English.
Here is the code :
Service :
app.factory('Medication', ['$resource', 'global', function ($resource, global) {
return $resource(global.API+'/medication/medication', {}, {})
}])
Method in the controller :
$scope.addMedication = function() {
var newMed = new Medication();
newMed.name = 'nameValue';
newMed.increaseinr = 1;
newMed.details = 'detailsValue';
newMed.$save();
}
I believe this is an issue with how PHP is handling the POST. When using AngularJS $resource it will POST the object with JSON as the post's BODY. PHP does not see this as a regular parameter. I've had to do this in other PHP (never used Fuel)
$requestBody = file_get_contents('php://input');
$requestBody = json_decode($requestBody, true);
Then you should be able to inspect $requestBody as a normal json object.
You need to config the $save method with a request method of 'POST'
you can set the default option 'transformRequest' of $http to change the transfer formation of the post data.
var myApp = angular.module('myApp');
myApp.config(function ($httpProvider) {
$httpProvider.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
$httpProvider.defaults.transformRequest = function(data){
if (data === undefined) {
return data;
}
return $.param(data);
}
});
Thanks for your answers.
Indeed, data is post in the request's body.
With FuelPHP, I used Input::json('key') to get the values (and not Input:post('key'))