Is it possible to use an Ajax call to submit a form to a PHP file, where it then using functions from within a separate PHP file that are not declared within the file being called by Ajax?
In my case, I am using an init.php file which holds the MySQL Connection and using include() to include functions for MySQL, Page Logic, and Handling users.
init.php
session_start();
$servername = "";
$username = "";
$password = "";
$database = "";
$conn = true;
$conn = mysqli_connect($servername, $username, $password, $database);
//Include functions for MYSQL
include('functions/fn_mysql.php');
//Include functions for Page Logic
include('functions/fn_pages.php');
//Include functions to handle users
include('forms/users.php');
For example, A simple HTML Form.
<form id="fileUpload" method="post" action="" enctype="multipart/form-data">
<input type="hidden" name="dispatch" value="file_upload" />
<label for="fileType">What kind of document is this?</label>
<select id="fileType" name="fileType">
<option value="PDF">PDF</option>
<option value="DOC">DOC</option>
</select>
<input type="submit" name="submit_upload" value="Submit" />
</form>
script.js
File used to submit form.
$("#fileUpload").on('submit', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'users.php',
data: new FormData(this),
dataType: 'json',
contentType: false,
cache: false,
processData: false,
});
users.php
This file accepts the Ajax call and using a function from a separate PHP file called fn_mysql.php will insert to the DB.
if ($_POST['dispatch'] == 'file_upload') {
// process to DB
$sql = "INSERT INTO doc_attributes (?u)";
$insert_array = array ();
$add = db_insert($sql, $insert_array);
if (!empty ($add)) {
// Added
}
Now, when the user submits this form the data is then sent to the users.php file. But, is unable to now access the functions detailed in the fn_mysql.php file as they are undefined.
Without the Ajax call this works as intended. Is using this method of separating files to keep functions separate from forms not possible with Ajax?
users.phpwill require that you useinclude "/path/to/file.php"for all required files also