I'm trying to use an API but their examples are in curl, not javascript, which is what I'm most familiar with. Here is their example:
$ curl http://visearch.visenze.com/uploadsearch \
-d im_url=http://example.com/example-0.jpg \
-d box=0,0,20,20 \
-u access_key:secret_key
This is my attempt at an equivalent jquery request, but it's not working.
$.get("http://visearch.visenze.com/uploadsearch/im_url=http://example.com/example-0.jpg/box=0,0,20,20/u access :secret_key", function(data){...});
If you use $.ajax()
instead (which $.get()
is shorthand for), you can use the username
and password
parameters (jQuery 1.7.2+) for the basic auth. You'll need to pass through a data object and specify POST if you need that request method.
$.ajax(
url: 'http://visearch.visenze.com/uploadsearch',
data: {
im_url: 'http://example.com/example-0.jpg',
box: '0,0,20,20',
},
username: 'access_key',
password: 'secret_key',
type: 'POST',
success: function(data) {
// ... your callback
}
);
Since you've tagged PHP in this question, I'll show an example of how you might want to hide your access keys etc in a backend wrapper as the Visenze API FAQs suggest you might do:
<?php
$accessKey = 'access_key';
$secretKey = 'secret_key';
if (isset($_POST['im_url'], $_POST['box'])) {
// Initialize the cURL request to ViSenze
$ch = curl_init('http://visearch.visenze.com/uploadsearch');
// We want to RETURN the result not output it
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set up the basic authentication settings
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "$accessKey:$secretKey");
// Define the post fields
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, [
'im_url' => $_POST['im_url'],
'box' => $_POST['box']
]);
// Do the request
$result = curl_exec();
curl_close($ch);
// Output the results
echo $result;
exit;
}
echo 'Nothing posted to this script.';
exit;
$.post(
'http://visearch.visenze.com/uploadsearch',
{
im_url: 'http://example.com/example-0.jpg',
box: '0,0,20,20',
},
function(data) {
// ... your callback
}
);
This way your API credentials are stored in your PHP code so not visible when you view the source of your page.
cURL requests with the -d
option send the request as POST
requests (unless you specify the G
modifier for GET
requests) so you will need to use that format. You will also need to set the header in a beforeSend
method:
$.ajax(
'http://visearch.visenze.com/uploadsearch',
type: 'post',
data: {
im_url: 'http://example.com/example-0.jpg',
box: '0,0,20,20'
},
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Basic ");
}
);