I'm struggling with sending a data which contains object as a member property.
This is the domain class.
public class Timeline extends Post{
String picture;
User user;
int like;
...
(getters and setters)
}
And I've got the JSON data with this code already so I could get the data from 'obj' variable.
var obj;
$.ajax({
method: "GET",
dataType: "json",
url: serverRoot + "/json/auth/loginUser",
async: false
})
.done(function(data) {
obj = data;
});
And the returned data looks like this.
"user" : {
"userNo" : 1,
"name" : "user01",
...
}
The next JSON data is the data I'd like to send to a server.
{
"no" : 23,
"content" : "hihi",
"createdData" : "2018-07-22",
"picture" : null,
"user" : {
"userNo" : 1,
"name" : "user01",
... **obj JSON data I got above**
}
}
And this is the codes to send to a server.
(Here is the thing I've been stuck)
$("#sh-tl-post-btn").click(() => {
$.ajax({
type: 'POST',
url: '../../../json/timeline/add',
data: {
picture: $('#sh_tl_upload').val(),
content: $('#sh_tl_post_write').val(),
**user: [{"userNo":obj.userNo}]**
},
}).done(function() {
console.log("inserted.");
location.href = "timeline.html"
});
});
The Mapper file looks like this.
<insert id="insert" parameterType="Timeline">
<choose>
<when test="picture != ''">
insert into TML(tmlno, uno, tmlpath)
values(#{no}, #{userNo}, #{picture})
</when>
<otherwise>
insert into TML(tmlno, uno)
values(#{no}, #{userNo})
</otherwise>
</choose>
</insert>
I've been searching what to write on here instead of
user: [{"userNo":obj.userNo}] , this...
I've been trying
user : {"userNo" : obj.userNo}
user.userNo : obj.userNo
user.[0].userNo : obj.userNo
...
but the console keeps saying
[Request processing failed; nested exception is
org.springframework.beans.InvalidPropertyException:.....
this kind of errors.
Is there anyone could help me how to bind the nested object's property via ajax
JSON data? Thanks in advance.
Related
I have a json file (file1.json) which contain json data.
I would like to replace these data by new datas (newDataToStore).
I don't know how to do it using a php file (save.php file below) ?
Content of file1.json :
[
{
"key" : "test1",
"desc": "desc1"
},
{
"key" : "test2",
"desc": "desc2"
},
]
New json to write into json1.json file :
var newDataToStore =
[
{
"key" : "test2",
"desc": "desc2"
},
{
"key" : "test3",
"desc": "desc3"
},
];
JS
this.save = function (newDataToStore) {
jQuery.ajax({
type : "POST",
dataType : "json",
url : 'save.php',
data : newDataToStore,
success : function() {
console.log("SUCCESS");
},
error : function() {
console.log("ERROR");
}
});
}
Another approach:
You'll need to stringify the JS-Object before sending it to the server:
this.save = function (newDataToStore) {
jQuery.ajax({
type : "POST",
dataType : "json",
url : 'save.php',
data : {'json': JSON.stringify(newDataToStore)},
success : function() {
console.log("SUCCESS");
},
error : function() {
console.log("ERROR");
}
});
}
On the serverside your script should do something like (as Mohammad Alabed pointed out):
file_put_contents('/path/to/file1.json', $_POST['json']);
BUT, beware! Users could write arbitrary data to the file. You should always validate user input on the server side. (Maybe using a json schema)
in php file the json data will be in the post global variable because you use post in your ajax
so all what you need is file_put_contents()
save.php
file_put_contents('file1.json', json_encode($_POST));
by using this function you will write a new json string to your json file (old content will be deleted)
in your save.php file
use json_decode()
it will decode your json datas passed from your ajax file
i'm coding a script that send datas (nickname & score) to a JSON file in Jquery but i'm having trouble to make it work.
Here is my Jquery :
function addInfos() {
var nicknameSubmit = $(".nickname").val();
var scoreSubmit = $(".score").val();
var newScore = {
Nickname : nicknameSubmit,
Score : scoreSubmit
};
$.ajax({
url: './js/scores.json',
type: "POST",
data: JSON.stringify(newScore),
contentType: "application/json",
complete: console.log(nicknameSubmit + " " + scoreSubmit )
});
};
$(".submit").click(function(){
addInfos();
});
I used Jquery.post for this ( http://api.jquery.com/jquery.post/ )
And here is my JSON file :
[{
"Nickname" : "Alex",
"Score" : "1000"
},
{
"Nickname" : "Tom",
"Score" : "0"
}]
The script find the JSON file, it show me the correct values in the console but it doesn't add the values to the JSON file...
Can anyone know where i'm wrong ? Do i do the request properly ?
Thanks in advance,
remid
Unless your server is webdav compatible, you can't save a file on it via HTTP.
You need to create a server side script (perhaps PHP) that reads "POSTed"values and add them in your JSON file.
I have this application where I'm going to update a database using jQuery and the HTTP PUT method.
There's some code before this, and some more after it. I'm having issues with the part where it has id: {...
The id variable is equal to: 9j6bddjg7fd6ee0df09j0989
I need it to end up looking something like this: "9j6bddjg7fd6ee0df09j0989"
The rest (path, http, etc.) work because they don't have quotes around them.
Is there a way that I can have the id surrounded by quotes right before it is sent off to /api/routes?
password = $('#password-' + i).val();
id = $('#id-' + i).html();
jQuery.ajax({
url: "/api/routes",
type: "PUT",
data: {
"routes": [
{
id : {
"path" : path,
"httpMethod": http,
"ensureAuthenticated": password,
"route": route
}
}
If you want the "id" key to be dynamic ( to have the value of your id variable ) you need to use a different notation:
var id = "9j6bddjg7fd6ee0df09j0989",
newRoute = {},
jsonData = {
"routes": []
};
newRoute[id] = {
"path" : "path",
"httpMethod": "http",
"ensureAuthenticated": "passwd",
"route": "route"
}
jsonData.routes.push(newRoute);
$.ajax({
type: 'POST',
dataType: 'json',
url: '/echo/json/',
data : { json: JSON.stringify( jsonData ) },
success: function(data) {
console.log("data > ", data);
}
});
Check this fiddle for a working copy and check your js console for the output.
I have a drop down
<%=Html.DropDownList("genre", Model.genres, "", new { #onchange = ChangeMovie()" })%>
The JavaScript looks like (incomplete)
function ChangeMovie() {
var genreSelection = container.find( '#genre' ).val();
$.ajax({
"url" : "/Movies/GetGenre" ,
"type" : "get" ,
"dataType" : "json" ,
"data" : { "selectedValue" : $( "#genre").val() },
"success" : function (data) {}
});
};
Conrtroller code
public ActionResult GetGenre(string genreName)
{
//Need to get the `genreName` from the JavaScript function above.. which is
// in turn coming from the selected value of the drop down in the beginning.
}
I want to pass the selected value of the drop down to the action result in the controller code via the js function. I need help manipulating the JavaScript code and the AJAX call code so the correct value is passed onto the controller.
You have a lot of unnecessary quotes as well not returning JSON in your action
$.ajax({
url: "/Movies/GetGenre/",
dataType: "json",
cache: false,
type: 'GET',
data: {genreName: $("#genre").val() },
success: function (result) {
if(result.Success) {
alert(result.Genre);
}
}
});
Plus your controller isn't returning Json, modify your action to this
public JsonResult GetGenre(string genreName) {
// do what you need to with genreName here
return Json(new { Success = true, Genre = genreName }, JsonRequestBehavior.AllowGet);
}
For model binding to function correctly, field names of passed json object should match parameter names of your controller action. So, this should work
"data" : { "genreName" : $( "#genre").val() },
The parameter name of the value you're posting in the Ajax request does not match the Action parameter name. selectedValue should be genreName.
Change this:
"data" : { "selectedValue" : $( "#genre").val() },
to this:
data : { genreName : $("#genre").val() },
Using Struts2.
In my Action I have a List<Person> persons;
In javascript, I have this function:
function mytestfunction() {
var url = "MyAction_mytestfunction.action";
var params = {};
var arr = [];
var p1 = { "firstname" : "John", "lastname" : "Doe"};
var p2 = { "firstname" : "Rob", "lastname" : "Smith"};
arr.push(p1); arr.push(p2);
params["persons"] = arr;
$.post(url, params, function(data) {
console.log("done");
});
}
Problem is, the post() never reaches the action. There are no errors in the logs, nothing.
This all changes if instead of posting objects I post primitives. So when I have a List<Integer> nums in the Action and params["nums"] = [1,2,3]; in javascript, everything is posted fine.
So, is there a way to post JSON objects to a Struts2 action via javascript/jquery?
I should mention that I'm using the struts-jquery plugin, not dojo.
I don't know anything about struts, but this is how I POST objects with json:
$.ajax({
type: "POST",
data: JSON.stringify(SOME_JAVASCRIPT_OBJECT),
contentType: "application/json; charset=utf-8"
// etc: etc
});
you can try as following example:
$.ajax({
type: "Post",
url: "action_name", //you can pass through querystring like actionname?paramname=value
data : {
//here comes your param or array
},
dataType:"json",
contentType: "application/json; charset=utf-8",
});
If you want to pass through querystring type must be GET