Jump to content

JSON


marcosdipaolo

Recommended Posts

Hi there. 

I'm a total ignorant about PHP, i need a little bit of help to write a really simple file. 

 

I have this form (sorry it's in spanish, but you get the idea):

 

68swog.jpg

 

Ok, I took the input of the form, created an JS object and the I JSON stringified it.  Then an ajax call to POST. Here it comes, i need the info to be appended into a JSON file, AND I DON'T KNOW HOW TO DO THAT and haven't found help all over the internet in this whole day, (about 10 hours already, imagine how frustrated i am).

 

Javascript Code:

var datos = document.getElementById('datos'); // this is the form
var boton = document.getElementById('boton'); // this is the button
var datosNombre, datosApellido, datosEdad, datosDni, datosCompletos, datosJson;// declaring variables
boton.addEventListener('click', grabardatos);

function grabardatos() {
    // VARIABLES
    datosNombre = datos.elements['nombre'].value;
    datosApellido = datos.elements['apellido'].value;
    datosEdad = datos.elements['edad'].value;
    datosDni = datos.elements['dni'].value;
    datosCompletos = { 
        nombre: datosNombre,
        apellido: datosApellido,
        edad: datosEdad,
        dni: datosDni
    }
    datosJson = JSON.stringify(datosCompletos); 
    var postRequest = new XMLHttpRequest(); 
    postRequest.open("POST", "datos.php");
    postRequest.setRequestHeader("Content-type", "application/json;charset=UTF-8");
    postRequest.send(datosJson); 
};

I would need the code for datos.php where the JSON data is received and stored in datos.json.

 

Thanks a lot, you'd help me a lot .

Link to comment
Share on other sites

  1. This question should be posted in the Javascript section.

Consider using jQuery.  Yeah, native JavaScript is better if you have tons of time on your hands, but otherwise...

What "info" do you need be appended?

So, you want to send some content from the client to the server, and then store it as a file?  First, make sure your server is getting the data. Put var_dump($_POST);exit; at the top of your php, and make the request.  Getting it?    Then you would use http://php.net/manual/en/function.json-encode.php to turn the $_POST array (or some element of it)  into a string, and http://php.net/manual/en/function.file-put-contents.php to store it in a file.

Link to comment
Share on other sites

 

  1. This question should be posted in the Javascript section.
  2. Consider using jQuery.  Yeah, native JavaScript is better if you have tons of time on your hands, but otherwise...
  3. What "info" do you need be appended?
  4. So, you want to send some content from the client to the server, and then store it as a file?  First, make sure your server is getting the data. Put var_dump($_POST);exit; at the top of your php, and make the request.  Getting it?    Then you would use http://php.net/manual/en/function.json-encode.php to turn the $_POST array (or some element of it)  into a string, and http://php.net/manual/en/function.file-put-contents.php to store it in a file.

 

 

1- I actually need help on the PHP side, not the JS

2- Yes, absolutely, but I'm actually learning and I want to figure this out in JS first. 

3- The info to be appended is the info the User input at the form. What i'm sending is a json string like this one:

{
 "nombre":"",
 "apellido":"",
 "edad":"",
 "dni":""
}

I already managed to understand fopen / fwrite / fclose and how to create with php a json file and append info to it. The problem is that the file isn't receiving the info and i don't know if the problem is in the JS, the PHP or both.

4-   I tried the var_dump($_POST) getting array(0){}; the thing is i tried in two ways, first with the button outside the form tag (and without the type of submit), and with the button inside the form tag with type of submit and the for with the action attribute of "datos.php". In the last case is where i could see the array(){}, in the other i didnt since it is an ajax call and the php doesn't get opened in the browser.     

Link to comment
Share on other sites

Split the project into small parts instead of writing one big block of code only to find out that it doesn't work and that you cannot debug it either.

 

If you're mostly interested in the PHP part, then forget about JavaScript for now. Write a minimal PHP script which JSON-encodes test data and writes the result to a file.

<?php

$test_data = [
    'foo' => 'bar',
    'qux' => 'quux',
];

$encoded_data = json_encode($test_data);

// file handling code goes here

You can easily var_dump() every single step and test the code until you know it's correct.

 

Note that writing JSON data to files is a very nasty and cumbersome approach, especially if you want to do it correctly (i. e. without messing up your data). As soon as you got past the Hello-world stage, you should look into actual database systems.

Link to comment
Share on other sites

Then you're not doing what I said.

 

I said: Take hard-coded test data. Do not send anything. Just write the data directly into your code. Write – it – down. OK?

 

When your goal is to test file operations, but you spend all your time trying to get some form to work, then there's something wrong with your priorities.

Link to comment
Share on other sites

Then you're not doing what I said.

 

I said: Take hard-coded test data. Do not send anything. Just write the data directly into your code. Write – it – down. OK?

 

When your goal is to test file operations, but you spend all your time trying to get some form to work, then there's something wrong with your priorities.

 

Sorry pal, i didn't understand. Well, yes, harcoded info works without any problems, either back into the html with .responseText or recorded into the JSON file. 

Something like this:

<?php 

// this for the response 

echo 'this is a test';

// this to create and append info to the JSON file

$datos = fopen("datos.json","a");
fwrite($datos, '{"info": "this is a test"}');
fclose($datos);
?>

this works, i get the info back at the html and i get a json file with the string. 

 

My problem at the moment seems to be getting the form's info into the PHP file.

p.s.: I'm console.logging the variable I'm sending and i get a perfect JSON string. 

Link to comment
Share on other sites

Several things:

  • Your PHP code makes no sense (which is why I suggested extensive tests), because there's no realistic way for you to ever retrieve the data again. You cannot JSON-decode the file content, because it's a sequence of JSON documents, not a single JSON document. You cannot split those documents either, because you have no idea where they begin and end. So the data you're collecting will be pretty useless -- unless you want to manually sift through the entire file.
  • You cannot pull the received data out of $_POST, because you aren't sending regular form data. You're sending a JSON document, and PHP has no idea what to do with that. You have to pull the raw HTTP body out of the php://input stream and parse it yourself.
Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.