2

I have found countless tutorials on how to retrieve data from json files using jQuery and ajax but none on how to POST data to a json file. If some one could show me or send me a small script on how to do this that would be great. I have searched everywhere on how to do this and have had no luck. I have seen examples of people doing it but they seem to forget to share important info that i am not seeing.I have no problem retrieving data json files using ajax. If someone could tell me if i am forgetting something or doing something wrong that would be great. I would be very appreciative if someone could send me a working file so that i can reverse engineer ir and understand how to do it. I am wanting to send the values from $firstName and $caption to the json file. I know this may seem stupid to others but i am tired of all the searching and not getting any straight answers.

Here is what i have.

      getImages: function(){
        var $firstName = $(".name"),
            $caption = $(".caption");
        var object = {
            name: $firstName.val(),
            caption: $caption.val()
        }
        $.ajax({
            type: 'POST',
            data: object,
            url: 'images.json',
            success: function(data){
                console.log("KILLER");
                var count = 0;
                $.each(data, function(i, imgSlide){
                    count ++;
                    //console.log(result.sliderImages[i].url[0].thumb);
                    var imageEl = "<img src='"+imgSlide.url[0].thumb+"' alt='"+imgSlide.name+"'>";
                    var slide = "<li class='imageSlide' data-id='"+count+"'>"+imageEl+"</li>";
                    $("ul.imageGallery").append(slide).fadeIn();
                });
            },
            error: function(){
                console.log("Abort");
            },
            timeout: 3000,
            beforeSend: function(){

            },
            complete: function(){

            }
        });

    }

and here is my JSON file

    [{
      "name": "Bootcamp",
      "url": [{
        "thumb": "img/ill-bootcamp.jpg",
        "med": "img/ill-bootcamp.jpg",
        "large": "img/ill-bootcamp.jpg"
            }],
      "caption": "Lifetime Fitness",
      "ID": ""
     },
     {
       "name": "Pinup Girl",
       "url": [{
            "thumb": "img/ill-pinup.jpg",
            "med": "img/ill-pinup.jpg",
            "large": "img/ill-pinup.jpg"
             }],
      "caption": "Illustration",
      "ID": ""
     },
     {
       "name": "SixDitch",
       "url": [{
             "thumb": "img/web-sixditch.jpg",
             "med": "img/web-sixditch.jpg",
             "large": "img/web-sixditch.jpg"
             }],
       "caption": "SD MotorSports",
       "ID": ""
     }]
3
  • 1
    You mean, post data and save it into a JSON file? For that you would need a server-side script language, like php. Commented Sep 16, 2014 at 17:58
  • 1
    can't post to an unexecutable text file Commented Sep 16, 2014 at 18:03
  • That is what i thought, i was just unable to get a straight answer on it. Got to the point where i was willing to ask the stupid question and get it over with. Thank you. got confused when i saw this video about POSTING with ajax and json but he failed to mention the part about working php in his video. Commented Sep 16, 2014 at 18:19

2 Answers 2

6

So you will need to use server-side script language. In this case we will use PHP.

After defining your json object you turn it into string and send it to the php file via post. From there the PHP will take it and encode it as a JSON object. This json object will saved to a file named my_json_data.json with the php function file_put_contents(). If you want to append the new content instead of replacing the old one use the function like this:

file_put_content('my_json_data.json', $jsonObject, FILE_APPEND);

JavaSrcipt:

var $firstName = $(".name"),
    $caption = $(".caption");
var object = {
    name: $firstName.val(),
    caption: $caption.val()
}

var params = JSON.stringify(object);

$.ajax({
    type: 'POST',
    data: params,
    url: 'save_to_json.php',
    success: function(data){
        // do something on success
    },
    error: function(){
        // do something on error
    }
});

PHP (save_to_json.php):

    if (!isset($_POST['params']) && !empty($_POST['params'])) {
        $params = $_POST['params'];

        $jsonObject = json_encode($params);
        file_put_contents('my_json_data.json', $jsonObject);
    }

I hope I didn't missed something. Good luck.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for taking the time to help me out. I was unsure he you needed php for this process and now i know you need it. Stupid question on my side but glad i finally asked.
I'm glad I helped. Please check this answer as accepted if it solved your problem :)
@HristoEnev I tried your solution also to my problem and it works. However when writing to the json file there are spaces and \ \ symbols. How to deal with this one? It seems its not in the proper json format.
2

It was a bit unclear ...
client side languages are not able to write or edit something on the server
via AJAX (with or without jQuery) you are only able to read data or send them
so you can pass your data to a php file then execute what you want to do , by php.
here is a tutorial for working with files in php
http://www.w3schools.com/php/php_file_open.asp
and here is another one for getting passed data by AJAX in php file
http://www.w3schools.com/php/php_superglobals.asp
look at $_GET , $_POST , $_REQUEST
good luck

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.