1

I want to get form variables and push them into an array in memory only and not destroy the page by reloading. This is really something I have no expertise in. Can this be done? I need to add contents to a json file with php based on a form.

JSON DATA:

var members = [ 
{ "Class": "B", "Rating": "1776", "ID": "12537964", "Name": "Ahmed, Jamshed", "Expires": "2018.10.18" }, 
{ "Class": "C", "Rating": "1500", "ID": "12210580", "Name": "Attaya, James", "Expires": "2019.01.12" }, 
{ "Class": "F", "Rating": "0000", "ID": "16281977", "Name": "Auld, Thomas", "Expires": "" }, 
{ "Class": "B", "Rating": "1759", "ID": "10117780", "Name": "Badamo, Anthony", "Expires": "2018.09.12" }
]

JS:

<form action="" id = "newMember" class="pure-form" method = "GET" > 
<fieldset> 

<label for="mem-name">Last, First name:</label> <input type="text" id = "mem-name" name="mem-name" maxlength = "25" size = "20" /> 
<label for="mem-expires">Membership:</label> <input type="text" id = "mem-expires" name="mem-expires" maxlength = "10" size = "8" /> <br /> 
<label for="mem-rating">Rating:</label> <input type="text" id = "mem-rating" name="mem-rating" maxlength = "4" size = "3" /> 
<label for="mem-ID">ID:</label> <input type="text" id = "mem-ID" name="mem-ID" maxlength = "8" size = "7" /> 
<label for="mem-class">Class:</label> <input type="text" id = "mem-class" name="mem-class" maxlength = "2" size ="2" /> 

<button type="button" id="addPlayer" style="margin-left:2rem;" class="pure-button pure-button-primary" onClick="validateForm()">add new player</button> 
<button type="reset" style="margin-left:2rem;" class="pure-button pure-button-secondary">reset form</button> 

</fieldset> 

</form>

<script> 

function validateForm() { 

var memName = document.getElementById('mem-name').value; 
var memExpires = document.getElementById('mem-expires').value; 
var memRating = document.getElementById('mem-rating').value; 
var  memID = document.getElementById('mem-ID').value; 
var memClass = document.getElementById('mem-class').value; 

if (memName == "") { 
alert("Name must be filled out"); 
return false; 
}else { 

$.ajax({ 

type: 'GET', 
url : 'welcome.php', 
data : { 

'mem-name' :memName, 
'mem-expires' :memExpires, 
'mem-rating' :memRating, 
'mem-ID' :memID, 
'mem-class' :memClass 

}, 
success : function(data) { 

console.log('My data should be here: ' + data); 

members = JSON.parse(data); 
console.log(members);

} 

}); 

} 

} 

</script>

MEMBERS.PHP:

<?php 

// Clean up data 
function test_input($data) { 
$data = trim($data); 
$data = stripslashes($data); 
$data = htmlspecialchars($data); 
return $data; 
} 


// define variables and set to empty values 
$mem_name = $mem_expires = $mem_rating = $mem_ID = $mem_class = ""; 

if ($_SERVER["REQUEST_METHOD"] == "GET") { 
$mem_name = test_input($_GET["mem-name"]); 
$mem_expires = test_input($_GET["mem-expires"]); 
$mem_rating = test_input($_GET["mem-rating"]); 
$mem_ID = test_input($_GET["mem-ID"]); 
$mem_class = test_input($_GET["mem-class"]); 

$array = array( 

"Class" => $mem_class, 
"Rating" => $mem_rating, 
"ID" => $mem_ID, 
"Name" => $mem_name, 
"Expires" => $mem_expires 


); 

$json = file_get_contents('/home/verlager/public_html/cccr_mems.json'); 

$json = preg_replace('/\s{0,}var\s{0,}members\s{0,}=\s{0,}/', '', $json); 
$json = preg_replace('/];\s{0,}/', ']', $json); 

$json_data = json_decode($json,true); 

array_push($json_data, $array); 

$encodedJson = json_encode($json_data); 

$myNewJson = 'var members =' . $encodedJson . '];';

file_put_contents('/home/verlager/public_html/cccr_mems.json', $myNewJson, LOCK_EX); 

echo json_encode($encodedJson); 

} 
?>

This almost works, but not quite. What is a satisfactory solution?

2 Answers 2

2

You can use array_push() to add another element of an array to an already existing array. If your js script uses an AJAX call to the php page, the php page will send back the json string to the calling js page. Then you can do whatever you want with it.

<?php
    // define variables and set to empty values
    $mem_name = $mem_expires = $mem_rating = $mem_ID = $mem_class = "";
    if ($_SERVER["REQUEST_METHOD"] == "GET") {
        $mem_name = test_input($_GET["mem-name"]);
        $mem_expires = test_input($_GET["mem-expires"]);
        $mem_rating = test_input($_GET["mem-rating"]);
        $mem_ID = test_input($_GET["mem-ID"]);
        $mem_class = test_input($_GET["mem-class"]);
    }    
    // Clean up data
    function test_input($data) {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        return $data;
    }
    // Read JSON file
    $json = file_get_contents('cccr_mems.json');
    //Decode JSON
    $json_data = json_decode($json,true);
    //Print data print_r($json_data); <=== WORKS
    //Here I want to push the GET vars to json members w/o writing to disk!

    //Create an element of the array.
    $array = array(

      "Class"   => $mem_class,
      "Rating"  => $mem_rating,
      "ID"      => $mem_ID,
      "Name"    => $mem_name,
      "Expires" => $mem_expires


    );

    array_push($json_data, $array); //Add the element to the $json_data array.

    //print_r($json_data);  //Shows the results as a php array. 

    echo json_encode($json_data); //Shows results as json string.
    //This is what will get sent back to the calling js page.


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

9 Comments

Yes, but the new item never shows up in "members" ... in real time.
Are you doing this all from the php script or are you calling the php script from a different file altogether. Please better explain your example of how stuff is happening.
Warning: array_push() expects parameter 1 to be array, null given in /home/verlager/public_html/assets/welcome.php on line 38
I am doing this from the php script.
LIne 38 = array_push($json_data, $array); //Add the element to the $json_data array.
|
0

1.Since $json_data is an associative array, the function array_push($json_data, array('Class' => $mem_class])); Can be used to add the variables to the array.

  1. Use json_encode to convert the array back into a json.

  2. If you don't want the page to reload, you could use an Ajax call from the client side to send the form data to the PHP script, and return the json object created in step 2.

        $.ajax({
        url: '/handle_form_data.php',
        type: 'POST',
        dataType: "json",
        data: {
            name: $('#name').val(),
            expires: $('#expires').val(),
            id: $('#ID'').val()   //all form variables which need to be sent 
        },
    success:function(response){
    //Do stuff with json object returned from step 2
    }
    });
    

Or if I understand your question correctly, If you don't want to reload the page and do not want to save the form data in your backend, the test_input() function can be written in the front end JavaScript, run on the values in the form fields and the results can be added to the member's array. A server call isn't required for this.

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.