如何使用AJAX将数据发送到我的PHP脚本?

时间:2022-03-21 20:25:39

I'm new to PHP and Javascript/Ajax so please bear with me.

我是PHP和Javascript / Ajax的新手,所以请耐心等待。

All I need to do is get a variable from Ajax and set it as a variable in php. I'm trying to do this with a super global GET but something is not right. I don't want to this by submitting the form.

我需要做的就是从Ajax获取一个变量并将其设置为php中的变量。我试图通过超级全球GET来做到这一点,但有些事情是不对的。我不想通过提交表格来做到这一点。

Here's my JS:

这是我的JS:

function myFunction(){
var hora= document.getElementById("hora").value;
$.ajax({ 
        type : 'GET',
         url : 'reservation.php',
         data : {hora: hora},
         success : function(data) {
                console.log(hora);//This is because I was curious as to
                             // what the console would say. I found
                             // that this sets the super global if I
                             // change the url to something else that
                             // doesn't exist. Console would say
                             // -GET http://localhost/bus/(somepage).php?hora=4
                             // 404 (Not Found)-  
                alert(hora);
               }
})
}

Here's my PHP:

这是我的PHP:

Hora:
 <select name="hora" id="hora" onchange="myFunction()">
     <?php
         $query = "SELECT * FROM vans";
         $horas_result = mysql_query($query);
         while ($horas = mysql_fetch_array($horas_result)) {
        echo "<option value=\"{$horas["van_id"]}\">{$horas["time"]}</option>";
         }
    ?>
 </select>&nbsp;
 Asientos Disponibles:
    <?php echo $_GET["hora"]; ?>
        //Right now I only want to echo this variable..

As you can see, right now I only want to echo this variable, later on I'll be using this to write a query.

正如你所看到的,现在我只想回显这个变量,稍后我会用它来编写一个查询。

2 个解决方案

#1


0  

Look at the code i post, ajax is used to post/get data without need to refresh the page but if you just want to post the data and give the result in other page use a form instead.

查看我发布的代码,ajax用于发布/获取数据而无需刷新页面,但如果您只想发布数据并在其他页面中给出结果,请使用表单。

<?php

    if (isset($_GET["hora"]))
    {
        echo $_GET["hora"];

        exit;
    }
?>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Page title</title>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

</head>

<body>

<script type="text/javascript">

        $(document).ready(function()
            {
                $("#hora").change(function ()
                    {
                        $.ajax(
                            { 
                                type : 'GET',
                                url : '',
                                data : $('select[name=\'hora\']'),
                                success : function(data)
                                    {
                                        $('#ajax_result').html('Asientos Disponibles:  ' + data);
                                    },
                                error: function(xhr, ajaxOptions, thrownError)
                                    {
                                        alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
                                    }
                            }
                        )
                    }
                )

            }
        )

</script>

<select name="hora" id="hora">
     <?php
         $query = "SELECT * FROM vans";
         $horas_result = mysql_query($query);
         while ($horas = mysql_fetch_array($horas_result)) {
        echo "<option value=\"{$horas["van_id"]}\">{$horas["time"]}</option>";
         }
    ?>
 </select>&nbsp;
    <div id="ajax_result">
    </div>
</body>
</html>

#2


0  

For example, the following script

例如,以下脚本

$.ajax({
            type: "POST",
            url: "test.php",
            data: {value:1}
        }).done(function(msg) {
                    // msg contains whatever value test.php echoes. Whether it is code, or just raw data. 
            if(msg=="Success") { 
              alert("hello world"); 
              } else {
                alert("Hello Hell")
            }
        });

Will set the variable $_POST['value'] to 1

将变量$ _POST ['value']设置为1

and my test.php looks like:

我的test.php看起来像:

<?php
 if($_POST['value'] == "1") {
     echo "Success";
 } else {
     echo "Failure";
 }
?>

If you run that example, the webpage will show you an alert box with the text "Hello World" If you change the value to any other number, it will show you an alert with the text "Hello Hell"

如果您运行该示例,网页将显示一个警告框,其中包含文本“Hello World”如果您将值更改为任何其他数字,它将显示带有“Hello Hell”文本的警报

Hope that answers your question.

希望这能回答你的问题。

#1


0  

Look at the code i post, ajax is used to post/get data without need to refresh the page but if you just want to post the data and give the result in other page use a form instead.

查看我发布的代码,ajax用于发布/获取数据而无需刷新页面,但如果您只想发布数据并在其他页面中给出结果,请使用表单。

<?php

    if (isset($_GET["hora"]))
    {
        echo $_GET["hora"];

        exit;
    }
?>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Page title</title>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

</head>

<body>

<script type="text/javascript">

        $(document).ready(function()
            {
                $("#hora").change(function ()
                    {
                        $.ajax(
                            { 
                                type : 'GET',
                                url : '',
                                data : $('select[name=\'hora\']'),
                                success : function(data)
                                    {
                                        $('#ajax_result').html('Asientos Disponibles:  ' + data);
                                    },
                                error: function(xhr, ajaxOptions, thrownError)
                                    {
                                        alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
                                    }
                            }
                        )
                    }
                )

            }
        )

</script>

<select name="hora" id="hora">
     <?php
         $query = "SELECT * FROM vans";
         $horas_result = mysql_query($query);
         while ($horas = mysql_fetch_array($horas_result)) {
        echo "<option value=\"{$horas["van_id"]}\">{$horas["time"]}</option>";
         }
    ?>
 </select>&nbsp;
    <div id="ajax_result">
    </div>
</body>
</html>

#2


0  

For example, the following script

例如,以下脚本

$.ajax({
            type: "POST",
            url: "test.php",
            data: {value:1}
        }).done(function(msg) {
                    // msg contains whatever value test.php echoes. Whether it is code, or just raw data. 
            if(msg=="Success") { 
              alert("hello world"); 
              } else {
                alert("Hello Hell")
            }
        });

Will set the variable $_POST['value'] to 1

将变量$ _POST ['value']设置为1

and my test.php looks like:

我的test.php看起来像:

<?php
 if($_POST['value'] == "1") {
     echo "Success";
 } else {
     echo "Failure";
 }
?>

If you run that example, the webpage will show you an alert box with the text "Hello World" If you change the value to any other number, it will show you an alert with the text "Hello Hell"

如果您运行该示例,网页将显示一个警告框,其中包含文本“Hello World”如果您将值更改为任何其他数字,它将显示带有“Hello Hell”文本的警报

Hope that answers your question.

希望这能回答你的问题。