Using Emotion API for Video (Javascript or Ruby) - javascript

So I'm working on posting a video to the Emotion API for video and I haven't been able to get a response.
I've been able to get it to work on the Microsoft online console, but when I try to implement it in my Rails app using (1) JavaScript Ajax, or (2) Ruby server-side code, I consistently get various errors.
Here's my code. At first I tried to Ajax way, but I had a suspicion that the API doesn't have CORS enabled. So then I tried Ruby, to no success.
Ruby attempt:
def index
uri = URI('https://api.projectoxford.ai/emotion/v1.0/recognizeinvideo')
uri.query = URI.encode_www_form({
})
data = File.read("./public/mark_zuck.mov")
request = Net::HTTP::Post.new(uri.request_uri)
# Request headers
request['Ocp-Apim-Subscription-Key'] = 'e0ae8aad4c7f4e33b51d776730cff5a9'
# Request body
request.body = data
request.content_type = "video/mov"
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http|
http.request(request)
end
puts response.body
end
Here's my Ajax attempt:
function CallAPI(apiUrl, apiKey){
console.log("API called");
$(".loading").css("display", "inline-block");
$.ajax({
url: apiUrl,
beforeSend: function (xhrObj) {
xhrObj.setRequestHeader("Content-Type", "application/octet-stream");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key", apiKey);
},
type: "POST",
data: '{"url": "http://localhost:5000/mark_zuck.mov"}',
processData: false,
success: function(response){
console.log("API success");
ProcessResult(response);
$(".loading").css("display", "none");
console.log(response);
},
error: function(error){
console.log("API failed");
$("#response").text(error.getAllResponseHeaders());
$(".loading").css("display", "none");
console.log(error);
}
})
Yes, I've regenerated my key. This is just to illustrate my point.

So you have to set Content-Type to application/octet-stream if it's a binary file you're sending, like I was.
If you use a url you should set Content-Type to application/json and the url must be publicly available.

Related

"How to fix 'Ajax request getting a 419 unknown status" (solved)

I am using laravel homestead. I am making a game that requires credits on the account of which it is played on. I want to make sure that after every play the credits of the user gets updated through an ajax request, however with this ajax request, I get the same error which is PATCH http://gamesite.test/updateBalance/13 419 (unknown status) if I change the data it gets the error: The GET method is not supported for this route. Supported methods: PATCH.
I already tried to change the methods of the ajax request and it is working on other pages.
The ajax request that I made is the following:
$(oMain).on("save_score", function(evt,iMoney) {
if(getParamValue('ctl-arcade') === "true"){
parent.__ctlArcadeSaveScore({score:iMoney});
}
//...ADD YOUR CODE HERE EVENTUALLY
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: 'updateBalance/'+{{ auth()->user()->id }},
type: 'PATCH',
data: {iMoney:iMoney, _method: "PATCH"},
success: function(res) {
}
});
});
I expected that it would update the users credits, instead got the error: "PATCH http://gamesite.test/updateBalance/13 419 (unknown status)"
EDIT:
Route:
Route::patch('/updateBalance/{id}', 'GamesController#updateBalance');
GamesController:
public function updateBalance(User $id) {
$selecteduser = User::find($id)->first();
$this->validate(request(), [
'credit' => 'int'
]);
$selecteduser->credit = request('iMoney');
$selecteduser->save();
}
Found the answer, I needed to add
to the header in the blade.
use HTTP default GET method, this works fine.
$.get (url, {iMoney:iMoney, _method: "PATCH"} , function(){
//success
})

how do I send a GET request with Jquery?

Currently I am using Flask and Jquery and getting a 500 Internal Server Error response in my console. When I post with Ajax to the url on flask, shouldn't it be able to be received? I don't understand why I am getting this error.
Jquery
$('.movie').click(function(){
console.log(this);
$(this).toggleClass('green blue').promise().done(function(){
if ($(this).html() == "Add Movie"){
$(this).html("Added");
}
});
id = $(this).val();
//get information from API
$.ajax({
url: "/profile",
dataType: 'json',
async: true,
data: {id: id},
success: function(data) {
}
});
Python/Flask
#app.route("/profile", methods = ["GET"])
def profile(id):
print("mydata is: ", request.args['id'])
if request.args.get:
print("this API is reached")
id = request.args.get['id']
url_movie = 'https://api.themoviedb.org/3/movie/{}?api_key=78cb6b67a99ce26e6d6619c617d9c907&language=en-US'.format(id)
r = requests.get(url_movie)
code = r.json();
return jsonify(code)
500 is a server error. There is something wrong with the request execution at server side only.

Angular post array object

I am trying to post a object array, I expect the post to post JSON like so
{"campaign":"ben",
"slots":[
{
"base_image": "base64 code here"
}
]
}
When I post I get this in the console
angular.js:9866 POST /ccuploader/Campaign/updateSlots 413 (Payload Too Large)
(anonymous) # angular.js:9866
n # angular.js:9667
f # angular.js:9383
(anonymous) # angular.js:13248
$eval # angular.js:14466
$digest # angular.js:14282
$apply # angular.js:14571
(anonymous) # angular.js:21571
dispatch # jquery.min.js:3
r.handle # jquery.min.js:3
app.js:71 failed
Im not sure why my post is not working. Can someone point out my mistake ?
JavaScript code
$scope.SaveImage = function () {
$http({
url: "http://www.somesite.co.uk/ccuploader/Campaign/updateSlots",
method: "POST",
data: $.param({ 'campaign': "name", 'slots': $scope.slots }),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function (response) {
// success
console.log('success');
console.log("then : " + JSON.stringify(response));
}, function (response) { // optional
// failed
console.log('failed');
console.log(JSON.stringify(response));
});
};
Seems you are sending a base64 string on the POST request.
Most web servers have a max POST limit.
You should configure your server to allow large POST params.
Implementation is different from server to server.
If your server is using PHP refer this.
Increasing the maximum post size
Also it is better if you can upload images by chunking them. There are lot of libraries that does it. Otherwise your browser will hang and the request will eventually timeout. That's called the multipart upload.
You can upload GBs of images without no problem with multipart upload mechanism.
UPDATE
Also without using the $.param function just pass the parameters directly to the data object. Since the payload is heavy the $.param may throw this exception when it's trying to parse the request.
$scope.SaveImage = function () {
$http({
url: "http://www.somesite.co.uk/ccuploader/Campaign/updateSlots",
method: "POST",
data: {
campaign: "name",
slots: $scope.slots
}),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function (response) {
// success
console.log('success');
console.log("then : " + JSON.stringify(response));
}, function (response) { // optional
// failed
console.log('failed');
console.log(JSON.stringify(response));
});

Getting an AJAX GET request to work with Express.js

I am using node.js and Express.js on the back end, and am trying to make a server call from the client via AJAX.
So I have this POST request that works fine with AJAX:
node.js/Express.js:
app.post('/createNewThing', function(req, res) {
var userInput = req.body.userInput;
if (userInput) {
res.send('It worked!');
}
});
Client Side/AJAX request:
var userInputForm = $('#userInputForm.val()')
$.ajax({
url: "/createNewThing",
type: "POST",
data: "userInput=" + userInputForm,
dataType: "text",
success: function(response, status, http) {
if (response) {
console.log('AJAX worked!);
}
}
});
The userInputForm comes from an HTML form.
This POST request works fine. But I want to change this to a GET request. If I change app.post to app.get, and change type in the AJAX call to GET, I get this 500 error:
GET /createNewThing?userInput= 500
When you make a GET request, the data appears in the query string (of the URL in the request headers). It doesn't appear in the request body. There is no request body.
When you try to read from the request body, you are trying to access a property of an undefined object, which triggers an exception and cause an internal server error.
This answer explains how to read a query string:
var id = req.query.id; // $_GET["id"]
So
var userInput = req.query.userInput;
I think var userInputForm = $('#userInputForm.val()') will get error or get wrong data..This may be the reason for the error. Due to userInputForm may not be a string and concatenate with userInput=
Actually it is bad data.
And for the data in ajax, you should modify data from data: "userInput=" + userInputForm,
to:
data: {
userInput: userInputForm
},
dataType: "json"
And var userInputForm = $('#userInputForm.val()')
to var userInputForm = $('#userInputForm').val();
At last, you could modify as bellow, I believe it works:
var userInputForm = $('#userInputForm').val();
$.ajax({
url: "/createNewThing?userInput=" + userInputForm,
type: "GET",
success: function(response, status, http) {
if (response) {
console.log('AJAX worked!);
}
}
});

Django + Ajax | File Upload | Server doesn't recognise Ajax Request

I am trying to implement file upload using ajax with Django but facing some problem.
When the user tries to upload the files after selecting the file and submitting the form, then as per my understanding , an ajax request should be send to the server using POST method ,but in my case a POST request is being made to the server, but the server is not able to identify it as an ajax request and browser is redirected to http://<server>:<port>/upload/ and the contents on this page are as follows.
{"status": "error", "result": "Something went wrong.Try Again !!"}
Django Version: 1.6.2
Python Version: 2.7.5
Also, testing on Django Development Server.
views.py
def upload(request):
logging.info('Inside upload view')
response_data = {}
if request.is_ajax():
logging.info('Is_AJAX() returned True')
form = UploaderForm(request.POST, request.FILES)
if form.is_valid():
logging.info('Uploaded Data Validated')
upload = Upload( upload=request.FILES['upload'] )
upload.name = request.FILES['upload'].name
upload.save()
logging.info('Uploaded Data Saved in Database and link is %s' % upload.upload)
response_data['status'] = "success"
response_data['result'] = "Your file has been uploaded !!"
response_data['fileLink'] = "/%s" % upload.upload
return HttpResponse(json.dumps(response_data), content_type="application/json")
response_data['status'] = "error"
response_data['result'] = "Something went wrong.Try Again !!"
return HttpResponse(json.dumps(response_data), content_type='application/json')
Template
<form id="uploadForm" action="/upload/" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input id="fileInput" class="input-file" name="upload" type="file">
<input type="submit" value="Post Images/Files" />
</form>
Javascript 1:
$('#uploadForm').submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: '/upload/',
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
Javascript 2
var options = {
url: '/upload/',
type: "POST",
error: function(response) {
alert('Something went Wrong. Try Again');
},
success: function(response) {
if ( response.status == 'success' ) {
alert('success');
}
}
};
$('#uploadForm').ajaxSubmit(options);
Question:
1) Why is Django not able to recognize the ajax request and value of request.is_ajax() is always False.
2) Even if the server doesn't recognize ajax request why is my browser getting redirected to another page ?
There is another similar question here but with no result.
This works for me. You need a jquery.form.js
$("#uploadForm").submit(function(event) {
$(this).ajaxSubmit({
url:'{% url upload_file %}',
type: 'post',
success: function(data) {
console.log(data)
},
error: function(jqXHR, exception) {
console.log("An error occurred while uploading your file!");
}
});
return false;
});
Here's the similar question here with answers.
Make sure that javascript code block
$('#uploadForm').submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: '/upload/',
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
loaded after your uploadForm html form in DOM on page. In your case seems you trying to bind submit handler with form element which not yet loaded so when you click, it send simple POST request.
1) why is_ajax() not working?
Have you included the JQuery form plugin (jquery.form.js) ? ajaxSubmit() needs that plugin.
Take a look at http://jquery.malsup.com/form/
If it's already done, you might take a look at the HTTPRequest object
Django Documentation says HttpRequest.is_ajax()
Returns True if the request was made via an XMLHttpRequest. And if you are using some javascript libraries to make the ajax request, you dont have to bother about this matter. Still you can verify "HTTP_X_REQUESTED_WITH" header to see if Django received an XMLHttpRequest or not.
2) Why page redirects?
As I said above, JQuery form plugin is needed for handling the ajax request and its call back. Also, for ajaxSubmit() you need to override the $(#uploadForm).submit()
$('#uploadForm').submit( function (){
$(this).ajaxSubmit(options);
return false;
});
Hope this was helpful :)

Categories

Resources