dongping6974 2017-04-12 12:51
浏览 70
已采纳

将带有ajax和jQuery的HTML表单发送到PHP

I'm trying to make first steps with JavaScript using the jQuery-library and Ajax. I want to read a HTML-form and recieve the users input in a PHP file. The following is a JavaScript function to sends the form via Ajax to the webserver:

function get_post( ) {

    $.ajax({
        type : "post",
        url : "ajax.php",
        data : $("form").serialize(),
        cache : false,
        success: function( data ) {
            console.log( data );

        }
    });

};

In the console.log the right input data are shown and also with the PHP-debug-output, which is programmed in ajax.php. console.log(data) gives:

Parameter: temperature
Sensorknoten: Node1
Start: 2017-04-20 14:15
End: 2017-04-06 06:30

which is obviously correct.

Echoing the PHP-variables in the Browser gives:

Parameter: FIELD EMPTY Sensorknoten: FIELD EMPTY Start: FIELD EMPTY End: FIELD EMPTY

ajax.php calls a class named UsersInput, which should retrieves the userinput with the gloabal $_POST. The different $_POST-methods in UserInput are similair to this

public function getNodes() {
    $location = isset($_POST['location'])?$_POST['location']:"FIELD EMPTY";
    return $location;
}

ajax.php:

<?php
require_once 'includes/autoload.php';


/*
 * get users input from HTML-Form 
 * @param object: $userIn
 */

$userIn = new UserInput();
$param = $userIn->getParams();
$node = $userIn->getNodes();
$start = $userIn->getStartdate();
$end = $userIn->getEnddate();
//debug output
echo "Parameter: $param";
echo"<br />";
echo "Sensorknoten: $node";
echo"<br />";
echo "Start: $start";
echo"<br />";
echo "End: $end";
echo"<br />";   
?>

This is the HTML-form:

<form>
<input type="hidden" name="nodeformsend" value="true">
<!-- Page Heading/Breadcrumbs -->
<div class="row">
    <div class="col-lg-12">
        <h1 class="page-header">Welcome!
            <small>Now, you are able to visualize your Data</small>
        </h1>
        <ol class="breadcrumb">
            <li><a href="index.html">Sensor Monitoring</a>
            </li>
            <li class="active">Visualize Data</li>
        </ol>
    </div>
</div>
<!-- table to select different Nodes -->
<div class="row">
    <div class="col-md-3">
        <div class="panel panel-default text-center">
            <div class="panel-heading">
                <h3 class="panel-title">Select Wireless Sensor Sodes</h3>
            </div>
            <div class="col-md">
                <select class="form-control" id="location" name="location">
                <?php for($i = 1; $i < 13; $i++) : ?>
                        <option  name="location[<?php echo $i ?>]" value="Node<?php echo $i ?>">Wireless Senssor Node <?php echo $i ?></option>
                <?php endfor; ?>
                </select>
            </div>
        </div>
    </div>
    <!-- table to select different parameters -->
    <div class="col-md-3">
        <div class="panel panel-default text-center">
            <div class="panel-heading">
                <h3 class="panel-title">Select Parameteres</h3>
            </div>
            <div class="col-md">
                <select class="form-control" id="parameter" name="parameter">
                    <option  name="parameter[0]" value="temperature">Temperature</option>
                    <option  name="parameter[1]" value="humidity">Humidity</option>
                    <option  name="parameter[2]" value="pressure">Pressure</option>
                </select>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="panel panel-default text-center">
            <div class="panel-heading">
                <h3 class="panel-title">Begin of Timestamp</h3>
            </div>
            <div class="input-group date" id="datetime-start" data-date-format="dd-mm-yyyy" >                                           
                <div class="input-group-addon">
                    <i class="glyphicon glyphicon-calendar"></i>
                </div>
                <input class="form-control" name="datetime-start" type="text" placeholder="YYYY-MM-DD HH:MM">
            </div>
        </div>
    </div>
    <!-- table to select Timestamps-->
    <div class="col-md-3">
        <div class="panel panel-default text-center">
            <div class="panel-heading">
                <h3 class="panel-title">End of Timestamp</h3>
            </div>
            <div class="input-group date" id="datetime-end" data-date-format="dd-mm-yyyy" >                                         
                <div class="input-group-addon">
                    <i class="glyphicon glyphicon-calendar"></i>
                </div>
                <input class="form-control" name="datetime-end" type="text" placeholder="YYYY-MM-DD HH:MM">
            </div>
        </div>
    </div>
</div>
<input id="submit" type="button" value="submit" onclick="get_post();">

EDIT

Yes, of course! Here it is:

<?php
//__________This class parse the usersinput UI__________

class UserInput{
    /**
     * get Nodes from UsersInput
     * $location = Node[i]
     */
    public function getNodes() {
        $location ='';
        $location = isset($_POST['location'])?$_POST['location']:"FIELD EMPTY";                                         //load the inputs of user to a variable as an array
        return $location;
    }
    /**
     * get Nodes from UI
     * $parameter = Temperature, Humidty, Pressure 
     */
    public function getParams() {
        $parameter = isset($_POST['parameter'])?$_POST['parameter']:"FIELD EMPTY";
        return $parameter;
    }
    /**
     * get Nodes from UI
     * $start = 'YYYY-mm-DD hh:ii:ss < $end
     */
    public function getStartdate() {
        $start = isset($_POST['datetime-start'])?$_POST['datetime-start']:"FIELD EMPTY";
        return $start;
    }
    /**
     * get Nodes from UI
     * $end = 'YYYY-mm-DD hh:ii:ss
     */
    public function getEnddate() {
        $end = isset($_POST['datetime-end'])?$_POST['datetime-end']:"FIELD EMPTY";
        return $end;
    }
    /**
     * get Nodes from UI
     */
}
  • 写回答

1条回答 默认 最新

  • dongnai1876 2017-04-12 13:05
    关注

    Try using the $_POST as a parameter and not a global variable. The value of the $_POST has changed. Alternatively since you have a class, you can take advantage of Object oriented programming: Now we add a construct function and when instantiating the class, we pass the $_POST as a parameter. This way we do not have to worry about accessing from $_POST

    Also if you are going to save these details to your database, please properly sanitize the input strings

    $userIn = new UserInput($_POST);
    $param = $userIn->getParams();
    $node = $userIn->getNodes();
    $start = $userIn->getStartdate();
    $end = $userIn->getEnddate();
    

    And in your class

    <?php
    //__________This class parse the usersinput UI__________
    
    class UserInput{
    
      var $variables = array();     
    
       public function __construct($posted_variables){
        try{
         if(is_array($posted_variables) && isset($posted_variables)){
            $this->variables = $posted_variables; 
          }else{
             throw new Exception('Post is empty'.var_dump($variables));
          }
        }catch(Exception $ex){
          echo $ex->getTraceAsString();
       } 
      }
    
        /**
         * get Nodes from UsersInput
         * $location = Node[i]
         */
        public function getNodes() {
            $location ='';
            $location = isset($this->variables['location'])?$this->variables['location']:"FIELD EMPTY";                                         //load the inputs of user to a variable as an array
            return $location;
        }
        /**
         * get Nodes from UI
         * $parameter = Temperature, Humidty, Pressure 
         */
        public function getParams() {
         //example:
            $parameter = isset($this->variables['parameter'])?$this->variables['parameter']:"FIELD EMPTY";
            return $parameter;
        }
        /**
         * get Nodes from UI
         * $start = 'YYYY-mm-DD hh:ii:ss < $end
         */
        public function getStartdate() {
            $start = isset($this->variables['datetime-start'])?$this->variables['datetime-start']:"FIELD EMPTY";
            return $start;
        }
        /**
         * get Nodes from UI
         * $end = 'YYYY-mm-DD hh:ii:ss
         */
        public function getEnddate() {
            $end = isset($this->variables['datetime-end'])?$this->variables['datetime-end']:"FIELD EMPTY";
            return $end;
        }
        /**
         * get Nodes from UI
         */
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化