Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Form Values as JS variables in callback function

I am trying to pass php form values in a JS function using my following code --

<script type="text/javascript">
var titleV = document.getElementById("mrp-title-<?php echo $sequence ?>").value;

var commentV = document.getElementById("comment-<?php echo $sequence; ?>").value;

mrp_data_callbacks.push( function(index, data) {
data["<?php echo "htitle-" . $sequence ?>"] = titleV;
return data;
});

mrp_data_callbacks.push( function(index, data) {
data["<?php echo "comment-" . $sequence ?>"] = commentV;
return data;
});
</script>

To get something like this --

jQuery(document).ready(function() { 
mrp_data_callbacks.push( function(index, data) {
data["hello"] = "world";
return data;
});
});

I tried directly like this --

 mrp_data_callbacks.push( function(index, data) {
        data["<?php echo "htitle-" . $sequence ?>"] = "<?php echo $htitle ?>";
        return data;
    });

The problem I am having is that the values will be constantly updated and handled with scripts on other js/ajax files. So trying to echo the php values directly in the callback function didnt work and I was told else where --

mixing PHP and JavaScript wont work (server side vs. client side). If htitle is updated, the values will not be updated. E.g. if htitle is "Hello" then the callback functions will always be: mrp_data_callbacks.push( function(index, data) { data["World"] = "World"; return data; }); The callback function is supposed to populate the values of the fields on the form to submit in the AJAX request. So you should use JavaScript not PHP to get the updated values from the HTML form.

Indeed, if you have an HTML form that the user fills in, then those modified values are not known by PHP until the form is submitted. PHP is only doing something when is passed to the server, not while the user is scrolling through the web page, filling in text. So in that case you should use javascript.

So how can I make it so these values are updated and the script works?

EDIT

The form is generated by a plugin and the related code can be seen below--- http://pastebin.com/RrjJqaFB -- The template for the form

http://pastebin.com/tp8Gxv8B -- Frontend.js - This is where the ajax is done and the callback function is defined.

like image 797
730wavy Avatar asked Dec 26 '15 21:12

730wavy


1 Answers

That'd be done with AJAX or WebSocket, with jQuery you can have something like:

JS:

$('#username').on('change input', function(){
  var username = $(this).val();
  // Here you send - post - data to the .php file which deals with as 
  // a regular post request, some thing could be said for $.get as GET request
  $.post('check_username.php', { username : username}, function(data){
    if(data == 1){
      // if data was 1, means the php found that username already in
      // the database and echoed 1 back
      $(this).addClass('errorMsg').text('This username is already taken.');
    }
  });
});

PHP:

if(isset($_POST['username'])){
    $username = escape($_POST['username']);
    $validate = new Validation();
    $validation = $validate->checkUniq('users', 'username', $username);
    $validation = ($validation == 0) ? 0 : 1;
    echo $validation;
}

using jQuery gives you functions like $.ajax() , $.post() , $.get(), the latter two functions are shortcuts.

However, if your expecting large number of users working on same data with forms and you keep bouncing data forth and back to all users that'll put lots of load on the server.


On the other hand web WebSocket works by opening a connection channel between the server and users, this connection channel stays opened until the user disconnected, somehow this doesn't make much load on the server, I haven't work with WebSocket yet but I have read couple articles and watched few videos on YouTube which most of them was about creating real-time chat apps or multi user web games.

  • WebSockets Examples

For PHP there's this PHP-Websockets, and this Ratchet library, also this WebSockets the UNIX way which is not for PHP only.



UPDATE 1: Upon a comment from the OP, let's suppose we have a similar - but simpler - situation, having the following files all on same file level:

  • data.txt: - is just used instead of database for demonstration

    title 0 , comment number 0
    title 1 , comment number 1
    title 2 , comment number 2
    
  • JS

    $(document).ready(function() { 
    
        // for initializing we call fetchData function as soon as DOM is ready
        // then re-call it every 10,000 milliseconds to update the input values with new
        // fetched data , that could have been changed by other users.
        fetchData();
        setInterval(fetchData, 10000);
    
    
        // on any button click we get the numeric index value, using this value
        // to pick correspnding title and comment values, then send a POST
        // request to foo.php and on response data we call updateHTML
        $('.buttons').on('click', function(){
            indexV = $(this).attr('id').replace('btn-', '');
            titleV = $('#mrp-title-' + indexV).val();
            commentV = $('#comment-' + indexV).val();
            $.post('foo.php', { index : indexV, title:titleV, comment: commentV}, function(data){
               if(data){
                    updateHTML(data);
                }
            });
        });
    
    
        // Making a get request to fetch fresh data
        function fetchData(){
            $.get('foo.php', function(data){
                updateHTML(data);       
            });
        }
    
        // Update title and comment inputs values
        function updateHTML(data){
            var titleID, titleV, commentID, commentV, indexV, content;
            // using jQuery parseJSON function to convert the JSON response
            // to and array, then loop through this array to update inputs
            // with new title and comment values.
            content = $.parseJSON(data); 
            for(var i = 0; i < content.length; i++){
                titleID = '#mrp-title-' + i;
                titleV = content[i].title,
                commentID = '#comment-' + i;
                commentV = content[i].comment;
                $(titleID).val(titleV);
                $(commentID).val(commentV);
            }
        }
    });
    
  • HTML:

    <!-- this is usually generated with PHP --> 
    <div id="output">
        <label for="mrp-title-0">Title #0:</label>
        <input type="text" id="mrp-title-0" class="titles" value="">
        <label for="comment-0">Comment #0:</label>
        <input type="text" id="comment-0" class="comments" value="">
        <button id="btn-0" class="buttons">Save Changes</button>
        <hr>
        <label for="mrp-title-1">Title #1:</label>
        <input type="text" id="mrp-title-1" class="titles" value="">
        <label for="comment-1">Comment #1:</label>
        <input type="text" id="comment-1" class="comments" value="">
        <button id="btn-1" class="buttons">Save Changes</button>
        <hr>
        <label for="mrp-title-2">Title #2:</label>
        <input type="text" id="mrp-title-2" class="titles" value="">
        <label for="comment-2">Comment #2:</label>
        <input type="text" id="comment-2" class="comments" value="">
        <button id="btn-2" class="buttons">Save Changes</button>
    </div>
    
  • foo.php:

    <?php
    
    if(isset($_POST['index']) && isset($_POST['title']) && isset($_POST['comment'])){
        // if there's a POST request, we retrieve the data.txt content as an array
        // depending on the POST index value we change the corresponding item in 
        // the array to update title and comment values, then write the array as
        // new content of the data.txt with the new array $foo. 
        $index = $_POST['index'];
        $title = $_POST['title'];
        $comment = $_POST['comment'];
        //Do validation and sanitizing here
        $temp = '';
        $foo = getContent();
        $foo[$index]['title'] = $title;
        $foo[$index]['comment'] = $comment;
        for($i = 0; $i < count($foo); $i++) {
            $temp .= $foo[$i]['title'] . ' , ' . $foo[$i]['comment'] . "\n";
        }
        $temp = trim($temp);
        file_put_contents('data.txt', $temp);
    }else{
        // if no POST request, no changes happened and our array is same as file content
        $foo = getContent();
    }
    
    // we encode $foo as JSON and echo it back to javascript
    $jsonFoo = json_encode($foo);
    echo $jsonFoo;
    
    // getting data.txt content and return an array of the content
    function getContent(){
        $bar = array();
        $data = file_get_contents('data.txt');
        $rows = explode("\n", $data);
        foreach ($rows as $row) {
            $cols = explode(",", $row);
            $title = trim($cols[0]);
            $comment = trim($cols[1]);
            $bar[] = array('title' => $title, 'comment' => $comment);
        }   
        return $bar;
    }
    

for above files as soon soon DOM is ready, we call fetchData() for the first time to populate input values with data from databas -data.txt. in this example instead of database for simplicity-, then we call fetchData() every 10 seconds using javascript setInterval(), so that if some input values have been changed by userX, all other users will see the result updated on their screen after 10 seconds, presuming 10 seconds is enough, it could be less than 10 seconds but users wouldn't have time to change one input value even, also the less time period you put the more load you put on server and vice versa.

If you create same file structure with same code as above on test server -localhost for example- and open the webpage that has all input fields and buttons in Chrome -as userX- and Firefox -as userY- and IE -as userZ- for example, change the value of one of the input fields and hit the corresponding "Save Changes"'s button in let's say "Chrome", you'll see the same field's value has been updated in "Firefox" and "IE"after 10 seconds automatically.

So you can make your PHP echo the let's say $result array AFTER json_encode it just like in my example, and in javascript, first use jQuery $.parseJSON() function to convert the JSON object into an array loop through the result and push each row values to the mrp_data_callbacks, and that's it!

like image 171
Mi-Creativity Avatar answered Nov 11 '22 00:11

Mi-Creativity