Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript action php

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 class="inp" type="text" name="name">
                    <input class="inp" type="email" name="email">
                    <input class="inp" type="tel" name="tel">
            
                    <button type="submit" id="uploadBTN" class="btn">Submit</button>
            </form>

PHP

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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('artwhite.urs@gmail.com');   
$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();
    
    ...
}

>Solution :

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 });
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading