Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to send form element values directly to php page using javascript

What I am trying here is when you click on submit button I am calling one javascript function which takes all the form element values and passes it to the php page without storing them inside the variable and then send those variables.

Example of my form:

<form enctype="multipart/form-data" method="post" name="fileinfo">
  <label>Your email address:</label>
  <input type="email" autocomplete="on" autofocus name="userid" placeholder="email" required size="32" maxlength="64" />
  <br />
  <label>Custom file label:</label>
  <input type="text" name="filelabel" size="12" maxlength="32" />
  <br />
  <label>File to stash:</label>
  <input type="text" name="email" required />
  <input type="button" onsubmit="sendvalues()" value="Stash the file!" />
</form>

Now on javascript, I want to send userid and email fields to directly go to php page without first retrieving them into a variable and then send that variable via ajax.

function sendValues() {
  var formElement = document.querySelector("form");
  console.log(formElement);
  var formData = new FormData(formElement);
  var request = new XMLHttpRequest();
  request.open("POST", "<?php echo VIEW_HOST_PATH;?>process_data.php");
  formData.append("process_type", 'process_data');
  request.send(formData); //want to send all form userid, email directly to php page
  request.onreadystatechange = (e) => {
    console.log(request.responseText)
  }
}

Is this possible to send user_id and email values to php page directly? So, for example, form element which contains emailed and user info and any other forms element and they all send to php page via ajax but most important without storing this element values in javascript variables. thanks

like image 957
Jimil Avatar asked Aug 09 '26 00:08

Jimil


1 Answers

In your form you should specify property "action". That action would be your php file that will handle your submit action. Also you could add to this form id selector.

<form id="file-info" enctype="multipart/form-data" action="/process_data.php" method="post" name="fileinfo">

And now in your function sendValues() you could submit form like this:

function sendValues() {
document.getElementById("file-info").submit();
}

or you do not even need this function if you set your input button type to submit:

 <input type="submit" name="submit" /> 

And then in your php file you can use your variables like:

if (isset( $_POST['submit'])) 
{
 $userId = $_POST['userid'];
 $email = $_POST['email']; 
}
like image 107
N. Djokic Avatar answered Aug 11 '26 14:08

N. Djokic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!