简体   繁体   English

如何在不使用ajax的情况下将数据从一个php文件发布到另一个php文件以将数据添加到数据库

[英]How to post data from a php file to another php file to add the data to database without using ajax

I have a php file (todo.php & todo.js) which collects some data from user and uses ajax to post the collected data to another php file (add.php) to be added to database . 我有一个php文件(todo.php和todo.js),该文件从用户收集一些数据,并使用ajax将收集的数据发布到另一个php文件(add.php)中,以添加到数据库中。 My issue is that I don't want to use ajax to post the data to the second php file (add.php). 我的问题是我不想使用ajax将数据发布到第二个php文件(add.php)。 How do I change this. 我该如何更改。 I have extracted the codes and shown below 我已提取代码,如下所示

//todo.js is called from todo.php to validate new todoEntry //从todo.php调用todo.js以验证新的todoEntry

function addToDo(){
    var descField = document.getElementById('nDesc');
    var percField = document.getElementById('nPerc');

    if( !validateField(descField) ){
        alert("Description " + errorMessage);
        return;
    }
    if( !validatePercentField(percField) ){
        alert("Percentage " + errorMessage);
        return;
    }

    //use ajax to post new entries to add.php which will add them
    ajaxCall(encodeURI('add.php?description=' + descField.value  
           + '&percentage=' + percField.value), function(response){
        if( response.status == 200 ){
            if( response.responseText.toString().indexOf
        ("success") != -1 ){
                //clear values
                descField.value = "";
                percField.value = "";

                //refresh table
                fetchToDo();
            }
            else
                alert(response.responseText);
        }
    });
    }

     From add.php:
    <?php
    session_start();

    if( !isset($_SESSION['username']) ){
        die("Your Session has expired. Please re-login to continue");
    }

    //get required data
    $description = trim(isset($_GET['description']) ? urldecode($_GET   
        ['description']) : "");
    $percentage = trim(isset($_GET['percentage']) ? urldecode($_GET
        ['percentage']) : "");

    //validate data
    if( empty($description) || empty($percentage) ){
        die("All fields are required!");
    }

    //connect to database
    include('connect.php');

    //insert data
    $stmt = $mysqli->prepare("INSERT INTO todo_entry VALUES (NULL, ?, NOW 
        (), NOW(), ?, ?)");
    $stmt->bind_param("ssi", $_SESSION['username'], $description,
         $percentage);
    $stmt->execute();

    if( $stmt->affected_rows > 0 ){
        $stmt->close();
        echo "success";
    }
    else{
        echo "An Error Occured: " . $stmt->error;
        $stmt->close();
    }

    //close database
    $mysqli->close();
    ?>

cURL is to PHP as AJAX is to JS. cURL指向PHP,而AJAX指向JS。 If you want to call one script from another directly from PHP without requiring the broswer to make additional requests to the server, you can use cURL. 如果要直接从PHP调用另一个脚本中的一个脚本,而无需浏览器向服务器发出其他请求,则可以使用cURL。 Here's a simple function. 这是一个简单的功能。

/*
 * Makes an HTTP request via GET or POST, and can download a file
 * @returns - Returns the response of the request
 * @param $url - The URL to request, including any GET parameters
 * @param $params - An array of POST values to send
 * @param $filename - If provided, the response will be saved to the 
 *    specified filename
 */
function request($url, $params = array(), $filename = "") {
    $ch = curl_init();
    $curlOpts = array(
        CURLOPT_URL => $url,
        // Set Useragent
        CURLOPT_USERAGENT => 
            'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:29.0) 
                    Gecko/20100101 Firefox/29.0',
        // Don't validate SSL 
        // This is to prevent possible errors with self-signed certs
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true
    );
    if(!empty($filename)){
        // If $filename exists, save content to file
        $file2 = fopen($filename,'w+') 
            or die("Error[".__FILE__.":".__LINE__."] 
                    Could not open file: $filename");
        $curlOpts[CURLOPT_FILE] = $file2;
    }
    if (!empty($params)) {
        // If POST values are given, send that shit too
        $curlOpts[CURLOPT_POST] = true;
        $curlOpts[CURLOPT_POSTFIELDS] = $params;
    }
    curl_setopt_array($ch, $curlOpts);
    $answer = curl_exec($ch);
    // If there was an error, show it
    if (curl_error($ch)) die(curl_error($ch));
    if(!empty($filename)) fclose($file2);
    curl_close($ch);
    return $answer;
}

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

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