简体   繁体   中英

How can I pass a value from jQuery to PHP

I have a simple button when I click it I wish to pass a value from jQuery and send it to a PHP file so I can execute it. So when the button is clicked the onclick event is triggered, it sends the number "1" to the jQuery code and in turn jQuery should send "1" to the PHP function displayRecords, and "1" should be echoed :). If you can help, it would be greatly appreciated.

HTML

<input type="button" value = "Click Me!" 
    id = "btn" nam = "btn" onClick="displayRecord(1)">

jQuery

<script>
    function displayRecord(num) {
        $.ajax({
            type: 'post',
            url: "display.php",
            data: { num: num }
        });
    };
</script>

PHP

<?php
    function displayRecord($num) {
        echo $num;
    }
?>

You can't just call variables like that

function displayRecord($num){

    echo $num;

    }

That's just a function delcaration. You're not calling it with anything. Add this to call your function with the POST data

displayRecord($_POST['num']);

You need a form and input with value..

<form id="btn">
    <input type="hidden" value = "Click Me!" 
       nam = "btn"> 
<button type="submit">Submit this form</button>  
</form>

To echo from php file do it this way:

Specify JSON header & Create array(jSon only reads arrays);

header("content-type:application/json");

if(!empty($_POST['num'])){

$result = array(array("num" => $num));

    echo json_encode($result);  }

in Ajax..

 var form = $("#btn");
    form .submit(function (ev) {
        $.ajax({
        type: 'POST',
        dataType: 'json',
        url: "display.php",
        data: { num: num },
        success: function( json ) {
            $.each(json, function(i, item) {
    alert('+item.num+');
                   })
              },

      error: function(xhr, desc, err) {
        console.log(xhr + "\n" + err);} 
              });

        ev.preventDefault();
        });

call this page: index.php

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script>
        function displayRecord(num){
            txt=num;
            $.post("demo.php",{num:txt},function(result){
                $("#displayRecord").html(result);
            });
        }
    </script>
</head>
<body>
    <input type="button" value="Click Me!" id="btn" name="btn" onClick="displayRecord(1)">
    <div id="displayRecord"></div>
</body>

and call this page: demo.php

 <?php echo $_POST['num']; ?>

First noticed that you need to put apostrophes around your input id which may cause unexpected results depending on what you're doing.

Here is the HTML needed.

<form id="form">
<input type="button" value="Click Me!" id="btn" name="btn" type="submit">
</form>

To send data from AJAX to PHP.

$(function() {
    $('#form').on('submit, function() {
        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: 'display.php',
            data: { num: num },
            success: function(message, data) {
                alert(message);
                $(data)...//ready to use
            }
        });
    });
});

To send data from PHP back to AJAX in JSON format.

<?php
    if ($_POST['num']) {
        $num = $_POST['num'];
        echo json_encode(array('message' => 'Completed!', 'data' => $num));
    }
?>

You have 2 things missing. In php you dont actually call the funtion, and in js you ignore the returned data.

To fix:

jQuery

<script>
    function displayRecord(num) {
        $.ajax({
            type: 'post',
            //dataType: 'json',  <--you are not currently sending json, so remove this
            url: "display.php",
            data: { num: num },
            //do something with the result of the ajax call
            success:function(data){
                alert(data);
            }
        });
    };
</script>

PHP

<?php
    function displayRecord($num) {
        echo $num;
    }
    //call the function, with the posted data
    displayRecord($_POST['num']);
?>

since you are already using jquery ajax, why not use some jquery bindings as well,

<input type="button" value = "Click Me!" 
    id = "sendbtn" >

<script>
$(document).ready(function(){
    var display = function (e) {
        e.preventDefault();
        var num = $("#yourtextinputidhere").val();
        $.ajax({
            type: 'post',
            dataType: 'json',
            url: "display.php",
            data: { num: num }
        });
    }
    $("#sendbtn").on('click', display); //note display is set as a function above
});
</script>

<?php //display.php
    function displayRecord($num){
        //Do what needs to be done here
    }

    displayRecord($_POST['num']);
?>

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