0

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

Eric Brandwein
  • 861
  • 8
  • 23
remid
  • 15
  • 4
  • I believe you actually need a controller method to update/create that json file. – Christopher Marshall May 26 '15 at 18:19
  • it will may helps you http://stackoverflow.com/questions/8951810/how-to-parse-json-data-with-jquery-javascript – gtzinos May 26 '15 at 18:20
  • You are not writing to file – Luka Krajnc May 26 '15 at 18:21
  • Also assuming .submit is a submit button, instead attach to the form submit and cancel the submit: `$("#formID").on("submit",function(e) { e.preventDefault(); var nickName....` – mplungjan May 26 '15 at 18:24
  • Yeah that's what I thought, but i don't really know how to write into the JSON in jquery, do you know where i can find some informations about it ? I try to don't use PHP for this one – remid May 26 '15 at 18:24
  • you need to write a server based file in, for example php to handle the post – Grumpy May 26 '15 at 18:25
  • 1
    You do not have a choice. You must use a server based process unless your whole thing is on your own local computer, then you could use the file API – mplungjan May 26 '15 at 18:26
  • Yeah i think i have to use PHP to store the datas, i'm gonna try to learn more about it, thanks – remid May 26 '15 at 18:28
  • 1
    You're attempting to use an HTTP request to directly write a file to your webserver.... can you imagine how that might be taken advantage of? – Jason P May 26 '15 at 18:49

1 Answers1

0

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.

Steeve Lefort
  • 89
  • 1
  • 3