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.
Related
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.
[added:] Thank you guys for the reply. I understand that ajax has to used on a server. I wonder if there is a way to load the data from local json file into js in this example?
I have a file named employee.json. I tried load this JSON data into JavaScript. I saved both the .json and .html files on my desktop but when I click in the HTML, there is nothing shown. I tried to use alert() in the .ajax() method but it does not work. I am not sure what is wrong with my AJAX method. What do I need to do to take the id from the JSON and put it into an array in javaScript? Thank you in advance.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
var res = [];
$.ajax({
url: 'employee.json',
dataType: 'json',
method: 'get',
cache: false,
success: function(data) {
$(data.employee).each(function(index, value) {
res.push(value.id);
});
document.getElementById("demo").innerHTML = res.toString();
}
});
</script>
</body>
</html>
{
"employee": [{
"id" : 1,
"firstName" : "Lokesh"
},{
"id" : 2,
"firstName" : "bryant"
},{
"id" : 3,
"firstName" : "kobe"
}]
}
As an alternative you can load your JSON as a javascript, just wrap all your JSON data into
var employees = { /*all your json data here*/ }
and save this as employees.js
Then you can just use a regular script tag in the html:
<script src="/yourpath/employees.js"/>
And then inside your javascript "employees" will be a global object.
so you will have:
employess.employee[1].FirstName
result in "bryant" in your case;
I'm trying to update a file in Alfresco... And I make this code:
var csrf_header = Alfresco.util.CSRFPolicy.getHeader();
var csrf_token = Alfresco.util.CSRFPolicy.getToken();
function getResponse(pdfbase64) {
var fd = new FormData();
if (Alfresco.util.CSRFPolicy && Alfresco.util.CSRFPolicy.isFilterEnabled())
{
fd.append(csrf_header, csrf_token);
}
fd.append("username", "admin");
fd.append("updatenoderef", nodeRef);
fd.append("filedata", pdfbase64);
fd.append("majorversion", "true");
fd.append("overwrite", "true");
alert(fileUpdateURL);
$.ajax({
url: fileUpdateURL,
type: "POST",
data: fd,
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
});
}
The variable pdfbase64 is the content to put on the file (the changes that I made on the file to update the file in base64), but maybe this isn't the right format?, nodeRef is the reference of the file like: "workspace://SpacesStore/4fb1b7e7-2502-4011-8870-17e8d626b93b" and fileUpdateURL is the URL to POST: http://localhost:8080/share/proxy/alfresco/api/upload
Source of params
I got the error:
POST http://localhost:8080/share/proxy/alfresco/api/upload 500
Internal Server Error
javax.servlet.ServletException: Possible CSRF attack noted when
comparing token in session and request parameter. Request: POST
/share/proxy/alfresco/api/upload at
org.alfresco.web.site.servlet.CSRFFilter$AssertTokenAction.run(CSRFFilter.java:845)
at
org.alfresco.web.site.servlet.CSRFFilter.doFilter(CSRFFilter.java:312)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241
) at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at
org.alfresco.web.site.servlet.SSOAuthenticationFilter.doFilter(SSOAuthenticationFilter.java:447)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241
) at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at
org.alfresco.web.site.servlet.MTAuthenticationFilter.doFilter(MTAuthenticationFilter.java:74)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241
) at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
at
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1074)
at
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2466)
at
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2455)
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
EDIT:
If I use
http://localhost:8080/alfresco/service/api/upload
instead of
http://localhost:8080/share/proxy/alfresco/api/upload
I get the error:
{
"status" :
{
"code" : 400,
"name" : "Bad Request",
"description" : "Request sent by the client was syntactically incorrect."
},
"message" : "Required parameters are missing",
"exception" : "",
"callstack" :
[
],
"server" : "Community v5.0.0 (d r99759-b2) schema 8,022",
"time" : "Jan 24, 2016 1:14:41 PM"
}
Can anyone help me?
EDIT2:
I try to make the request with http://localhost:8080/share/proxy/alfresco/api/upload with this:
function getResponse(pdfbase64) {
var csrf_header = Alfresco.util.CSRFPolicy.getHeader();
var csrf_token = Alfresco.util.CSRFPolicy.getToken();
var fd = new FormData();
if (Alfresco.util.CSRFPolicy && Alfresco.util.CSRFPolicy.isFilterEnabled())
{
fd.append(csrf_header, csrf_token);
fileUpdateURL += "?" + Alfresco.util.CSRFPolicy.getParameter() + "=" + encodeURIComponent(Alfresco.util.CSRFPolicy.getToken());
}
fd.append("username", "admin");
fd.append("updatenoderef", nodeRef);
fd.append("filedata", pdfbase64);
fd.append("majorversion", "true");
fd.append("overwrite", "true");
alert(fileUpdateURL);
$.ajax({
url: fileUpdateURL,
type: "POST",
data: fd,
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
});
}
But I obtain the error:
{
"status" :
{
"code" : 400,
"name" : "Bad Request",
"description" : "Request sent by the client was syntactically incorrect."
},
"message" : "Required parameters are missing",
"exception" : "",
"callstack" :
[
],
"server" : "Community v5.0.0 (d r99759-b2) schema 8,022",
"time" : "Jan 24, 2016 1:14:41 PM"
}
Try moving these lines inside your function:
var csrf_header = Alfresco.util.CSRFPolicy.getHeader();
var csrf_token = Alfresco.util.CSRFPolicy.getToken();
And if that does not solve your problem and the issue turn out to be not a matter of variable scope for csrf_* vars, then you should try hint (2) from here
UPDATE :
As I explained in our chat you should replace :
fd.append("filedata", pdfbase64);
with :
fd.append("filedata", new Blob([pdfbase64], {type: 'application/pdf'}););
Instead of setting the header, pass the token on the url:
if (Alfresco.util.CSRFPolicy && Alfresco.util.CSRFPolicy.isFilterEnabled())
{
url += "?" + Alfresco.util.CSRFPolicy.getParameter() + "=" + encodeURIComponent(Alfresco.util.CSRFPolicy.getToken());
}
As described in CSRF Policy
When uploading a file by submitting a form with enctype
multipart/form-data it is not possible to set a header on the request,
the reason is not because of the enctype specifically but due to the
fact that its not possible to set a header on any form submission in
the browser.
The other solution is to use Alfresco.forms.Form that takes care of everything.
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 am trying to retrieve a list of places from Google Places API in JSON. I am sending an AJAX request.
The GET request sends the correct parameters and receives a 200 OK success message, but no response (per firebug).
Do you know how I can retrieve the list of places in JSON or convert JSONP to JSON?
photos.js
$.ajax({
type: 'GET',
url:'https://maps.googleapis.com/maps/api/place/search/json',
dataType: 'json',
data: {
'location' : data.location.latitude+","+data.location.longitude,
'radius' : 500,
'key' : "mykeyhere",
'sensor' : "false",
'keyword' : "hotel"
},
success: function(hotel){
console.log(hotel);
}
});
I have tried changing dataType to jsonp and I was able to get a response with all the listings, but I get "html_attributions" : [] error because it is expecting JSON.The response is as described in https://developers.google.com/places/documentation/search , but I get a firebug error that does not recognize html_attributions
Ok! I've got a solution (thanks to Chris Green)!
Just use this
function produceSearch(term) {
var _params = {
radius : 11000,
name : term,
location : app.modules.mapsProvider.getLatLng(),
key : 'KEY'
};
var service = new google.maps.places.PlacesService(map_inst);
service.search(_params, requestSucceeded);
}
Instead of jQuery Ajax function :)
https://developers.google.com/maps/documentation/javascript/places#place_search_requests