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

时间:2021-06-19 09:46:07

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 . My issue is that I don't want to use ajax to post the data to the second php file (add.php). How do I change this. I have extracted the codes and shown below

我有一个php文件(todo.php和todo.js),它从用户收集一些数据并使用ajax将收集的数据发布到另一个要添加到数据库的php文件(add.php)。我的问题是我不想使用ajax将数据发布到第二个php文件(add.php)。我该如何改变呢。我已经提取了代码,如下所示

//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();
    ?>

1 个解决方案

#1


cURL is to PHP as AJAX is to 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. Here's a simple function.

cURL是PHP,因为AJAX是JS。如果要直接从PHP调用另一个脚本,而不需要broswer向服务器发出其他请求,则可以使用cURL。这是一个简单的功能。

/*
 * 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;
}

#1


cURL is to PHP as AJAX is to 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. Here's a simple function.

cURL是PHP,因为AJAX是JS。如果要直接从PHP调用另一个脚本,而不需要broswer向服务器发出其他请求,则可以使用cURL。这是一个简单的功能。

/*
 * 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;
}