简体   繁体   中英

How can I send javascript values to PHP script?

this is my php code that creates a table using the results of a mysql query:

echo "<table id='table' class='selectQuery'>
while($row = mysqli_fetch_array($slctQuery)) {  
        // ; echo $row['id']; echo
            echo "<tr class='someClass' idNumber="; echo $row['id']; echo ">
                <td>";
                    echo $row['fname'];
              echo "</td>
                <td>";
                    echo $row['lname'];                 
              echo "</td>;
              </tr>";
        }
    echo "</table>";

and this part is my jquery code for changing style on click on table row:

<script>
$(document).ready(function(){
            $("#table tr").click(function(){
                $('.someClass').removeClass('selected');
                $(this).addClass('selected');

                idNum = $(this).attr('idNumber');
            });
            $("#table tr").click(function(){
                $("#DelEdtQuestion").addClass('selected1');
            });
});
</script>

and this part is for style:

<style>
tr.selected {
    background-color: brown !important;
    color: #FFF;
}
</style>

and this is my php code for button

if(@$_POST['Search']){
    ///   what should I do?
}

So, now I want have my idNum value when my search button in form was clicked.

thanks for attentions

You can use ajax. If you have a form with id="myform" and (example) input fields: firstname, lastname, username and password, the following script should send data to the php:

$(document).ready(function(){
    var datastring = $("#myform").serialize();
    $.ajax({
        type: 'POST',
        url: 'ajaxfile.php',
        data: datastring
    }).done(function(res){
        var res = $.trim(res);
        alert(res);
    });
});

The ajaxfile.php can be something like that:

<?php

$firstname = mysql_real_escape_string($_POST["firstname"]);
$lastname = mysql_real_escape_string($_POST["lastname"]);
$username = mysql_real_escape_string($_POST["username"]);
$password = mysql_real_escape_string($_POST["password"]);

//here you have the variables ready to do anything you want with them...
//for example insert them in mysql database:
$ins = "INSERT INTO users (firstname, lastname, username, password ) VALUES ( '$firstname', '$lastname', '$username', '$password' )";
if(mysql_query($ins)){echo "SUCCESS";}else{echo "FAILURE";}

?>

Another example, similar to yours, is to take the row id from your table, pass it to ajax, have ajax (for example) make a query to the database and return the results:

// your script, modified for ajax:
$(document).ready(function(){
    $("#table tr").click(function(){
        $('.someClass').removeClass('selected');
        $(this).addClass('selected');
        var idNum = $(this).attr('idNumber'); //use "var" to -initially- set the variable
        $.ajax({
            type: 'POST',
            url: 'ajaxfile.php',
            data: 'id='+idNum
        }).done(function(res){
            var res = $.trim(res);
            alert(res);
        });
    });
    $("#table tr").click(function(){
        $("#DelEdtQuestion").addClass('selected1');
    });
});

Modified ajaxfile.php to suit the above example:

<?php

$id = mysql_real_escape_string($_POST["id"]);

//query database to get results:
$result = "SELECT * FROM `users` WHERE `id` = '$id' LIMIT 1";
$row = mysql_fetch_assoc($result);

echo "Username: ".$row["username"]."Password: ".$row["password"]."Firstname: ".$row["firstname"]."Lastname: ".$row["lastname"].

?>

Since your question was rather ambigious, I put more effort to give you an idea about the basics of ajax so that you work out your own solution, rather than to suggest a potential solution -that at the end could not be what you were looking for...

And since we are talking about ajax basics, it is a good practice to secure your ajax files since they are accessible from any browser:

in the very beginning of any ajax file, right below the "?php" tag, you can add these lines below, to protect the file from being accessed by browser -but remain accessible to ajax calls:

//protect the file from un-authorized access
define('AJAX_REQUEST', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
if(!AJAX_REQUEST) {die();}

Hope that helps you and others. T.

UPDATE:

It is ALWAYS a good practice to keep your php and javascript files separately... In the above examples there are ideally 3 files involved: the main php file, the scripts file and the ajax-php file.

So -preferably after the "body" tag of your "main" php file- you should include the scripts-file (after the jquery ofcourse!). Like that:

<!-- jQuery v.1.11.3-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

<!-- include scripts file -->
<?php include("scripts.php"); ?>

(notice that for jquery I use the regular "script" tags but for the scripts file I just do a "php include").

As you see above, the javascript file has also ".php" extension (not ".js"). This is a "trick" I like to do because it gives me the ability to execute php code within the js file. Of course, all javascript code in that file is included between "script" tags.

example of a hypothetical "scripts.php":

<script>

// I create a js variable that takes value from php
var phpDate = '<?php date("Y-m-d"); ?>';
alert(phpDate); 

//or pass the contents of another php variable in your app to javascript:
var myPhpVar = '<?php echo $my_php_var; ?>';

//or put a php SESSION to a js variable:
var mySess = '<?php echo $_SESSION["my_session"]; ?>';

</script>

The above comes quite handy sometimes when you want to pass to javascript php variables that already exist in your application.

It is a very long answer (more like a tutorial!)... But now should be quite clear to you how to pass values not only from js to php but also vice versa!!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM