Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SubmitFormData as Json (Update w/o page refresh

I am working on my submit form w/o a page refresh. Below is my code which is working perfectly. How ever it would be easier if i can send data to my back.php file in Json format so i dont need to declare al variables in the script section. Is there a way to send the data from the form in json and decode it in my back.php file ? It would make my life much easier. Thank you!

front.php

<script>
    function SubmitFormData() {
        var vorname = $("#vorname").val();
        var nachname = $("#nachname").val();
        $.post("back.php", {
                vorname: vorname,
                nachname: nachname
            },
            function(data) {
                $('#results').html(data);
                $('#myForm')[0].reset();
            });
    }
</script>

<form id="myForm" method="post">
    Name: <input name="vorname" id="vorname" type="text" /><br/>
    Name: <input name="nachname" id="nachname" type="text" /><br/>
    <input type="button" id="submitFormData" onclick="SubmitFormData();" value="Submit" />
</form>

<div id="results">
    <!-- All data will display here  -->
</div>

back.php

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

// Here some Json decode?

// get values form input text and number
$vorname = $_POST['vorname'];
$nachname = $_POST['nachname'];

// Update SQL table with prepared statement
$query =   "UPDATE users  
                SET vorname = :vorname, nachname = :nachname  
                WHERE id = :user_id";
$pdoResult = $pdo->prepare($query);
$pdoExec = $pdoResult->execute(array(":vorname" => $vorname, ":nachname" => $nachname, ':user_id' => 2));
if ($pdoExec) {
    $success_msg = "Erfolgreich!";
} else {
}

>Solution :

this should work for you:

with JQuery you could use $("#idOfYourForm").serialize() to the form;

The .serialize() method creates a text string in standard URL-encoded notation.

So in your script, you will do something like:

function SubmitFormData() {

   //in your case your form id its #myForm
   var formValues = $("#myForm").serialize();
   $.post("back.php", formValues,
        function(data) {
             $('#results').html(data);
             $('#myForm')[0].reset();
        }
   );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading