0

I have a database field that is long test that's a whole users page. I want to allow the user to edit parts of their page. It is not possible to search the long string of text and just update certain parts so I want to have ID's in the code and do a dom getElementbyId and change the inner html in the correct spots and then insert the new code into db. However this works when I'm echoing to the page but not inserting back in to database. If this is confusing see what I mean below

This works, when I echo the $var it says hello guy:

<?php 

$newVar = "hello guy";
$var = "<p id='hello world'></p>";

echo $var;
?>
<script>
document.getElementById("demo").innerHTML = "<?php echo $newVar; ?>";
</script>

But when inserted into database it is hello world, not hello guy:

<?php 

$newVar = "hello guy";
$var = "<p id='hello world'></p>";

$stmt = $conn->prepare("INSERT INTO temp429 (post_content) VALUES (?)");
$stmt->bind_param("s", $var);


$stmt->execute();
?>
<script>
document.getElementById("demo").innerHTML = "<?php echo $newVar; ?>";
</script>

I'm expecting hello guy to be inserted into the database like it shows when echoed but does not do this. Is there any solution around this?

12
  • Just to make sure I'm understanding, you're binding $var in your bind_param call, but expecting it to be the value from $newVar? Apr 29, 2019 at 21:18
  • Well yea I know the answer I'm going to get it well javascript is client side and php is serverside and I get that but I'm just curious if anyone knows a way around this. Yes I want "hello guy" which is what the javascript changed to be inserted in db not origional hello world
    – Dylano236
    Apr 29, 2019 at 21:19
  • I know it seems like just put $newVar in the bind_param but the $var variable is actually going to be a ton of text that cant be changed. I just want to changed certain elements of $var. This is just a one line example.
    – Dylano236
    Apr 29, 2019 at 21:23
  • Is $var more like a template? Like, would it be accurate to say $var = 'Good afternoon <first name here>, your current balance is <balance>';, and you'd want to be able to automatically substitute data into <first name here> and <balance>? Apr 29, 2019 at 21:26
  • I think AJAX is the solution you're looking for, no? Apr 29, 2019 at 21:29

2 Answers 2

3

From your comments, it sounds like you understand why your code doesn't work, but I'm going to address that anyway. PHP has no knowledge of what happens after its output is sent to the client. It can't see anything that happens to the DOM. That line that changes the innerHTML to "hello guy" executes on the client and doesn't impact how the PHP script runs. Javascript can see the DOM, but it needs to pass along that information to some PHP script since PHP is in charge of interfacing with the database.

The solution you're likely looking for is AJAX. In order for PHP to know what happens on the client side, you're going to need to push that information back. You could simply use a html form and post the edit to a PHP script, but it sounds to me like you don't want the user leaving/reloading the page. Set up some sort of event handler to wait for the user to change a field or whatever the element in question is. Then, make a request through AJAX that pushes the edit along using either POST or GET. Then your PHP script can insert/update the record in your database. Here's an MDN article about starting with AJAX. Additionally, here's a bit of Javascript to give you an idea of what your solution might look like:

var fields = document.getElementsByClassName('updatable');

function send(event){
    if(event.type === 'blur' || event.keyCode === 13){
    xhr = new XMLHttpRequest();

    xhr.open('POST', 'path/to/php/script.php');
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onload = function() {
        if (xhr.status === 200) {
            alert('data pushed to server');
        }
        else if (xhr.status !== 200) {
            alert('Request failed.  Returned status of ' + xhr.status);
        }
    };
    xhr.send(encodeURI('field=' + event.target.id + '&value=' + event.target.value));
    }
}

for(var i = 0; i < fields.length; i++){
    fields[i].onkeypress = send;
    fields[i].onblur = send;
}

This script assumes all fields that you want to push the values to via AJAX have the updatable class and the db column that it corresponds to is the id. Then your PHP script should be able to get the data from $_POST. This should be enough for a starting point, at least.

7
  • cool I appreciate the help! Yea I understand the problem is client vs server but I guess I'm just trying to get an Idea how to approach this. I think the bit problem is that I need to change certain elements of a long text field (that is an html page) but keep other elements as they are. is Ajax the answer for this? I'm working on it now so will soon find out
    – Dylano236
    Apr 30, 2019 at 14:36
  • I had a feeling you understood the difference between client and server, but I figured it be best to go over it anyway in case someone stumbles upon this question later. It's hard to say without seeing at least a mockup of what you're going for, but I think maybe a combination of AJAX and contenteditable is what you want. Here's a little demo of what that could look like. Apr 30, 2019 at 14:58
  • wow that's cool. Updatable class. I'm going to look into this. Yea the problem is super confusing because of how the wordpress database is set up but you were really helpful and I'll give you the answer. I'll figure this out eventually but yes I think the answer lies in ajax and possibly now this updateable class. Thanks!
    – Dylano236
    Apr 30, 2019 at 15:03
  • One more question. Any Idea why an ajax post varible like this var = "<php echo "<p>Hello world</p>"; will work but not var = "<p id='demo'>Hello world</p>"; I'm trying to do an ajax post to another page with this varible and it works with out the id in the code but not if id element is there?
    – Dylano236
    Apr 30, 2019 at 15:06
  • it's the contenteditable="true" that is making it editable. The updatable class is just for styling and for getting all the fields with javascript. Not sure what your problem is. How are you trying to post it? Apr 30, 2019 at 15:10
1

The best way to do this is going to be an ajax/xhr request.

Here is an example where I am having a user enter an id number and upload an excel file.

<script type="text/javascript">

document.addEventListener("DOMContentLoaded", function () {


    $("#simplePricingReportUpdateForm").submit(function (e) {

        e.preventDefault();
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': '{!!csrf_token()!!}'
            }
        });

        var form = $('#simplePricingReportUpdateForm');
        var formData = new FormData(form[0]);
        formData.append("customerId", $('#customerId').val());

        $.ajax({
            method: 'POST',
            enctype: 'multipart/form-data',
            processData: false,
            contentType: false,
            cache: false,
            url: "/simplePricingReport/postAjax/",
            data: formData,
            xhrFields: {
                responseType: "blob"
            },
            "success": function (response) {
                var file = document.getElementById("ReportToUpdate");
                var filename = file.files[0].name;
                var a = document.createElement("a");
                var url = window.URL.createObjectURL(response);
                a.href = url;
                a.download = filename;
                a.click();
                window.URL.revokeObjectURL(url);
            }

        });
    });
});

After that javascript you will need to configure your system (whether it be a framework or homegrown) to accept this request at the 'url' you specify.

In laravel I do this in the routes

Route::post('simplePricingReport/postAjax','simplePricingReportController@postAjax');

of course from there you setup your controller. If you are doing something very simple like saving a variable to a db field it 'might' be acceptable to just write the save in the controller. Doing things properly however you would want to use you controller to call a model file which would then have a command to save the variable in the database......and welcome to mvc land.

4
  • Cool I have to go at the moment but when I log back on I'll work on this and for sure give you the answer if I'm able to figure it out. Thanks!
    – Dylano236
    Apr 29, 2019 at 21:38
  • So when I pass the ajax request to the model page to do the insert it will be the variable changed by javascript? I'm going to try this now. This answer you posted is so different to my problem it's a bit confusing but I think I understand what you mean and will try this now.
    – Dylano236
    Apr 30, 2019 at 13:57
  • sorry this was just the most convienant example i had on hand apologies if its overly complicated. But the gist of it is you configure a controller to recieve the data from your javascript, pass that data from the controller to a model and then save the variable to the database in your model. If you succedd return true else return false; Apr 30, 2019 at 15:14
  • No problem! I appreciate the help. I decided to take a different approach that's a bit more upfront work but will be better later. It's not so much of an ajax problem and more of how wordpress db is structured.
    – Dylano236
    Apr 30, 2019 at 15:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.