posting data from javascript to php is not working

Codes here !

Moderators: egami, macek, gesf

Post Reply
sunnykeerthi
New php-forum User
New php-forum User
Posts: 1
Joined: Sun Jan 31, 2021 12:27 pm

Sun Jan 31, 2021 12:31 pm

Hi,

I'm pretty new to PHP and pardon me if my question is a dumb one and also sorry for pasting my entire code here. I'm writing a code that sends an email from PHP with an attachment. And here is my code.

my main.php file

Code: Select all

<form action="javascript:postData()" id="form">

<fieldset>

<!-- Form Name -->
<legend>Application</legend>

<!-- Text input-->
<div class="form-group">
  <label class="col-md-4 control-label" for="Full Name">Full Name</label>  
  <div class="col-md-4">
  <input id="FullName" name="FullName" type="text" placeholder="" class="form-control input-md">
    
  </div>
</div>

<!-- Text input-->
<div class="form-group">
  <label class="col-md-4 control-label" for="Email">Email</label>  
  <div class="col-md-4">
  <input id="Email" name="Email" type="text" placeholder="" class="form-control input-md">
    
  </div>
</div>

<!-- Text input-->
<div class="form-group">
  <label class="col-md-4 control-label" for="roleFor">Role Applying for</label>  
  <div class="col-md-4">
  <input id="roleFor" name="roleFor" type="text" placeholder="" class="form-control input-md">
    
  </div>
</div>

<!-- Text input-->
<div class="form-group">
  <label class="col-md-4 control-label" for="jobId">Job ID</label>  
  <div class="col-md-4">
  <input id="jobId" name="jobId" type="text" placeholder="" class="form-control input-md">
    
  </div>
</div>

<!-- File Button --> 
<div class="form-group">
  <label class="col-md-4 control-label" for="uploadResume">Upload Resume</label>
  <div class="col-md-4">
        <input type="file" name="file" class="form-control">
  </div>
</div>

<!-- Textarea -->
<div class="form-group">
  <label class="col-md-4 control-label" for="experience">Experience</label>
  <div class="col-md-4">                     
    <textarea class="form-control" id="experience" name="experience"></textarea>
  </div>
</div>

<!-- Button -->
<div class="form-group">
  <label class="col-md-4 control-label" for="submit"></label>
  <div class="col-md-4">
    <button id="submit" type="submit" name="submit" class="btn btn-success">Submit</button>
  </div>
</div>

</fieldset>
</form>

and my js is

Code: Select all

function postData() {
    const form = document.getElementById('form');
    const data = new FormData();
    data.append('FullName', form.FullName.value);
    data.append('Email', form.Email.value);
    data.append('roleFor', form.roleFor.value);
    data.append('jobId', form.jobId.value);
    data.append('experience', form.experience.value);

    fetch('sendEmail.php', {method: 'POST', body: data}).then(response => {
        if (!response.ok){
            throw new Error('Network response was not ok.');
        } else 
        {
            console.log(response);
            alert('New job posted');
            document.getElementById("form").reset();

        }
    }).catch(err => console.log(err));
}
and my sendEmail.php is

Code: Select all

<?php
$fName = $_POST['FullName'];
$emailAddr = $_POST['Email'];
$roleFor = $_POST['roleFor'];
$jobId = $_POST['jobId'];
$exp = $_POST['experience'];

if (!empty($fName) && !empty($emailAddr))
    {

       

        $statusMsg = '';
        if (isset($_FILES["file"]["name"]))
        {
            $emailAddr = $_POST['Email'];
            $fromemail = 'admin@admin.com';
            $subject = 'Teesst Syubect';
            $email_message = "<table><tr><td>Name: </td><td>" . $fName . "</td></tr> </table>";
            $email_message .= "Please find CV in the attachment";
            $semi_rand = md5(uniqid(time()));
            $headers = "From: " . $fromemail;
            $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

            $headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";

            if ($_FILES["file"]["name"] != "")
            {
                $strFilesName = $_FILES["file"]["name"];
                $strContent = chunk_split(base64_encode(file_get_contents($_FILES["file"]["tmp_name"])));

                $email_message .= "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type:text/html; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $email_message .= "\n\n";

                $email_message .= "--{$mime_boundary}\n" . "Content-Type: application/octet-stream;\n" . " name=\"{$strFilesName}\"\n" .
                //"Content-Disposition: attachment;\n" .
                //" filename=\"{$fileatt_name}\"\n" .
                "Content-Transfer-Encoding: base64\n\n" . $strContent .= "\n\n" . "--{$mime_boundary}--\n";
            }
            $toemail = "myEmail@gmail.com";

            if (mail($toemail, $subject, $email_message, $headers))
            {
                $statusMsg = "Email send successfully with attachment";
                header("Location:careers.php");
            }
            else
            {
                $statusMsg = "Not sent";
            }
        }

    }

    else
    {
        echo "Enter both Title and Desription";
        die();
    }
?>
Now the issues are,

when I do <form action="sendEmail.php" id="form" method="post">, it is sending the email as expected, but when I try to post it through javascript (as shown in my code), it isn't sending an email, but to my surprise, the response status is 200 OK.

Please let me know where I'm going wrong and how can I fix this.

Thanks
User avatar
Strider64
php-forum GURU
php-forum GURU
Posts: 418
Joined: Sat Mar 23, 2013 8:24 am
Location: Livonia, MI
Contact:

Sun Jan 31, 2021 7:16 pm

I set my javascript/FETCH into segments that way I know how to handle the error(s).

Here's an example what I'm talking about (Sorry about it be a little long) :

Code: Select all

    /* Handle General Errors in Fetch */
    const handleErrors = function (response) {
        if (!response.ok) {
            throw (response.status + ' : ' + response.statusText);
        }
        return response.json();
    };

    /* Success function utilizing FETCH */
    const checkUISuccess = function (parsedData) {
        //console.log(parsedData);
        var correct = parseInt(parsedData.correct);
        var userAnswer = parseInt(d.querySelector('#headerStyle').getAttribute('data-user'));
        scoringFcn(userAnswer, correct);
        calcPercent(answeredRight, total);
        highlightFCN(userAnswer, correct);

        disableListeners();
        next.style.display = "block";
        next.addEventListener('click', removeQuiz, false);
    };

    /* If Database Table fails to load then hard code the correct answers */
    const checkUIError = function (error) {
        console.log("Database Table did not load", error);
        switch (gameData[gameIndex].id) {
            case 1:
                var correct = gameData[gameIndex].correct;
                break;
            case 55:
                var correct = gameData[gameIndex].correct;
                break;
            case 9:
                var correct = gameData[gameIndex].correct;
        }
        var userAnswer = parseInt(d.querySelector('#headerStyle').getAttribute('data-user'));
        scoringFcn(userAnswer, correct);
        calcPercent(answeredRight, total);
        highlightFCN(userAnswer, correct);

        disableListeners();
        next.addEventListener('click', removeQuiz, false);

    };

    /* create FETCH request for check answers */
    const checkRequest = function (url, succeed, fail) {
        fetch(url, {
            method: 'POST', // or 'PUT'
            body: JSON.stringify(responseAns)

        })
                .then((response) => handleErrors(response))
                .then((data) => succeed(data))
                .catch((error) => fail(error));
    };

    /* User has made selection */
    const clickHandler = (e) => {
        const userAnswer = parseInt(e.target.getAttribute('data-correct'));
        responseAns.id = parseInt(gameData[gameIndex].id); // { id: integer } 
        const checkUrl = "check.php";
        stopTimer();
        if ((gameIndex + 1) === totalQuestions) {
            next.textContent = 'results';
        }
        checkRequest(checkUrl, checkUISuccess, checkUIError);
        d.querySelector('#headerStyle').setAttribute('data-user', userAnswer);
    };
This is a portion of code from a JavaScript Trivia Game that I developed, but I just want to show the break down of the fetch statement. However, the main important thing which I think might be your problem is in you php file. Here's a snippet of my check.php file :

Code: Select all

<?php

require_once 'assets/config/config.php';

/* Makes it so we don't have to decode the json coming from javascript */
header('Content-type: application/json');

/*
 * The below must be used in order for the json to be decoded properly.
 */
$data = json_decode(file_get_contents('php://input'), true);
Notice the last line as that is the only way that I could get $_POST to work correctly, but unfortunately I don't know if it will work for $_FILES?

Hopes that helps you out a little.
Life is a fig newton of your imagination! https://www.miniaturephotographer.com
Post Reply