Post restful method java error - javascript

Can anyone tell me why this error?
Server Log:
StandardWrapperValve[ws_site.ApplicationConfig]: Servlet.service() for servlet ws_site.ApplicationConfig threw exception
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 5
at com.google.gson.stream.JsonReader.expect(JsonReader.java:339)
at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:322)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:165)
at com.google.gson.Gson.fromJson(Gson.java:791)
Javascript function, responsible for capturing the data of the filled form and sending to the server:
function save()
{
var str_name = $("#name").val();
var str_email = $("#email").val();
var str_country = $("#country").val();
var str_state = $("#state").val();
var str_city = $("#city").val();
var str_zipcode = $("#zipcode").val();
var str_neighborhood = $("#neighborhood").val();
var str_street = $("#street").val();
var str_number = $("#number").val();
var objdata = '{"email_user":"' + str_email + '","name_user":"' + str_name}';
var objlocation = '{"country":"' + str_country + '","state":"' + str_state + '","city":"' + str_city + '","neighborhood":"' + str_neighborhood + '","street":"' + str_street + '","number":"' + str_number + '","zipcode":"' + str_zipcode + '"}';
var obj = '{"user":['+objdata+'],"endereco":['+objlocation+']}';
$.ajax({
headers: {'content-type': 'application/json'},
dataType: 'json',
method: "POST",
url: "http://localhost:8080/SystemExample/webservice/Save/data",
data: obj
}).done(function (data)
{
alert(data);
});
}
Restful Java method:
#POST
#Path("data")
#Produces(MediaType.TEXT_PLAIN)
#Consumes({MediaType.APPLICATION_JSON})
public String registerUser(Gson json)
{
User u = json.fromJson("user", User.class);
Address a = json.fromJson("endereco", Address.class);
u.setAddress(a);
userDAO.save(u);
return "Saved successfully!";
}
Save userDAO method:
public void save(User u) {
EntityManager em = JPAUtil.getEntityManager();
EntityTransaction tx = em.getTransaction();
try {
tx.begin();
if (u.getId_User() == null) {
em.persist(u);
} else {
em.merge(u);
}
tx.commit();
} catch (Exception ex) {
ex.printStackTrace();
if (tx != null && tx.isActive()) {
tx.rollback();
}
} finally {
em.close();
}
}
Using Gson to convert json into an object

You're not sending an object to the server, you're just sending a string:
var obj = '...';
Instead, send an object:
var objdata = {
"email_user": str_email,
"name_user": str_name
};
var objlocation = {
"country": str_country,
"state": str_state,
"city": str_city,
"neighborhood": str_neighborhood,
"street": str_street,
"number": str_number,
"zipcode": str_zipcode
};
var obj = {
"user": [objdata],
"endereco": [objlocation]
};
A string that looks like an object is still a string.

objdata was not populating correctly as valid json. Try with this:
function save() {
var str_name = $("#name").val();
var str_email = $("#email").val();
var str_country = $("#country").val();
var str_state = $("#state").val();
var str_city = $("#city").val();
var str_zipcode = $("#zipcode").val();
var str_neighborhood = $("#neighborhood").val();
var str_street = $("#street").val();
var str_number = $("#number").val();
var objdata = '{"email_user":"' + str_email + '","name_user":"' + str_name + '"}';
console.log(objdata);
var objlocation = '{"country":"' + str_country + '","state":"' + str_state + '","city":"' + str_city + '","neighborhood":"' + str_neighborhood + '","street":"' + str_street + '","number":"' + str_number + '","zipcode":"' + str_zipcode + '"}';
console.log(objlocation);
var obj = '{"user":[' + objdata + '],"endereco":[' + objlocation + ']}';
console.log(obj);
$.ajax({
headers: {'content-type': 'application/json'},
dataType: 'json',
method: "POST",
url: "http://localhost:8080/SystemExample/webservice/Save/data",
data: JSON.parse(obj)
}).done(function (data) {
alert(data);
});
}

In your server side you are trying bind JSON data.
User u = json.fromJson("user", User.class);
Address a = json.fromJson("endereco", Address.class);
It mean user and endereco should be a JSON objects like below.
{
"user":{
"email_user":"str_mail","name_user":"nameeee"
},
"endereco":{
"country":"str_country","state":"str_state","city":"str_city","neighborhood":"str_neighborhood","street":"str_street","number":"str_number","zipcode":"str_zipcode"
}
}
But in your case user and endereco are actually a JSONArray's(See the square brackets.).
{
"user":[
{
"email_user":"str_mail",
"name_user":"nameeee"
}
],
"endereco":[
{
"country":"str_country",
"state":"str_state",
"city":"str_city",
"neighborhood":"str_neighborhood",
"street":"str_street",
"number":"str_number",
"zipcode":"str_zipcode"
}
]
}
So change below line
var obj = '{"user":['+objdata+'],"endereco":['+objlocation+']}';
to
var obj = '{"user":'+objdata+',"endereco":'+objlocation+'}';

Related

Javascript query on SharePoint list items returning same results

I'm trying to show the Title field of a SharePoint list using a JavaScript Query but it just keeps returning the same result regardless of the link I click on. So as below, if I click on 'Lenovo T470' that's what its hould show above the image but it keeps showing 'Lenovo X1 Carbon'.
If I change the code:
var DeviceName = result.Title;
to:
var DeviceName = item.Title;
it comes back undefined. Any ideas? Full code below:
function getDevices() {
var txtTitle = "";
var txtTitleName = "";
//var txtDeviceType = "";
var query = "http://example.com/sites/it/ITInfrastructure/_vti_bin/listdata.svc/Devices?select=ID,Title";
var call = $.ajax({
url: query,
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
});
call.done(function (data,textStatus, jqXHR){
$.each(data.d.results, function (i, result) {
var tempID = result.Id;
var tempTitle = result.Title;
var DeviceName = result.Title;
txtTitle = txtTitle + "<p><a href='/sites/it/ITInfrastructure/SitePages/Service%20Catalogue%20Devices.aspx?did=" + tempID + "'>" + tempTitle + "</a></p>";
txtTitleName ="<p>" + DeviceName + "</p>";
});
$('#devices').append($(txtTitle));
$('#devicetitle').append(txtTitleName);
});
call.fail(function (jqXHR,textStatus,errorThrown){
alert("Error retrieving data: " + jqXHR.responseText);
});
}

Trying to store ajax response to input hidden?

I am trying to set value of input hidden, but it returns me null or 0.
function addbettrack(odd){
if($(".leagues_arr").val()!='0' && $('.games_arr').val()!='0' && $('.bet_type').val()!='0' && $('.book').val()!='0'
&& $('.bet_venue').val()!='0'){
if(odd=='undefined') odd=0.00;
var datetime = $(".games_arr").children(":selected").data('value').DateTime;
var league = $(".leagues_arr").val();
var hometeam = $(".games_arr").children(":selected").data('value').HomeTeam;
var awayteam = $(".games_arr").children(":selected").data('value').AwayTeam;
var eventname = $(".games_arr").children(":selected").data('value').EventName;
var bettype = $(".bet_type").val();
var book = $('.book').children(":selected").data('book');
var bookid = $('.book').val();
var bet = $(".bet_venue").val();
//var odd = $(".odds").val();
var stake = 1;
var marked = '';
if (bet == "Visitor") {
marked = 'A';
} else if (bet == "Host") {
marked = 'H';
} else {
marked = '';
}
var source = 'bettrack';
var id = $('.hidden_id').val();
var mode = "insert";
if(id > 0){
mode = "edit";
}
console.log(id + " " + mode);
console.log(datetime + " " + league + " " + hometeam + " " + awayteam + " " + eventname + " " + bettype + " " + bet + " " + odd + " " + stake);
$.ajax({
type: "POST",
url: '/index.php?/bettrack/insert_bettip/'+id,
data: {
DateTime: datetime,
LeagueName: league,
HomeTeam: hometeam,
AwayTeam: awayteam,
EventName: eventname,
BetType: bettype,
Bet: bet,
Book: book,
BookID: bookid,
Odd: odd,
Stake: stake,
Marked: marked,
Source: source,
Id : id,
Mode : mode
},
dataType:"json",
success: function(data) {
console.log(data);
$('.hidden_id').attr('value',data.odd);
$('.hidden_id').val(data.odd);
alert($('.hidden_id').val()); //here returns nothing
},
error: function(xhr, textStatus, error) {
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
}
}
this function runs inside other function and ajax request:
function get_bettrack(eventname, bettype, betvenue, book, mode = "a", id = 0) {
console.log(eventname+" "+bettype+" "+betvenue + " " + book);
$.ajax({
type: "POST",
url: '/index.php?/bettrack/get_odds',
data: {
EventName: eventname,
BetType: bettype,
BetVenue: betvenue,
Book: book
},
dataType: 'json',
success: function(data) {
if (mode == "a") {
console.log(data.odd);
$(".odds").val(data.odd);
var stake = 1;
var towin = parseFloat(data.odd) * parseFloat(stake);
$(".towin").html(towin);
addbettrack(data.odd); //HEREEE <=====================
} else {
$(".myodd" + id).val(data.odd);
var stake = 1;
var towin = parseFloat(data.odd) * parseFloat(stake);
$(".towin" + id).html(towin);
}
},
error: function(xhr, textStatus, error) {
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
}
and also get_bettrack function runs inside an event inside ajax success:
$('.games_arr').change(function() {
var date = $(this).children(":selected").data('value').DateT;
var label = date;
$(".game_date").html(label);
if ($('.leagues_arr').val() != '0') {
$(".bet_type").val("ToWin");
$(".bet_venue").val("Host");
var eventname = $(".games_arr").children(":selected").data('value').EventName;
var betvenue = $(".bet_venue").val();
var bettype = $(".bet_type").val();
var book = $(".book").children(':selected').data('book');
load_book(eventname, bettype);
get_bettrack(eventname, bettype, betvenue, book);
}
});
<input type="hidden" class="hidden_id" value="0" />

Ajax send image to server

I am working phonegap application. I want to send data image to server but i can not sent it.
function addSiteToServer() {
var cId = localStorage.getItem("cId");
var sname = $('#sitename').val();
var slat = $('#lat').val();
var slng = $('#lng').val();
var storedFieldId = JSON.parse(localStorage["field_id_arr"]);
var p = {};
for (var i = 0; i < storedFieldId.length; i++) {
var each_field = storedFieldId[i];
var val_each_field = $('#' + each_field).val();
p[each_field] = val_each_field;
console.log("p" + p);
}
var online = navigator.onLine;
if (online) {
var data = {
site: {
collection_id: cId,
name: sname,
lat: slat,
lng: slng,
properties: p
}
};
//function sending to server
$.ajax({
url: App.URL_SITE + cId + "/sites?auth_token=" + storeToken(),
type: "POST",
data: data,
enctype: 'multipart/form-data',
crossDomain: true,
datatype: 'json',
cache: false,
contentType: false,
processData: false,
success: function(data) {
console.log("data: " + data);
alert("successfully.");
},
}
Looks like you are using the normal method to send data/image to server which is not recommended by Phonegap/Cordova Framework.
I request you to replace your code with the following method which works as you expected,I also used local storage functionality to send values to server,
function sendDataToServer(imageURI) {
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
var params = {};
params.some_text = localStorage.getItem("some_text");
params.some_id = localStorage.getItem("some_id");
params.someother_id = localStorage.getItem("someother_id");
options.params = params;
var ft = new FileTransfer();
ft.upload(imageURI, encodeURI("http://example.co.uk/phonegap/receiveData.php"), win, fail, options);
}
function win(r) {
console.log("Code = " + r.responseCode+"Response = " + r.response+"Sent = " + r.bytesSent);
}
function fail(error) {
alert("An error has occurred: Code = " + error.code);
}
function saveData(){
sendDataToServer(globalvariable.imageURI);
alert("Data Saved Successfully");
}
Hope this helps.

Can't scrobble tracks (batch) to Last.fm API. Invalid method signature

I've been trying this for a while now, but I can't get my head around what's wrong. Maybe I've tried so many ways that I'm not even sure this piece of code is right anymore.
Basically I'm trying to use the track.scrobble method from the Last.fm API, sending a batch of tracks.
That's the code I have, and it's always returning Invalid method signature. Does anyone can give me some help here, please?
UPDATE
Based on mccannf answer, I've changed the code, but am still getting the error:
var apiUrl = "http://ws.audioscrobbler.com/2.0/";
var apiMethod = "track.scrobble";
var apiKey = "MY_API_KEY";
var apiSecret = "MY_API_SECRET";
var key = "MY_SESSION_KEY";
var apiSig = "";
var lastfmScrobble = function (data) {
var dataToScrobble = setTiming(data);
var albums = [];
var artists = [];;
var timestamps = [];
var tracks = [];
var dataToHash = "";
for (var i = 0; i < dataToScrobble.tracks.length; i++) {
albums["album["+ i.toString() + "]"] = dataToScrobble.album;
artists["artist[" + i.toString() + "]"] = dataToScrobble.artist;
timestamps["timestamp[" + i.toString() + "]"] = dataToScrobble.tracks[i].split("|")[1];
tracks["track[" + i.toString() + "]"] = dataToScrobble.tracks[i].split("|")[0];
}
dataToHash += albums.sort().join("");
dataToHash += "api_key" + apiKey;
dataToHash += artists.sort().join("");
dataToHash += "method" + apiMethod;
dataToHash += "sk" + key;
dataToHash += timestamps.sort().join("");
dataToHash += tracks.sort().join("");
dataToHash += apiSecret;
apiSig = $.md5(unescape(encodeURIComponent(dataToHash)));
var songsToScrobble = {};
$.extend(songsToScrobble,
albums.sort(),
{ api_key: apiKey },
{ api_sig: apiSig },
artists.sort(),
{ method: apiMethod },
{ sk: key },
timestamps.sort(),
tracks.sort());
$.ajax({
url: apiUrl,
type: "POST",
data: songsToScrobble,
success: function (data) {
console.log(data);
}
});
}
Now the object sent has the correct format (JSON). What can still be wrong?
I did a quick sample JS Fiddle of your code.
The dataToHash is like this:
album[0]Achtung Babyalbum[1]Achtung Babyapi_keyxxxBLAHxxxartist[0]U2artist[1]U2methodtrack.scrobbleskkkkFOOkkktimestamp[0]1379368800timestamp[1]1379369000track[0]Onetrack[1]The FlymmmySecrettt
The songsToScrobble variable in the code above looked like this:
{ "album": [
"album[0]Achtung Baby",
"album[1]Achtung Baby"
],
"api_key":"xxxBLAHxxx",
"api_sig":"8dbc147e533411a41ba9169f59e65b3a",
"artist":["artist[0]U2","artist[1]U2"],
"method": "track.scrobble",
"sk":"kkkFOOkkk"
"timestamp": [
"timestamp[0]1379368800",
"timestamp[1]1379369000"
],
"track": [
"track[0]One",
"track[1]The Fly"
]
}
I believe songsToScrobble should look like this:
{ "album[0]": "Achtung Baby",
"album[1]": "Achtung Baby",
"api_key":"xxxBLAHxxx",
"api_sig":"8dbc147e533411a41ba9169f59e65b3a",
"artist[0]": "U2",
"artist[1]": "U2",
"method": "track.scrobble",
"sk":"kkkFOOkkk"
"timestamp[0]": "1379368800",
"timestamp[1]": "1379369000",
"track[0]": "One",
"track[1]": "The Fly"
}
Only other minor point is to make sure dataToHash is UTF-8 encoded before you convert to MD5 hash.
Edit
This is how I created the data for the ajax call. NOTE: this is untested - I don't have a last.fm account.
var songsToScrobble = {};
function addDataToScrobble(parentElement, inputData) {
if ($.isArray(inputData)) {
$.each(inputData, function(index ,element) {
songsToScrobble[parentElement + "[" + index + "]"] = element;
dataToHash += parentElement + "[" + index + "]" + element;
});
} else {
songsToScrobble[parentElement] = inputData;
dataToHash += parentElement + inputData;
}
}
for (var i = 0; i < data.tracks.length; i++) {
albums.push(data.album);
artists.push(data.artist);
// The tracks are coming in the format: title|timestamp
timestamps.push(data.tracks[i].split("|")[1]);
tracks.push(data.tracks[i].split("|")[0]);
}
addDataToScrobble("album", albums);
addDataToScrobble("api_key", apiKey);
addDataToScrobble("artist", artists);
addDataToScrobble("method", apiMethod);
addDataToScrobble("sk", key);
addDataToScrobble("timestamp", timestamps);
addDataToScrobble("track", tracks);
apiSig = $.md5(unescape(encodeURIComponent(dataToHash+apiSecret)));
songsToScrobble["api_sig"] = apiSig;
$.ajax({
url: apiUrl,
type: "POST",
data: songsToScrobble,
success: function (data) {
console.log(data);
}
});

Passing JSON to controller action issue

I have the following javascript.
Problem is if I enter one row in the table "ingredients" but I am getting 2 rows in the resulting pass to controller action after seralising into my C# object. But the second object is null?
I checked the javascript and the variable "cnt" is 1 not 2.
Why would that be?
Malcolm
[code]
$("#Save").click(function () {
var title = $("#recipetitle").val();
var category = $("#category").val();
var preptime = $("#prepTime").val();
var preptimeperiod = $("#lstPrepTime").val();
var cooktime = $("#cookTime").val();
var cooktimeperiod = $("#lstCookTime").val();
var rating = $("#rating").val();
var method = $("#method").val();
var jsontext = '{ "RecipeTitle": "' + title + '",';
jsontext += '"CategoryID":' + category + ',';
jsontext += '"PrepTime":' + preptime + ',';
jsontext += '"PrepTimePeriod":"' + preptimeperiod + '",';
jsontext += '"CookTime":' + cooktime + ',';
jsontext += '"CookTimePeriod":"' + cooktimeperiod + '",';
jsontext += '"Rating":' + rating + ',';
jsontext += '"Method":"' + method + '",';
var ing = "";
var cnt = 0;
$("#ingredients tr.ingredientdata").each(function () {
if ($("td.ingredient", this).text() != "") {
ing += '{ "IngredientName": "' + $("td.ingredient", this).text() + '",';
ing += '"Units": ' + $("td.units", this).text() + ',';
ing += '"Measure": "' + $("td.measure", this).text() + '"} ,';
}
cnt = cnt + 1;
});
alert(cnt);
if (ing != "") {
jsontext += '"Ingredients": [';
ing = ing.substring(0, jsontext.length - 1);
jsontext = jsontext + ing;
jsontext += ']';
}
jsontext += '}';
var json = eval('(' + jsontext + ')');
//var json = { Field: 1 };
$.ajax({
url: "/Recipe/Save",
type: "POST",
dataType: 'json',
data: JSON.stringify(json),
contentType: "application/json; charset=utf-8",
success: function () {
//alert("DONE!!");
}
});
});
[/code]
I would recommend a refactoring of your javascript as it would help you identify the errors more easily. Also checkout with FireBug the actual JSON request being sent to the controller:
$("#Save").click(function () {
var ingredients = $('#ingredients tr.ingredientdata').map(function(index, element) {
return {
ingredientName: $('td.ingredient', element).text(),
units: $('td.units', element).text(),
measure: $('td.measure', element).text()
};
});
var json = {
RecipeTitle: $('#recipetitle').val(),
CategoryID: $('#category').val(),
PrepTime: $('#prepTime').val(),
PrepTimePeriod: $('#lstPrepTime').val(),
CookTime: $('#cookTime').val(),
CookTimePeriod: $('#lstCookTime').val(),
Rating: $('#rating').val(),
Method: $('#method').val(),
Ingredients: ingredients
};
$.ajax({
url: '/Recipe/Save',
type: 'POST',
dataType: 'json',
data: JSON.stringify(json),
contentType: 'application/json; charset=utf-8',
success: function () {
//alert("DONE!!");
}
});
});

Categories

Resources