1

I want to append form data into a json file, here is my code however i'm not sure what I have done wrong. Every time I submit data via post I only get an error response. Where is this code going wrong?

HTML

<form class="ajax form-inline">
<div class="form-group">
            <label for="exampleInputAmount">Yo, whats your first name?</label>
            <div class="input-group">
              <input type="text" class="form-control" id="fname" placeholder="First name">
            </div>
          </div>
          <div class="form-group">
            <label for="exampleInputAmount">&& Last name?</label>
            <div class="input-group">
              <input type="text" class="form-control" id="lname" placeholder="Last name">
            </div>
          </div>
          <button type="submit" class="btn btn-primary">Submit to JSON</button>
        </form>

JS/ Jquery

  $('form.ajax').on('submit', function(){
      var $fname = $("#fname")
            var $lname = $("#lname")
            var object = {
            firstname: $fname.val(),
            lastname: $lname.val(),
            }

            var params = JSON.stringify(object);


            $.ajax({
              type: 'POST',
              data: params,
              dataType: "json",
              url: 'save_to_json.php',

              success: function(data) {
                  console.log('success');
                },
                error: function(data) {
                  console.log('error');
                },
                complete: function() {
                  console.log('complete');
                }
                });
                return false;
e.preventDefault()
            });

PHP / save_to_json.php

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

     $jsonObject = json_encode($params);
     file_put_contents('my_json_data.json', $jsonObject, FILE_APPEND);
 }
 else {
   echo "Noooooooob";
 }

 ?>
Simon
  • 147
  • 1
  • 10
  • what error you are getting? First of that you have to write `e.preventDefault()` for `submit` with `ajax` – Parth Trivedi Jan 21 '16 at 10:28
  • file_put_content should be file_put_contents – Franz Gleichmann Jan 21 '16 at 10:29
  • Instead of `console.log('error');` or `console.log('succes');` Use `console.log(data);` This will give you more details (most of the time) – Reyno Jan 21 '16 at 10:34
  • @theblackgigant Thanks, now it states 'Uncaught ReferenceError: data is not defined' – Simon Jan 21 '16 at 10:38
  • @Simon That probably means you're not returning anything, try adding `echo $jsonObject;` in your if statement, also i don't think FILE_APPEND is needed (not sure about that though) – Reyno Jan 21 '16 at 10:44
  • -1 and voted to close for the lack of either a single, narrow problem or an MCVE demonstrating it (and also the ugly, readability-harming formatting). – Mark Amery Jan 17 '17 at 20:28

1 Answers1

0

First of all, use event.preventDefault() method to stop your form from being submitted.

Here's the reference:

Second, there's no point using var params = JSON.stringify(object); in your code.

And finally, Remove this line dataType: "json", unless you're expecting a json object as response from server. dataType is the type of data that you're expecting back from the server.

So your jQuery script should be like this:

$(document).ready(function(){
    $('form.ajax').on('submit', function(e){
        e.preventDefault();
        var $fname = $("#fname");
        var $lname = $("#lname");
        var params = {
        firstname: $fname.val(),
        lastname: $lname.val(),
        }

        $.ajax({
          type: 'POST',
          data: params,
          url: 'save_to_json.php',

          success: function(data) {
              console.log('success');
            },
            error: function(data) {
              console.log('error');
            },
            complete: function() {
              console.log('complete');
            }
        });
        return false;
    });
});

And this is how you can process the AJAX request,

<?php

    if (isset($_POST['firstname']) && isset($_POST['lastname'])) {
        $params = array('firstname' => $_POST['firstname'], 'lastname' => $_POST['lastname']);

        $jsonObject = json_encode($params);
        file_put_contents('my_json_data.json', $jsonObject, FILE_APPEND);
    }
    else {
        echo "Noooooooob";
    }

?>

Edited:

Based on your requirement you should process the AJAX request like this:

<?php

    if (isset($_POST['firstname']) && isset($_POST['lastname'])) {
        $params = array('firstname' => $_POST['firstname'], 'lastname' => $_POST['lastname']);

        $jsonObject = json_encode($params);
        $json = file_get_contents('my_json_data.json');
        if(empty($json)){
            $jsonObject = json_encode(array('username' => [$jsonObject]));
            file_put_contents('my_json_data.json', $jsonObject);
        }else{
            $json = json_decode($json, true);
            $newJson = $json['username'][0] . "," . $jsonObject;
            $jsonObject = json_encode(array('username' => [$newJson]));
            file_put_contents('my_json_data.json', $jsonObject);
        }
    }
    else {
        echo "Noooooooob";
    }

?>
Rajdeep Paul
  • 16,887
  • 3
  • 18
  • 37
  • However the json produced is not valid – Simon Jan 21 '16 at 10:59
  • @Simon The above code would generate a json string like this: `{"firstname":"Rajdeep","lastname":"Paul"}`, which is a perfectly valid json string. You can check it's validity here, [http://jsonlint.com/](http://jsonlint.com/) – Rajdeep Paul Jan 21 '16 at 11:17
  • How do I display it like this? `{"username":[{"firstname":"test","lastname":"ts"},{"firstname":"test","lastname":"test"}]}` – Simon Jan 21 '16 at 11:18
  • @Simon Not sure about the underlying business logic, but this string `{"username": [{"firstname": "test","lastname": "ts"}, {"firstname": "test","lastname": "test"}]}` is a perfectly valid string. – Rajdeep Paul Jan 21 '16 at 11:24
  • the string you showed is valid, but when more are added they need a comma to separate them. That is why its best if I have the JSON like I demonstrated. But im not sure what to send to the PHP file to do so. Also this is a reduced test case. :) – Simon Jan 21 '16 at 11:24
  • @Simon It's pretty easy, [see this answer](http://stackoverflow.com/a/18884871/5517143). – Rajdeep Paul Jan 21 '16 at 11:28
  • So the PHP takes the data and turns it into json, why do it client side then? – Simon Jan 21 '16 at 11:41
  • @Simon May I know which PHP version are you using so that I can update my answer accordingly. – Rajdeep Paul Jan 21 '16 at 11:51
  • I am using PHP Version 5.4.45-0+deb7u2 – Simon Jan 21 '16 at 11:54
  • @Simon Before testing your application with the updated code make sure that `my_json_data.json` file is empty. – Rajdeep Paul Jan 21 '16 at 12:03
  • Thank you for putting in the time to help me. After looking at question you told me I also thought doing it server side might be better. Now howerever it add \ to the json file. – Simon Jan 21 '16 at 12:05
  • @Simon Backslashes are added just to escape the inner double quotes, but that's a valid json string. Having said that, it'll get escaped when you decode the json string using `json_decode()` function. – Rajdeep Paul Jan 21 '16 at 12:11
  • How do I add JSON_UNESCAPED_SLASHES? also if the data is just numbers, how do you remove the quotes? – Simon Jan 21 '16 at 13:34
  • @Simon I don't understand what exactly you're trying to do, but refer [this SO question](http://stackoverflow.com/questions/6743554/problem-slash-with-json-encode-why-and-how-solve-it) and [the documentation](http://php.net/manual/en/function.json-encode.php) to know what it does or how it works. – Rajdeep Paul Jan 21 '16 at 14:11
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/101313/discussion-between-simon-and-rajdeep-paul). – Simon Jan 21 '16 at 14:53
  • -1 for [answering an off-topic question](http://meta.stackexchange.com/q/194963/200582) (no MCVE) and [for the "**Edited:**" marker](http://meta.stackexchange.com/q/127639/200582). – Mark Amery Jan 17 '17 at 20:26