简体   繁体   English

将值从javascript传递给php

[英]passing values from javascript to php

HTML CODE HTML代码

<form action="phpfile.php" method="post">
    <input type="button" id="id1">
    <input type="button" id="id2">
    <input type="submit">
</form>

<div id="result"></div>

JAVASCRIPT CODE JAVASCRIPT代码

qty1=0;
qty2=0;
totalqty=0;


    $("#id1").click(function(){

        qty1=qty1+1;
        totalqty=totalqty+1;
        $("#result").html(qty1);
    });

    $("#id2").click(function(){
        qty2=qty2+1;
        totalqty=totalqty+1;
        $("#result").html(qty2);
    });

Can you give me some tips on how I can send the qty1, qty2 and totalqty to my php file, after I click the submit button. 你能给我一些关于如何在点击提交按钮后将qty1,qty2和totalqty发送到我的php文件的提示。 Before I send it to the php file, I need to check first if the button is already clicked. 在我将它发送到php文件之前,我需要先检查按钮是否已被点击。 If not, no qty will be send to the phpfile. 如果没有,则不会将任何数量发送到phpfile。 I need to send the exact number of qty based on how many times you clicked the button. 我需要根据您点击按钮的次数发送确切的数量。

The easiest solution would be to add qty as <input type="hidden" id="qty1" name="qty1" /> to your form. 最简单的解决办法是添加qty<input type="hidden" id="qty1" name="qty1" />到表单中。 They will be invisible as your variables, and will be sent to the server as form fields. 它们将作为变量隐藏,并将作为表单字段发送到服务器。 To access their values from Javascript, use $("#qty1").value() 要从Javascript访问它们的值,请使用$("#qty1").value()

You're looking for something called AJAX . 你正在寻找一种叫做AJAX的东西。

This is easy to implement using the jQuery library, but it's also available using regular JavaScript. 这很容易使用jQuery库实现,但它也可以使用常规JavaScript。

If you choose to use the jQuery implementation then your can look at the documentation . 如果您选择使用jQuery实现,那么您可以查看文档

Here's a basic example: 这是一个基本的例子:

$.ajax({
    type : 'post',
    url : 'target.php',
    dataType : 'json',
    data  : {
       'foo' : 10
   }
}).done(function()
{
    $(this).addClass("done");
});

You then use the back-end to handle the response, let's for example assume that you send an object of parameters whera one key is named foo and the value is 10, then you could fetch it like this (if the code is PHP): 然后使用后端来处理响应,例如假设您发送一个参数对象,其中一个键名为foo,值为10,那么您可以像这样获取它(如果代码是PHP):

$foo = isset($_POST['foo']) ? $_POST['foo'] : "";

Using the ternary operator 使用三元运算符

try using jquery $.ajax or $.post function: 尝试使用jquery $ .ajax$ .post函数:

qty1=0;
qty2=0;
totalqty=0;

$("#id1").click(function(){
    qty1=qty1+1;
    totalqty=totalqty+1;
    $("#result").html(qty1);

    get_values(qty1);
});

$("#id2").click(function(){
    qty2=qty2+1;
    totalqty=totalqty+1;
    $("#result").html(qty2);

    get_values(qty2);
});

function get_values(qty_val) {
    $.post(
        'get_values.php', // url of your php who will receive the values
        { post_variable_name: qty_val }, // your post variables here
        function(data) {
            // call back function
            $("#result").html(data); // see what does your get_value.php echoes via html
            console.log(data); // see it via console in inspect element
        }
    );
}

and in your php that will recieve the values, just retrieve using $_POST: 并在您的PHP中将收到值,只需使用$ _POST检索:

<?php
$qty_val = '';
if(isset($_POST['post_variable_name'])) {
   $qty_val = $_POST['post_variable_name'];
   echo $qty_val;
}
?>

HTML HTML

<form>
    <input name="id1" type="button" id="id1" />
    <input name="id2" type="button" id="id2" />
    <input type="submit" />
</form>
<div id="status"></div>

JS JS

qty1=0;
qty2=0;
totalqty=0;

$("#id1").click(function(){
    qty1=qty1+1;
    totalqty=totalqty+1;
    $("#result").html(qty1);
});

$("#id2").click(function(){
    qty2=qty2+1;
    totalqty=totalqty+1;
    $("#result").html(qty2);
});


$( "form" ).submit(function( event ) {
    // prevent the default event
    event.preventDefault();

    // check first if the totalqty. You can add more checks here
    if ( totalqty === 0 ) {

        // usually show some kind of error message here
        alert('No quantity selected!');

        // this prevents the form from submitting
        return false;
    } else {
        $.ajax({
            type: 'post',
            url: 'phpfile.php',
            dataType: 'json',
            data: {
                quantity1: qty1,
                quantity2: qty2,
                totalQuantity: totalqty
            }
        }).done(function(data) {
            console.log(data);

            alert( "success" );

            $('#status').html("Successfully saved!");
        }).fail(function() {
            console.log(data);

            alert( "error" );

            $('#status').html("Successfully saved!");
        });
    }
});

PHP PHP

$qty1 = isset($_POST['quantity1']) ? $_POST['quantity1'] : "";
$qty2 = isset($_POST['quantity2']) ? $_POST['quantity2'] : "";
$total = isset($_POST['totalQuantity']) ? $_POST['totalQuantity'] : "";

Sorry, i can't test it, but it should work 对不起,我无法测试它,但它应该工作

For more detailed you could have a look to the jQuery Learning Center - Ajax where you can find useful examples to work with ajax and forms. 有关更详细的信息,您可以查看jQuery学习中心 - Ajax ,您可以在其中找到使用ajax和表单的有用示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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