function check() {
var svar = document.getElementsByName("svar");
var len = svar.length;
var object = 5;
var jsonData = JSON.parse(JSON.stringify(object));
$.ajax({
type : 'POST',
url : 'http://localhost:9000/postasvar',
dataType : 'json',
contentType : 'application/json',
data : jsonData
});
}
I got the above code in my javascript with the purpose to send a json object to the java.
#BodyParser.Of(BodyParser.Json.class)
public static Result postaSvar(){
JsonNode json = request().body().asJson();
//String svar = json.findPath("svar").textValue();
if(json== null){
return badRequest("förväntade json");
}else{
return ok("hello " + json);
}
}
The java code above is the code that is suppose to handle the json from the javascript but the answer i get is always null.
I also have the following code in my main.scala.html:
#(title: String)(content: Html)
<!DOCTYPE html>
<html>
<head>
<title>#title</title>
<link rel="stylesheet" media="screen" href="#routes.Assets.at("stylesheets/main.css")">
<link rel="shortcut icon" type="image/png" href="#routes.Assets.at("images/favicon.png")">
<script src="#routes.Assets.at("javascripts/check.js")" type="text/javascript"> </script>
<script src="#routes.Assets.at("javascripts/hello.js")" type="text/javascript"> </script>
</head>
<body>
#content
</body>
</html>
And this is index.scala.html:
#(message: String)
#main("Welcome to Play") {
#message
<form action="http://localhost:9000/postasvar" method="post">
</br>
<input type="radio" name="svar" value="svar1"/>svar1
<input type="radio" name="svar" value="svar2"/>svar2
<input type="radio" name="svar" value="svar3"/>svar3
<input type="radio" name="svar" value="svar4"/>svar4</br>
<button name="knappen" onclick="check();">Klar</button>
</form>
}
Is it someone who know what the problem might be?
You will need to give a string to jQuery to send and not an object. In your case you get always null because jQuery is not sending anything in the body.
For example, if you do this
$.ajax({
// (...)
dataType : 'json',
contentType : 'application/json',
data : {name: "Salem"}
});
jQuery will send this in the request body
name=Salem
and not the object formatted as JSON (dataType specifies the type of response it is waiting, not the type of data it is sending). So send a string instead:
$.ajax({
// (...)
dataType : 'json',
contentType : 'application/json',
data : JSON.stringify({name: "Salem"})
});
which will send the correct body and work as expected
{"name": "Salem"}
Related
I'm trying to use Microsoft Azure Face API in Javascript to verify two faces. I follow their sample codes and found one javascript API. In the below sample code how can I pass the two images that I want to verify in the body section of this API? Can someone give me an example pls?
<!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
};
$.ajax({
url:
"https://westus.api.cognitive.microsoft.com/face/v1.0/verify?"
+ $.param(params),
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","
{subscription key}");
},
type: "POST",
// Request body
data: "{body}",
})
.done(function(data) {
alert("success");
})
.fail(function() {
alert("error");
});
});
</script>
</body>
</html>
Below sample works for me.
<!DOCTYPE html>
<html>
<head>
<title>JSSample</title>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
faceapi();
})
function faceapi(){
var SendInfo= { faceId: '43a4de00-e750-4bb8-8379-de3b33c9c0a6',personId:'2c0f2289-68cc-4cf6-ab12-9c0eec6bf3c7',largePersonGroupId:'112233'};
$.ajax({
type: 'POST',
url: 'https://yoursourcename.cognitiveservices.azure.com/face/v1.0/verify',
dataType: 'json',
data: JSON.stringify(SendInfo),
beforeSend: function(request) {
request.setRequestHeader("Content-Type", 'application/json');
request.setRequestHeader("Ocp-Apim-Subscription-Key", 'yourkey');
},
success: function(res){
console.log(res)
}
});
}
</script>
</head>
<body>
</body>
</html>
You can easily use our face verification api which is available for free in rapidapi
I am having difficulty getting a share on LinkedIn. I am trying to post a LinkedIn share update via its Share on LinkedIn API. Does anyone can tell me how to post on linked share update and give me steps to manage it.
First you have to sign into LinkedIn Developers and create an app to get the API code specific to your application: Login Here
Then, the quickest way for you to learn is to look at some examples. Here is a working version of what you are trying to code: http://datopstech.com/linkedin-share-tool/
The only thing you NEED to change to get this code running for yourself is the API_Key found in the HTML snippet.
The source for this can be found here or, I copied and pasted relevant pieces below for reference:
$(document).ready(function(){
$("#submit_button").click(function organizeinput(){
if (IN.User.isAuthorized() == true){
var values = new Array();
//comment, title, description, image-content, image-url
// Get the parameters as an array
values = $(":input").serializeArray();
// Find and replace `content` if there
var countinput=0;
for (index = 0; index < values.length; ++index)
{
if (values[index].name == "comment" && values[index].value != "")
{
var comment;
comment = values[index].value;
countinput=countinput+1;
}
if (values[index].name == "title" && values[index].value != "")
{
var title;
title = values[index].value;
countinput=countinput+1;
}
if (values[index].name == "description" && values[index].value != "")
{
var description;
description = values[index].value;
countinput=countinput+1;
}
if (values[index].name == "image-content" && values[index].value != "")
{
var imagecontent;
imagecontent = values[index].value;
countinput=countinput+1;
}
if (values[index].name == "image-url" && values[index].value != "")
{
var imageurl;
imageurl = values[index].value;
countinput=countinput+1;
}
}
if (countinput == 5){
var postcontent = new Array();
postcontent = {"comment": comment, "content": {"title": title,"description": description,"submitted-url": imagecontent,"submitted-image-url": imageurl},"visibility": {"code": "anyone"} };
postcontent = JSON.stringify(postcontent);
shareContent(postcontent);
}
else alert("All the fields are required.");
}
else alert("You have to login to linkedin before you can post content.");
});
function onLinkedInLoad() {
IN.Event.on(IN, "auth", organizeinput);
}
// Handle the successful return from the API call
function onSuccess(data) {
console.log(data);
alert("Post Successful!");
}
// Handle an error response from the API call
function onError(error) {
console.log(error);
alert("Oh no, something went wrong. Check the console for an error log.");
}
// Use the API call wrapper to share content on LinkedIn
function shareContent(pcontent) {
IN.API.Raw("/people/~/shares?format=json")
.method("POST")
.body(pcontent)
.result(onSuccess)
.error(onError);
}
//function executepost (pcontent)
//{
//$.post("https://api.linkedin.com/v1/people/~/shares?format=json", postcontent, function() {return null;});
// Setup an event listener to make an API call once auth is complete
//}
});
/*
$.ajax({
url: "https://api.linkedin.com/v1/people/~/shares?format=json",
type: 'post',
data: postcontent,
headers: {
'Content-Type': 'application/json',
'x-li-format': 'json'
},
dataType: 'json',
success: function (data) {
console.info(data);
}
});*/
// Convert to URL-encoded string
//values = jQuery.param(values);
/*
if (crflag ==1)
{
$.post("index.php", values, function(response) {processdata(response); return response;});
}
else
{
alert("Sorry, looks like we are missing some input");
}
//$.post("db_insert.php", $(":input").serializeArray(), function(tabledata){$("#result").html(tabledata);});
*/
Status API Training Shop Blog About Pricing
© 2016 GitHub, Inc. Terms Privacy Security Contact Help
<DOCTYPE html>
<html lang="en">
<head>
<title>Linkedin Share Link With Image, Choose Picture for Hyperlink Thumbnail, JSON Post Developer, Web Tool, Without Meta Property og: tag Online</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- add jQuery -->
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<!-- add bootstrap -->
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<!-- user typed js for form -->
<script src="postscript.js"></script>
<!-- initialize LinkedIn JS SDK -->
<script type="text/javascript" src="//platform.linkedin.com/in.js">
api_key: //YOUR API KEY HERE
authorize: true
//onLoad: onLinkedInLoad
</script>
</head>
<body>
<div class="wrap">
<h1 align="center">Create An Advanced LinkedIn Post</h1>
<p align="center">Configure a share post for Linkedin. First, authorize through LinkedIn by logging in.</br> Then, fill out all of the fields below and click submit to share the content.</br></br><script type="in/Login"></script></p> <br><br>
<div class="col-md-4"><!--quick spacer :)--></div>
<div class="col-md-5">
<form name="post_content" action="" method="post">
<label for="comment">Comment: </label>
<input type="text" class="form-control" name="comment" placeholder="Comment" required></input><br>
<label for="title">Title: </label>
<input type="text" class="form-control" name="title" placeholder="Title" required></input><br>
<label for="description">Description: </label>
<input type="text" class="form-control" name="description" placeholder="Description" required></input><br>
<label for="image-content">Link to Content: </label>
<input type="text" class="form-control" name="image-content" placeholder="http://example.com/content" required></input><br>
<label for="image-location">Image Location: </label>
<input type="text" class="form-control" name="image-url" placeholder="http://example.com/images/example.jpg" required></input><br><br>
<input type="button" id="submit_button" value="Submit" class="btn btn-default"></input>
</form>
</div>
</div>
</div>
<div id="VINoutput"></div>
</body>
</html>
Just use a URL like this...
https://www.linkedin.com/sharing/share-offsite/?url={url}
Source: Microsoft LinkedIn Share URL Documentation.
For example, this works for me:
https://www.linkedin.com/sharing/share-offsite/?url=http://www.wikipedia.org/
Demonstration:
refer.jvmhost.net/refer247/registration, this is my url,i have to fetch request to this url like user details and should get the appropriate response in json format with status n error if it contains ..dont give me android code..
this is html page.
<head>
<script type="text/javascript" src="json2.js"></script>
</head>
<body>
<div data-role="page" data-theme="c">
<div data-role="header" data-position="fixed" data-inset="true" class="paddingRitLft" data-theme="c">
<div data-role="content" data-inset="true"> <img src="images/logo_hdpi.png"/>
</div>
</div>
<div data-role="content" data-theme="c">
<form name="form" method="post" onsubmit="return validate()">
<div class="logInner">
<div class="logM">Already have an account?</div>
<div class="grouped insert refb">
<div class="ref first">
<div class="input inputWrapper">
<input type="text" data-corners="false" class="inputrefer" placeholder="Userid" name="userid" id="userid" />
</div>
<div class="input inputWrapper">
<input type="password" data-corners="false" class="inputrefer" placeholder="Password" name="password" id="password" />
</div> <input type="submit" data-inline="true" value="Submit" onclick="json2()">
<p>Forgot Password
</p>
</div>
</div>
<div class="logM">New user? Create refer Account</div>
<input type="button" class="btnsgreen" value="Sign Up! its FREE" class="inputrefer" data-corners="false" data-theme="c" />
</form>
</div>
</div>
<p style="text-align: center;">© refer247 2013</p>
</div>
</body>
this is json2.js
function json2()
{
var json1={"username":document.getElementById('userid').value,
"password":document.getElementById('password').value,
};
//var parsed = jsonString.evalJSON( true );
alert(json1["username"]);
alert(json1["password"]);
};
so tell me how to send the json data to that url n obtain some response like if email
id is already exist if u registering with that id ..then give some error
like email id already exist n if registerd succesfully then give respone like registerd successfully and status msg..200 okk...
You can use ajax to post json data to specified url/controller method. In the below sample I am posting an json object. You can also pass each parameter separately.
var objectData =
{
Username: document.getElementById('userid').value,
Password: document.getElementById('password').value
};
var objectDataString = JSON.stringify(objectData);
$.ajax({
type: "POST",
url: "your url with method that accpects the data",
dataType: "json",
data: {
o: objectDataString
},
success: function (data) {
alert('Success');
},
error: function () {
alert('Error');
}
});
And your method can have only one parameter of string type.
[HttpPost]
public JsonResult YourMethod(string o)
{
var saveObject = Newtonsoft.Json.JsonConvert.DeserializeObject<DestinationClass>(o);
}
$.ajax({
url: urlToProcess,
type: httpMethod,
dataType: 'json',
data:json1,
success: function (data, status) {
var fn = window[successCallback];
fn(data, callbackArgs);
},
error: function (xhr, desc, err) {
alert("error");
},
});
function addProductById(pId,pMqty){
$.getJSON("addtocart?pid=" + pId + "&minqty="+ pMqty +"&rand=" + Math.floor((Math.random()*100)+1), function(json) {
alert(json.msg);
});
}
Here is a simple example, which will call on button click or onclick event and call addtocart servlet and passes 2 argument with it i.e. pId and pMqty.
and after successful completion it return message in alert which is set in that servlet in json.
var json1={"username":document.getElementById('userid').value,
"password":document.getElementById('password').value,
};
$.ajax({
url: '/path/to/file.php',
type: 'POST',
dataType: 'text',//no need for setting this to JSON if you don't receive a json response.
data: {param1: json1},
})
.done(function(response) {
console.log("success");
alert(response);
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
on the server you can receive you json and decode it like so:
$myjson=json_decode($_POST['param1']);
I am trying to get the response from an Ajax call into a html label. I am using a tomcat server. Ia m able to see the description returned form the server however how do i get the responses into the lable text. Under is what i have tried:
Jquery
function GetDescription(Id){
$.ajax({
type:'GET',
url:'getDescription.htm',
data:{dId:Id},
dataType: 'json',
success: function (data) {
$('.TypeDesc').text = data.responseText;
}
});
}
$(document).ready(function() {
$(".photos").each(function(i){
if ($(this).val() != '') {
var image = new Image();
image.src = $(this).val();
image.onload = function(){
var typeId = document.getElementsByClassName("TypeId")[i].value;
GetDescription(typeId);
var ctx = document.getElementsByClassName("canvas")[i].getContext('2d');
ctx.drawImage(image,0,0, 320, 240);
}
}
});
});
html
</head>
<body>
<div id ="content">
<c:forEach items="${object}" var="i">
<div id="table">
<div>
<p><canvas class="canvas" height="240" width="320"></canvas>
</div>
Name:- ${i.fName} ${i.lName}
<input type="hidden" id="photo" value="${i.photo}" class="photos"/>
<input type="hidden" id="Number" value="${i.Number}" />
<input type="text" class="TypeId" value="${i.citizenTypeId}"/>
<label class="TypeDesc"></label>
</div>
</c:forEach>
</div>
</body>
</html>
The problem is that you're telling jQuery you're expecting JSON:
dataType: 'json',
...and so it's (trying to) parse the response as JSON and pass you an object, but then you're trying to use it like a raw XHR object.
If you want the text, remove the dataType or change it to dataType: 'text', and then use data which will be a string.
Your other problem is that text is a function, not a property, so you need to call it.
So:
dataType: 'text',
success: function (data) {
$('.TypeDesc').text(data);
}
Please add this to the parameters of the ajax call
success: function(data) {
$('.TypeDesc').each(function(){
$(this).text(data);
});
}
You need to give the lable a unique ID like id="TypeDesc{i}" or something different.
So you can refer to it something like this:
$('#TypeDesc{i}').text = data.responseText;
I'm getting a null JsonNode object in the following code. There's something wrong with the client javascript. If I run a curl command with a POST request, I get the correct response. If I run the same in the below mentioned Javascript - I get a null for the JsonNode object. Here's the code
Application.java
package controllers;
import org.codehaus.jackson.JsonNode;
import play.Routes;
import play.mvc.Controller;
import play.mvc.Result;
import views.html.index;
public class Application extends Controller {
public static Result index() {
return ok(index.render("Your new application is ready."));
}
public static Result receiveData() {
response().setContentType("application/json");
JsonNode json = request().body().asJson();
if(json == null) {
return badRequest("Expecting Json data");
} else {
String name = json.findPath("name").getTextValue();
if(name == null) {
return badRequest("Missing parameter [name]");
} else {
return ok("Hello " + name);
}
}
}
public static Result javascriptRoutes() {
response().setContentType("text/javascript");
return ok(
Routes.javascriptRouter("jsRoutes",
// Routes
controllers.routes.javascript.Application.receiveData()
)
);
}
}
Routes
# This file defines all application routes (Higher priority routes first)
# ~~~~
# Home page
GET / controllers.Application.index()
POST /receiveData controllers.Application.receiveData()
GET /assets/javascripts/routes controllers.Application.javascriptRoutes()
# Map static resources from the /public folder to the /assets URL path
GET /assets/*file controllers.Assets.at(path="/public", file)
main.scala.html
#(title: String)(content: Html)
#import helper._
#import controllers.routes.javascript._
<!DOCTYPE html>
<html>
<head>
<title>#title</title>
<link rel="stylesheet" media="screen" href="#routes.Assets.at("stylesheets/main.css")">
<link rel="stylesheet" media="screen" href="#routes.Assets.at("stylesheets/bootstrap.css")">
<link rel="shortcut icon" type="image/png" href="#routes.Assets.at("images/favicon.png")">
<script type="text/javascript" src="#routes.Application.javascriptRoutes"></script>
<script src="#routes.Assets.at("javascripts/jquery-1.9.0.min.js")" type="text/javascript"></script>
<script src="#routes.Assets.at("javascripts/bootstrap.js")" type="text/javascript"></script>
<script src="#routes.Assets.at("javascripts/message.js")" type="text/javascript"></script>
</head>
<body>
<div class="container">
<div class = "row">
<div class = "span12">
<input type = "text" id = "inputValue" value="getData"></input>
<button class = "approveButton btn btn-primary">Approve </button>
</div>
</div>
</div>
</body>
</html>
message.js
$(document).ready(function(){
$('.approveButton'). click(function(){
var value = $('#inputValue').val();
var jsonToSend = {};
jsonToSend.name = value;
var outputData = JSON.stringify(jsonToSend);
jsRoutes.controllers.Application.receiveData().ajax({
data:outputData,
contentType:'application/json',
success: function(data) {
console.log(data);
},
error: function() {
alert("Error!");
}
});
});
});
Here's the output of the curl command:
curl --header "Content-type:application/json" --request POST --data '{"name":"abx"}' http://localhost:9000/receiveData
Hello abx
Can someone please help in identifying whats wrong in the javascript file.
The expected result of the ajax call is a json object. In this case if you want to response with a plain text add dataType: 'text' to the request:
jsRoutes.controllers.Application.receiveData().ajax({
data:outputData,
dataType: 'text',
contentType:'application/json',
success: function(data) {
console.log(data);
},
error: function() {
alert("Error!");
}
});
Maybe a stupid question but what does you make think, that ajax call will be POST instead of GET ? Have you tried replacing POST by GET ?