I'm trying to simply create a HTML webpage that gives me emotions from images input by the user.
Using Microsoft's documentation I created a HTML file below:
<!DOCTYPE html>
<html>
<head>
<title>JSSample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(function() {
$.ajax({
url: "https://api.projectoxford.ai/emotion/v1.0/recognize",
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","my-key");
},
type: "POST",
// Request body
data: {"url": "https://oxfordportal.blob.core.windows.net/emotion/recognition1.jpg"},
})
.done(function(data) {
alert("success");
})
.fail(function() {
alert("fail");
});
});
</script>
</body>
</html>
My understanding is that this should work without the need of a server, however, I am always getting 'fail' message on loading the website.
Any help would work, thank you!
Use the API testing tool we (Microsoft) have on over here:
https://dev.projectoxford.ai/docs/services/5639d931ca73072154c1ce89/operations/563b31ea778daf121cc3a5fa/console
Ensure you can make a correct request and you are actually setting your api key and not sending my-key on over.
If your key is invalid you'll get an error in the javascript console: 'Access-Control-Allow-Origin' header is present on the requested resource.
If your key is valid but your data is not escaped, you'll get a 400 bad request error. Update your data field to wrap with ''. See my example here (fill in your key) http://jsfiddle.net/w3npr1ue
$(function() {
$.ajax({
url: "https://api.projectoxford.ai/emotion/v1.0/recognize",
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","SetYourKey");
},
type: "POST",
// Request body
data: '{"url": "http://1.bp.blogspot.com/-dWka6rPeHZI/UL7newH9TnI/AAAAAAAAAQI/OfU3TW0dDBE/s220/Asa%2Band%2BDada%2Bin%2Bst.%2Bpetersburg%2BSmall.jpg"}',
})
.done(function(data) {
alert("success");
})
.fail(function(error) {
console.log(error.getAllResponseHeaders());
alert("fail");
});
});
Related
So I am trying to post some some data from one PHP file to another PHP file using jquery/ajax. The following code shows a function which takes takes data from a specific div that is clicked on, and I attempt to make an ajax post request to the PHP file I want to send to.
$(function (){
$(".commit").on('click',function(){
const sha_id = $(this).data("sha");
const sha_obj = JSON.stringify({"sha": sha_id});
$.ajax({
url:'commitInfo.php',
type:'POST',
data: sha_obj,
dataType: 'application/json',
success:function(response){
console.log(response);
window.location.replace("commitInfo");
},
error: function (resp, xhr, ajaxOptions, thrownError) {
console.log(resp);
}
});
});
});
Then on inside the other php file 'commitInfo.php' I attempt to grab/print the data using the following code:
$sha_data = $_POST['sha'];
echo $sha_data;
print_r($_POST);
However, nothing works. I do not get a printout, and the $_POST array is empty. Could it be because I am changing the page view to the commitInfo.php page on click and it is going to the page before the data is being posted? (some weird aync issue?). Or something else? I have tried multiple variations of everything yet nothing truly works. I have tried using 'method' instead of 'type', I have tried sending dataType 'text' instead of 'json'. I really don't know what the issue is.
Also I am running my apache server on my local mac with 'sudo apachectl start' and running it in the browser as 'http://localhost/kanopy/kanopy.php' && 'http://localhost/kanopy/commitInfo.php'.
Also, when I send it as dataType 'text' the success function runs, but I recieve NO data. When I send it as dataType 'json' it errors. Have no idea why.
If anyone can help, it would be greaat!
You don't need to JSON.stringify, you need to pass data as a JSON object:
$(function() {
$(".commit").on('click', function() {
const sha_id = $(this).data("sha");
const sha_obj = {
"sha": sha_id
};
$.ajax({
url: 'commitInfo.php',
type: 'POST',
data: sha_obj,
dataType: 'json',
success: function(response) {
console.log(response);
},
error: function(resp, xhr, ajaxOptions, thrownError) {
console.log(resp);
}
});
});
});
And on commitInfo.php, you have to echo string on json format
=====================================
If you want to redirect to commitInfo.php you can just:
$(".commit").on('click',function(){
const sha_id = $(this).data("sha");
window.location.replace("commitInfo.php?sha=" + sha_id );
});
I am new to Microsoft Cognitive services and this problem seems to have an easy fix but it has spoiled my two days. I have just copied the Computer vision for javascript code and replaced my the subscription key with mine and opened the .html file in my browser it says error.
DO I have to add something in the code
Also, I have nowt provided any image in this code what's he doing without an image?
The script code is here
<!DOCTYPE html>
<html>
<head>
<title>JSSample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(function() {
var params = {
// Request parameters
"visualFeatures": "Categories",
"details": "{string}",
"language": "en",
};
$.ajax({
url: "https://westus.api.cognitive.microsoft.com/vision/v1.0/analyze?" + $.param(params),
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","{6e07223403d94848be20af6f126fsssd}");
},
type: "POST",
// Request body
data: "{body}",
})
.done(function(data) {
alert("success");
})
.fail(function() {
alert("error");
});
});
</script>
</body>
</html>
code and preview of error
While it's not very obvious, in any code snippet from the Cognitive Service API reference page such as this one that I suspect you were using, you must provide a value (or remove) wherever it shows {something}. Here's code with suitable values:
<!DOCTYPE html>
<html>
<head>
<title>JSSample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
var myKey = "6e07223403d94848be20af6f126fsssd";
var myBody = {url:"http://www.gannett-cdn.com/-mm-/2d2a8e29485ced74b7537554043aeae2e0bba202/c=0-104-5177-3029&r=x1683&c=3200x1680/local/-/media/2015/07/18/USATODAY/USATODAY/635728260394906410-AP-GOP-Trump-2016.jpg"}
$(function() {
var params = {
// Request parameters
"visualFeatures": "Categories",
"language": "en",
};
$.ajax({
url: "https://westus.api.cognitive.microsoft.com/vision/v1.0/analyze?" + $.param(params),
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key", myKey);
},
type: "POST",
// Request body
data: JSON.stringify(myBody),
})
.done(function(data) {
alert("success");
debugger;
})
.fail(function() {
alert("error");
});
});
</script>
</body>
</html>
I am sending a post request to the REST web service using the following code:
<script type="application/javascript">
$(document).ready(function() {
$("#logbutton").click(function(event){
$.post(
"http://localhost:8080/CredentialsOnDemand/loginexpert/dologin",
{
ephone: $("#mobile").val(),
epassword: $("#password").val()
},
function(data) {
data = $.parseJSON( data );
$(".ray").html("$" + data.tag);
console.log( "You clicked a paragraph!" );
}
);
});
});
The web service gives a JSON response in format below:
{"tag":"login","status":true}
The call from the jquery code is running i.e. the web service is running fine, but the function that I have created to parse JSON is not working.
NOTE:
I tried to run this code without providing any value in the text field. The console displayed the json response and also console.log line. But when I again entered the values into the fields, then it didn't. I am unable to understand this thing.
Anyone having any idea?
Thanks in advance.
You could try the more verbose and detailed form using $.ajax:
$(document).ready(function() {
$("#logbutton").click(function(event) {
var req = {
ephone: $("#mobile").val(),
epassword: $("#password").val()
};
$.ajax({
url: "http://localhost:8080/CredentialsOnDemand/loginexpert/dologin",
data: req,
dataType: 'json',
type: 'POST'
}).done(function(data) {
console.log(data);
$(".ray").html("$" + data.tag);
console.log("You clicked a paragraph!");
}).fail(function(err) {
console.error(err);
});
});
});
This will be easier for you to pinpoint where the error is coming from
I'm trying to get some information from my php code when clicking on a button, but it doesn't connect to php.
front page is displayed in index.php
index.php:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
<script type="text/javascript" src="jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="functions.js"></script>
<title>Account Panel</title>
</head>
<div "getInfos">
<h2>In this section you can get your inforrmation</h2>
<button id="getNameBtn">Get Your Name!</button>
<span id="getNameSpan"> something must come here</span>
</div>
</body>
</html>
javascript codes and ajax are in
functions.js:
$(document).ready(function(){
$("#getNameBtn").live('click', function() {
$.ajax({
type: 'POST',
url: 'handler.php',
data:JSON.stringify({taskid = 1}),
headers: {
'content-type': 'application/json'
},
success: function(response) {
document.getElementById('getNameSpan').innerHTML = response;
},
error: function() {
alert("Error Ajaxing");
}
});
});
and php in serverside is some simple thing like this:
handler.php:
<?php
echo('Ajax successful!');
?>
You have not close the document ready function:
$(document).ready(function(){
$("#getNameBtn").live('click', function() {
$.ajax({
type: 'POST',
url: 'handler.php',
data:JSON.stringify({taskid = 1}),
headers: {
'content-type': 'application/json'
},
success: function(response) {
document.getElementById('getNameSpan').innerHTML = response;
},
error: function() {
alert("Error Ajaxing");
}
});
});
});
data:JSON.stringify({taskid = 1}),
shoulde be
data:JSON.stringify({taskid: 1}),
First of all, you should better use a newer jquery version.
There is at least one error in your Code:
data:JSON.stringify({taskid = 1})
The json should read
{taskid : 1}
Use a colon, not an equal sign. Not sure that it is true for your jQuery version, but usually data can be attached as json object already, so the whole line should work so:
data: {taskid : 1},
And the data is then visible as POST data in the PHP page. Note that the live() function is deprecated since 1.7. You can use
$("#getNameBtn").click(function(){...});
instead. Moreover, I don't think you need the headers in your request.
First important change you need to do, use $.on instead of $.live, since the latter is deprecated. Another thing you should check, if the handler.php file is at the same level as your JS/HTML file. It could be that the file is not reachable from your code. Here is what you can try:
$(document).ready(function(){
$("#getNameBtn").on('click', function() {
$.ajax({
type: 'POST',
url: 'handler.php',
data: { call: 'myAjax', taskid : 1 },
headers: {
'content-type': 'application/json'
},
success: function(response) {
$('#getNameSpan').html(response);
},
error: function() {
alert("Error Ajaxing");
}
});
});
});
And in the PHP file, you can check for the call key:
<?php
if(isset($_POST) && $_POST['call'] == 'myAjax') {
echo $_POST['taskid'];
exit;
}
?>
That exit is really important.
In your PHP file that returns JSON you should also set the header to JSON.
header("Content-Type: application/json"); //Above all HTML and returns
And the true answer to your problem has already been answered.
As the title says, I'm trying to pass a couple js variables to a php file. Here is my code so far.
JS:
$.ajax({
method: "POST",
url: "sendDataToDB.php",
data: {
mainVideoData: mainVideoTitle
},
success: function(data) {
alert("data sent");
},
error: function(data) {
alert("Data sending failed");
}
});
sendDataToDB.PHP:
<?php
$temp = $_POST["mainVideoData"];
echo $temp;
?>
I saw this code on different websites, but for some reason it's not working for me. It says that 'mainVideoData' is undefined which basically means that it doesn't exist.
Does anyone know what I did wrong?
Thanks!
EDIT:
I've read some suggestions, and decided to make a whole new file with just the code someone gave me that worked for him. Here is my whole php file and whole js file.
php.php:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="jquery-2.1.3.js" type="text/javascript"></script>
<script src="getApiData.js" type="text/javascript"></script>
<meta charset="utf-8"/>
<link rel="stylesheet" href=""/>
</head>
<body>
</body>
</html>
<?php
if(isset($_POST['mainVideoData'])){
$temp = $_POST["mainVideoData"];
echo $temp;
}
?>
And here is my whole js file:
$(document).ready ( function(){
var mainVideoTitle = "Hello";
$.ajax({
method: "POST",
url: "php.php",
data: {
mainVideoData: mainVideoTitle
},
success: function(data) {
alert("data sent");
},
error: function(data) {
alert("Data sending failed");
}
});
});
It only gives me an alert saying 'data sent', but it doesn't echo 'hello'.
Does anyone know what's wrong?
EDIT 2:
So I've added some code in my php file that should put my $temp in a database. Sadly that doesn't work. When I replace $temp by a normal value like 'hello' it places it in my database. When I use $temp it gives me this error:
Error: INSERT INTO youtubevideos (category)
VALUES (Wiz Khalifa - See You Again ft. Charlie Puth [Official Video] Furious 7 Soundtrack)You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Khalifa - See You Again ft. Charlie Puth [Official Video] Furious 7 Soundtrack)' at line 2
As you can see, it does give me the right value, and it also places that right value in VALUES. But for some reason it still gives me this error. Any reason why?
jQuery library is definitely included
check the path of your php file is valid
check mainVideoTitle defined or not
After just try this.
script:
$(document).ready ( function(){
var mainVideoTitle = "Hello";
$.ajax({
method: "POST",
url: "sendDataToDB.PHP",
data: {
mainVideoData: mainVideoTitle
},
success: function(data) {
alert("data sent");
},
error: function(data) {
alert("Data sending failed");
}
});
});
sendDataToDB.PHP:
<?php
if(isset($_POST['mainVideoData'])){
$temp = $_POST["mainVideoData"];
echo $temp;
}
?>
I hope this is help to achieve your result!!!
Try this it will work.Data will be captured in success.
$.ajax({
method: "POST",
url: "sendDataToDB.php",
data: {
mainVideoData: mainVideoTitle
},
success: function(data) {
console.log(data);
alert("data sent");
},
error: function(data) {
alert("Data sending failed");
}
});