Home > database >  SubmitFormData as Json (Update w/o page refresh
SubmitFormData as Json (Update w/o page refresh

Time:05-10

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

// 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 {
}

CodePudding user response:

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();
        }
   );
}
  • Related