admin管理员组

文章数量:1289423

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 mentV = document.getElementById("ment-<?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 "ment-" . $sequence ?>"] = mentV;
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--- -- The template for the form

-- Frontend.js - This is where the ajax is done and the callback function is defined.

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 mentV = document.getElementById("ment-<?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 "ment-" . $sequence ?>"] = mentV;
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./RrjJqaFB -- The template for the form

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

Share Improve this question edited Jan 8, 2016 at 4:53 730wavy asked Dec 26, 2015 at 21:10 730wavy730wavy 7041 gold badge20 silver badges65 bronze badges 1
  • i guess this is only ONE reason why everybody exposes their server-side with a RESTful API endpoints... something like coreymaynard./blog/creating-a-restful-api-with-php – ymz Commented Jan 19, 2016 at 21:05
Add a ment  | 

4 Answers 4

Reset to default 8

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 ment 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 , ment number 0
    title 1 , ment number 1
    title 2 , ment 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 ment 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();
            mentV = $('#ment-' + indexV).val();
            $.post('foo.php', { index : indexV, title:titleV, ment: mentV}, 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 ment inputs values
        function updateHTML(data){
            var titleID, titleV, mentID, mentV, 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 ment values.
            content = $.parseJSON(data); 
            for(var i = 0; i < content.length; i++){
                titleID = '#mrp-title-' + i;
                titleV = content[i].title,
                mentID = '#ment-' + i;
                mentV = content[i].ment;
                $(titleID).val(titleV);
                $(mentID).val(mentV);
            }
        }
    });
    
  • 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="ment-0">Comment #0:</label>
        <input type="text" id="ment-0" class="ments" 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="ment-1">Comment #1:</label>
        <input type="text" id="ment-1" class="ments" 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="ment-2">Comment #2:</label>
        <input type="text" id="ment-2" class="ments" value="">
        <button id="btn-2" class="buttons">Save Changes</button>
    </div>
    
  • foo.php:

    <?php
    
    if(isset($_POST['index']) && isset($_POST['title']) && isset($_POST['ment'])){
        // 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 ment values, then write the array as
        // new content of the data.txt with the new array $foo. 
        $index = $_POST['index'];
        $title = $_POST['title'];
        $ment = $_POST['ment'];
        //Do validation and sanitizing here
        $temp = '';
        $foo = getContent();
        $foo[$index]['title'] = $title;
        $foo[$index]['ment'] = $ment;
        for($i = 0; $i < count($foo); $i++) {
            $temp .= $foo[$i]['title'] . ' , ' . $foo[$i]['ment'] . "\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]);
            $ment = trim($cols[1]);
            $bar[] = array('title' => $title, 'ment' => $ment);
        }   
        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!

As you were told correctly, you are getting the value from the input field only once (it will set the value for titleV and mentV when first loading the page). So, if anything is changed in the form by user action, it will not be there. You need to move the part of code which gets the titleV and mentV inside the callback functions. So it will get always the current value from the input when the function is called on the fly. Something like this (a bit improved) -

<script type="text/javascript">
var sequence = "<?php echo $sequence ?>";
mrp_data_callbacks.push( function(index, data) {
    var titleV = document.getElementById("mrp-title-"+sequence).value;
    data["htitle-"+ sequence] = titleV;
return data;
});

mrp_data_callbacks.push( function(index, data) {
    var mentV = document.getElementById("ment-"+sequence).value;
    data["ment-"+sequence] = mentV;
return data;
});
</script>

Have you tried to generate the whole JS-Code with PHP? This could work:

<?php
$js  = "<script type='text/javascript'>";
$js += "var sequence = " . $sequence . ";";
$js += "mrp_data_callbacks.push(function(index, data) {";
$js += "    data[" . $key . "] = " . $value . ";";
$js += "    return data;";
$js += "});";
$js += "</script>";
echo $js;
?>

A bit confusing but all I believe you need to do is get the values using JavaScript at the time the form is being posted. TaReQ MahMooD is correct.

So this:

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

Should look like this:

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

Daniel

本文标签: javascriptPHP Form Values as JS variables in callback functionStack Overflow