Home > Net >  Javascript action php
Javascript action php

Time:05-26

I have form with js validation, and I need to action on php file through js, how I can this do better. Can you help and say who is better to do it. if you directly connect the action to the php file, then everything works, but how can I do it through js?

FORM HTML

<form id="contact-form" >

                    <input  type="text" name="name">
                    <input  type="email" name="email">
                    <input  type="tel" name="tel">
            
                    <button type="submit" id="uploadBTN" >Submit</button>
            </form>

PHP

require_once('./phpmailer/PHPMailerAutoload.php');
$mail = new PHPMailer;
$mail->CharSet = 'utf-8';

$name = $_POST['username'];
$email = $_POST['email'];
$tel = $_POST['tel'];
$check = $_POST['agreement'];

$mail->addAddress('[email protected]');   
$mail->addAttachment($_FILES['upload']['tmp_name'], $_FILES['upload']['name']);
$mail->isHTML(true);

$mail->Subject = 'TITLE';
$mail->Body    = '' .$name . ' NAme ' .$tel. '<br>Email: ' .$email;
$mail->AltBody = '';

if ($mail->send()) {
    echo 'Sussesful';
    } else {
    echo "error";
    }

JS

form.addEventListener('submit', e => {
    e.preventDefault();
    
  checkInputs();
  

});

function checkInputs() {
    // trim to remove the whitespaces
    const usernameValue = username.value.trim();
    const emailValue = email.value.trim();
    const phoneValue = phone.value.trim();
    
    ...
}

CodePudding user response:

If I understand correctly, you want to make a POST request in javascript. In modern javascript, this can be done through the Fetch API, or through jQuery's $.ajax() function. I reccomend the Fetch API. Here's an example with the Fetch API using your code:

let data = new FormData();
data.append("username", usernameValue);
data.append("email", emailValue);
data.append("phone", phoneValue);
fetch("INSERT_PHP_FORM_URL_HERE", { method: "POST", body: data });
  • Related