I the objective of the code that I attached this note is to
Collect data in a form.
Post to a PHP file where the collected information is turned into a JSON
Write the JSON information to a file
Return the JSON and print it to the an ID in the HTML

All of the above works except step 4 and I can seem to find the error. I hope some on will take a look and tell me where I have gone astray.

Recommended Answers

All 14 Replies

I copied the files form the attached zip and everything works fine. Json gets displayed in the jsonReadArea div. Have you checked all permissions are OK?

I can read the file and put the contents in the jsonReadArea div, but when the process leaves the PHP file I would like to learn how to return the JSON to the javaScrip/jQuery and display it. Look at the success funcction in local.js. Hope my description is clear.

The jquery load function does exactly that. It is the following function in the local.js:

$('#jsonReadButton').click(function () {
    alert('Click');
    $('#jsonReadArea').load('storage/jsonStorage.txt');
});

I added the alert function to check if the call gets through OK. If you get alert, then the JSON should be loaded into the div. If not, something is wrong with permissions, path or something similar.

I'm not explaining clearly what I cannot do. I know that I can write the JSON data to a file and later read the entire contents of the file to the jsonReadArea <div>. I would also like to be able from the PHP file return the current JSON to the jQuery success function and display it. Further investigating last night with the debugger, I seem to be returning a object and that is not being accessed correctly.
In the HTML you will find a <div> called "the-return" and text that reads "HTML is replaced when successful. And in the jQuery post function you will see that both the success and error return try to write to this <div>. What I don't know how to do correctly is in the PHP file send the JSON back to the jQuery post if successful, and an error statement if unsuccessful and write to the "the-return" <div>.
Thanks!

You have to define all the criteria for errors. You have already defined one criteria being file open error. I do not know what other errors you would like to catch. Maybe some missing data in the JSON or invalid data etc. See comments in my example:

// since there can be many types of errors save them in an array 
$errors = array();

$name = filter_input(INPUT_POST, "name", FILTER_SANITIZE_STRING);
$email = filter_input(INPUT_POST, "email", FILTER_VALIDATE_EMAIL);
$gender = filter_input(INPUT_POST, "gender", FILTER_SANITIZE_STRING);
$temperature = filter_input(INPUT_POST, "temperature", FILTER_SANITIZE_STRING);
$terms = filter_input(INPUT_POST, "terms", FILTER_SANITIZE_STRING);

$tempArray = array("name" => $name, "email" => $email, "gender" => $gender, "temperature" => $temperature, "terms" => $terms);

// check if required fields exist (e.g. email)
if(isset($tempArray["email"]) && !empty($tempArray["email"])) {
    $errors[] = 'Email field is empty';
}

// check if encoding worked
$jsonVal = json_encode($tempArray);
if($jsonVal === false) {
    $errors[] = 'Encoding to JSON failed';
}

// Open file and test operation
$fileHandle = fopen('storage/jsonStorage.txt', "a");
if (!$fileHandle) {
    // check if file could be opened
    $errors[] = 'Could not open the file for writing';
} else {
    fwrite($fileHandle, $jsonVal);
    fwrite($fileHandle, "<br />\n");
}

// no errors
if (empty($errors)) {
    return $jsonVal;
// some errors
} else {
    $msg = '';
    foreach($errors as $e) {
        $msg .= "$e<br>";
    }
    return $msg;
}

broj1:
Your code is helpfull. Tell me what this line means:
I think it means if there is a field called "email" in $tempArray and $tempArray[email] is not empty, then log an error. Is this correct?

if (isset($tempArray["email"]) && !empty($tempArray["email"])) {
    $errors[] = 'Email field is empty';
}

Yes, this is just an example when email would be required. What are the errors you want to check for, is something you have to decide.

Edit: I just realized that my example code contains errors, sory. It should be:

if (!isset($tempArray["email"]) || empty($tempArray["email"])) {
    $errors[] = 'Email field is empty';
}

Basically whenever there is an error, you add a string to the $errors array. Then you check if there are any error strings in the array, something went wrong and you display all the errors that occured. You can decide that you want to handle errors differently.

broj1:
Thanks for the tip. I have implemented server side testing for all the incoming parameters in the PHP now. I just have to figure out how to access the return data on the javaScript side.

Depending on what you want you might use the third parameter of the load method - a function that fires on complete.

Edit: I have just noticed that there is a displayRet(inc) function which is used for displaying data. It is in this function that you should check if the data represents an error or valid data and display information accordingly.

broj1:
Attached is a revision with your suggestions and the readings I learned today from the web. See if you know why I can't get the success funtion to and the error function to display their contents to the div the-return.

This is my version of ajax function. See comments in the code.

$("document").ready(function () {
    $(function () {
        //setup ajax error handling
        $.ajaxSetup({
            error: function (x, status, error) {
                if (x.status == 403) {
                    alert("Sorry, your session has expired. Please login again to continue");
                    window.location.href = "/Account/Login";
                }
                else {
                    alert("An error occurred: " + status + "nError: " + error);
                }
            }
        });
    });


    $("#Jform").submit(function (e) {
        // so the form does not get submitted
        e.preventDefault();
        data = $('#Jform').serialize();
        $.ajax({
            type: "POST",
            // I think this is correct datatype
            dataType: "json",
            url: "processJson.php",
            data: data,
            success: function (msg) {
                // I don't thimk you need to parse, since msg is already a JSON
                displayRet(msg);
            },
            error: function (msg) {
                console.log(msg);
                $("#the-return").html("ERROR: " + msg);
            }
        });
    });
});

Also, you are appending to the jsonStorage.txt so it keeps growing and getting big. Is that what you want?

broj1:
Your version works with 1 small exception, for some reason the temperature variable does not print out in the HTML. I have a meeting now so will look into it later. Also I do want to append in jsonStorage.txt. I want the total in the file and the current entry on the HTML. Thanks!

You have an error in the displayRet() function in the line that displays temperature (missing the > in the br tag):

"<br /Temperature: " + inc["temperature"] +

It should be

"<br />Temperature: " + inc["temperature"] +

broj1:
Thanks for your assistance. All is well.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.