I was working on making a facial recognition system. I used the API called Kairos.The response I got back is the data of the feature of a face or an error message from a nonface image. How can I change the response and display them on the screen, such as "success! It's a face" or "There's no face". I tried to if/else statement, but it seems that there's no response from it. How should I do it?
<script>
$("#testDetect").click(function () {
var file = $('#imageFile')[0].files[0];
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onloadend = function () {
var imageData = parseImageData(reader.result);
var data = {};
data.image = imageData;
$.ajax({
url : "http://localhost/Karios/simple-detect/form-post.php",
type : "POST",
data : data,
dataType : 'text'
}).done(function(response) {
console.log(response);
if (!response) { // Something unexpected happened. The message body is empty.
alert('Hmm, unexpected response from Kairos');
} else if (response['Errors'] && response['Errors'].size() > 0) { // If Errors is defined in the response, something went wrong.
if (response['Errors'][0]['ErrCode'] == 5002) { // This appears to be the error when no faces are found.
alert(response['Errors'][0]['Message']);
} else {
alert('Some other error occurred:\n' + response['Errors']['ErrorCode'] + ': ' + response['Errors']['Message']);
}
} else { // If there are no errors in the response, can we assume it detected a face? I guess so.
alert('Face(s) detected');
// The response has a ton of information about what it saw, including gender, age, ethnicity
// and more.
}
})
}
});
Based on the response that you receive, you can write what you want to be displayed:
if(response === true){
alert('success!');
}
else{
alert('fail!');
}
EDIT
To redirect to another page, use: window.location = http://mywebsite.com;
To make a button unclickable, you will need to set the disabled attribute: document.querySelector('button').setAttribute('disabled',true);
EDIT
If this is your response: {"Errors":[{"Message":"no faces found in the image","ErrCode":5002}]} then you will have to parse it first because it will most likely be a string. Then in your conditional statement, check to see if it exists.
var obj = '{"Errors":[{"Message":"no faces found in the image","ErrCode":5002}]}';
obj = JSON.parse(obj);
if(obj.Errors){
console.log("errors exist");
}
In addition to .done(), you can call .fail() which will run when the ajax was unsuccessful.
$("#testDetect").click(function() {
var data = {}
$.ajax({
url: "http://localhost/Karios/simple-detect/form-post.php",
type: "POST",
data: data,
dataType: 'text'
}).done(function(response) {
alert(response)
}).fail(function(error) {
alert("Not a face")
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="testDetect">Test</button>
Related
I'm newbie in asp.net mvc, I try to create a post data using ajax, when in the development is run well, but when I try to publish web in server I get the error when post data, the error like this POST https://example.com/login-testing 500 (Internal Server Error). I try to look for many examples but fail all.
this is my code, may be you can find any problem in my code:
JS script in index.cshtml
function login() {
var email = $('#input-email').val();
var password = $('#input-password').val();
if (email && password) {
$.ajax({
url: '#Url.Action("LoginTesting", "Auth")',
type: 'POST',
data: JSON.stringify({
email: email,
password: password
}),
dataType: 'json',
contentType: 'application/json',
success: function (data){
console.log(data);
if (data == 1) {
window.location.href = '#Url.Action("Index", "Home")';
} else {
$('#login-warning').show();
}
},
error: function (data) {
$('#login-warning').show();
}
});
} else if (!email) {
$('#text-danger-email').show();
} else if (!password) {
$('#text-danger-password').show();
}
}
controller
[Route("login-testing")]
public JsonResult LoginTesting(LoginViewModel smodel)
{
var email = smodel.email;
var password = smodel.password;
DBHandle sdb = new DBHandle();
var account = sdb.GetLoginVerify(email);
if (account.password != null)
{
if (BCrypt.Net.BCrypt.Verify(password, account.password ))
{
var detail = sdb.GetUserDetail(account.id);
if (detail != null)
{
Session["is_login"] = true;
Session["id"] = detail.id;
Session["fullname"] = detail.fullname;
Session["id_levels"] = detail.id_levels;
Session["levels"] = detail.levels;
return Json(1);
}
else
{
return Json(2);
}
}
else
{
return Json(3);
}
}
else
{
return Json(4);
}
}
Please anyone help me to solve this problem.
Thanks.
Internal Server Error probably means something is wrong with your program.cs file .The order in which they are placed is important,improper placements could actually give rise to these errors.
500 internal server also means , there is something wrong with your Code,
according to me Go to Chrome Dev Tool and Click on Network Tab, in that Click on XHR tab
there your API call must located with red Highlighted text (Since its 500 internal server error ), Click on it, right side window will be appear then
click on Preview Tab , you might see which line of Code causing the issue
You can also Debug the Code , and step over code line by line, and check what is wrong.
when i want enter a city here, nothing happens, no error in my console, i don't know why
this is my code :
ajax.js
$(document).ready(function(){
$('#submitLocation').click(function(){
//get value from input field
var city = $("#city").val();
$.post('PHP/controller.php', {variable: city});
//check not empty
if (city != ''){
$.ajax({
url: "PHP/router.php",
// url :"http://api.openweathermap.org/data/2.5/weather?q=" + city +"&lang=fr"+"&units=metric" + "&APPID=697edce53ba912538458a39d776ca24e",
type: "GET",
dataType: "jsonp",
success: function(data){
console.log(data);
console.log(data.weather[0].description);
console.log(data.main);
console.log(data.main.temp);
var information = show(data);
$("#show").html(information);
}
});
}else{
$('#error').html('Field cannot be empty');
}
});
})
function show(data){
return "<h3>Témpérature: "+ data.main.temp +"°C"+"</h3>" + "<h3>"+ data.weather[0].description +"</h3>";
}
this is my router.php, my js call the router
<?php
require('../PHP/controller.php');
if (isset($_GET['city'])) {
return getWeatherCity($_GET['city']);
}
else {
echo'Error';
}
?>
i know that i can do this only with js or only with php but i want use both of them.
Do you have any request happening in the "Requests" tab of your DevTool?
You should see a request towards PHP/router.php and the associated status code. Given that you might collect clues to debug what's going on.
I have a JSON request using post method using ajax within this code
$(document).ready(function() {
$(document).on('submit', '#registration_check', function() {
var data = $(this).serialize();
$.ajax({
type: 'POST',
url: 'apidomain.com',
data: data,
success: function(data) {
$("#registration_check").fadeOut(500).hide(function() {
$(".result_1").fadeIn(500).show(function() {
$(".result_1").html(data);
});
});
}
});
return false;
});
});
the response will return 3 fields like name, email, phone on this element:
<div id="result_1"></div>
it's working nice so far, but want I plan to do is I want to display the alert or popup message if the ajax response found some of return value null. For example:
If JSON response return:
name: jhon, email: jhon#doe.com, phone: 123456789
user will redirect to the other page (done so far)
But if JSON response return
name: jane, email: jane#doe.com, phone:
The popup or alert will appeared, within text phone number empty.
If your data is a JSON object then you can do:
success: function(data) {
for (var i in data) {
if (!data[i]) {
alert(/* MESSAGE HERE */)
return;
}
}
// Your regular code here
}
You can make an associative array of your values in php file and echo it in the json format like
echo json_encode($array);
Then you will receive this in your ajax response like this
var objs = JSON.parse(data);
Then you can parse the values by keys like name, email and phone as you defined in associative array in your php file
console.log(objs.name);
console.log(objs.email);
console.log(objs.phone);
This is how you can parse the values individually. You can also apply conditions by your own way
First thing that comes to my mind: Do you need the JSON response in the document element or is it, that you dont know how to work with jQuery Ajax?
Anyway, this solution should help you in both cases:
$(document).ready(function()
{
$(document).on('submit', '#registration_check', function()
{
var data = $(this).serialize();
$.ajax({
type : 'POST',
url : 'apidomain.com',
data : data,
dataType: 'json', // tell jQuery, that the response data will be a JSON - it will be parsed automatically
success : function(data)
{
// now you have a parsed JSON object in the 'data' var
var show_alert = false;
if (data.phone === null || !data.phone.length) {
show_alert = true;
}
if (data.email === null || !data.email.length) {
show_alert = true;
}
if (show_alert) {
alert('here is the alert :)');
}
$("#registration_check").fadeOut(500).hide(function()
{
$(".result_1").fadeIn(500).show(function()
{
$(".result_1").html(JSON.stringify(data));
});
});
}
});
return false;
});
});
Im quiet confused with this code. Im reading this code of ajax which inserts the data automatically. but what im confused is this line if(result=='12') then trigger ajax what does 12 means why it should be 12 then conditioned to before ajax. Apparently im still learning ajax thanks. P.S this is working well btw im just confused with the code
here is the full code of the create function javascript / ajax
$('#btnSave').click(function(){
var url = $('#myForm').attr('action');
var data = $('#myForm').serialize();
//validate form
var empoyeeName = $('input[name=txtEmployeeName]');
var address = $('textarea[name=txtAddress]');
var result = '';
if(empoyeeName.val()==''){
empoyeeName.parent().parent().addClass('has-error');
}else{
empoyeeName.parent().parent().removeClass('has-error');
result +='1'; //ALSO THIS NUMBER 1 WHY SHOULD IT BE 1?
}
if(address.val()==''){
address.parent().parent().addClass('has-error');
}else{
address.parent().parent().removeClass('has-error');
result +='2'; //ALSO THIS NUMBER 2 WHY SHOULD IT BE 2?
}
if(result=='12'){ //HERE IS WHAT IM CONFUSED
$.ajax({
type: 'ajax',
method: 'post',
url: url,
data: data,
async: false,
dataType: 'json',
success: function(response){
if(response.success){
$('#myModal').modal('hide');
$('#myForm')[0].reset();
if(response.type=='add'){
var type = 'added'
}else if(response.type=='update'){
var type ="updated"
}
$('.alert-success').html('Employee '+type+' successfully').fadeIn().delay(4000).fadeOut('slow');
showAllEmployee();
}else{
alert('Error');
}
},
error: function(){
alert('Could not add data');
}
});
}
});
As I have explained in my commentaries, and since you wanted an example. This is how I will proceed in order to avoid checking for result == '12':
$('#btnSave').click(function()
{
var url = $('#myForm').attr('action');
var data = $('#myForm').serialize();
// Validate form
var empoyeeName = $('input[name=txtEmployeeName]');
var address = $('textarea[name=txtAddress]');
var formValid = true;
if (empoyeeName.val() == '')
{
empoyeeName.parent().parent().addClass('has-error');
formValid = false;
}
else
{
empoyeeName.parent().parent().removeClass('has-error');
}
if (address.val() == '')
{
address.parent().parent().addClass('has-error');
formValid = false;
}
else
{
address.parent().parent().removeClass('has-error');
}
// If form is not valid, return here.
if (!formValid)
return;
// Otherwise, do the ajax call...
$.ajax({
type: 'ajax',
method: 'post',
url: url,
data: data,
async: false,
dataType: 'json',
success: function(response)
{
if (response.success)
{
$('#myModal').modal('hide');
$('#myForm')[0].reset();
var type = '';
if (response.type=='add')
type = 'added';
else if (response.type=='update')
type ="updated";
$('.alert-success').html('Employee ' + type + 'successfully')
.fadeIn().delay(4000).fadeOut('slow');
showAllEmployee();
}
else
{
alert('Error');
}
},
error: function()
{
alert('Could not add data');
}
});
});
It's just checking existence of values and appending string to it.
if(empoyeeName.val()=='')
This check empty name and add error if name is empty. else it concat 1 to result.
if(address.val()=='')
This check empty address and add error if address is empty. else it concat 2 to result.
So if both of them are non empty that means result will be 12 and than only you make ajax call else show error.
I am trying to add data to a cart(using) Ajax jQuery, now I have added a primary key constraint and I want when the constraint is violated in get the error message in jQuery:
function add()
{
$(document).ready(function()
{
$('#addtocart').submit(function() {
//$('#add-button').prop('disabled',true);
var user = $('#user').val();
var pid = $('#pid').val();
$.ajax({
type: "post",
url: "/devilmaycry/register?action=addtocart",
data: {pid:pid ,user:user},
success:
function()
{
alert("Item has been added to cart");
},
error:
function()
{
alert("Item already present in the cart");
}
});
return false;
});
});
}
The error function never runs, the functionality in the DB is running fine but I don't see the error message in Ajax.
Here is Java code:
public int addintocart(String user,int pid)
{
try
{
conn = obj.connect();
String sql="insert into cart(userid,product_id,quantity) values(?,?,?)";
ps1 = conn.prepareStatement(sql);
ps1.setString(1,user);
ps1.setInt(2,pid);
ps1.setInt(3,1);
ps1.executeUpdate();
}
catch(SQLException e)
{
e.printStackTrace();
}
catch(Exception k)
{
k.printStackTrace();
}
return x;
}
What is going wrong?
You have to send the error back as a servlet response from Java. Here is an example: How to return Java Exception info to jQuery.ajax REST call?
Also, you are missing some parameters in the ajax error function. It might be another problem. Check out http://api.jquery.com/jquery.ajax/ You should evaluate the error and present the appropriate message.
That error code wwill never work. the onerror event of AJAX only runs when connection cannot be established or URL does not exist. You have to return something from your the server indicating success or faliure.
I would do it this way.
PHP(convert this code to JAVA):
if(success){
die(1);
} else {
if(notyetincart){
die(0);
} else {
die(2);
}
}
Then Jquery coded:
function add()
{
$(document).ready(function()
{
$('#addtocart').submit(function() {
//$('#add-button').prop('disabled',true);
var user = $('#user').val();
var pid = $('#pid').val();
$.ajax({
type: "post",
url: "/devilmaycry/register?action=addtocart",
data: {pid:pid ,user:user},
success:
function(response)
{
if(reponse==="1")
alert("Item has been added to cart");
else if(reponse==="0")
alert("Item could not be added to cart");
else alert("Item already present in the cart");
},
error:
function()
{
alert("Item could not be added to cart due to poor network connection");
}
});
return false;
});
});
}
Hope this helps