vendredi 3 juin 2016

AJAX not receiving response from PHP file


TL;DR: I want to create a script that runs PHPMailer.php at the onsubmit event without refreshing or changing the current page. I want it to display a text next to the button instead, however, the request doesn't get any response from the PHP file.

I've created a form that's supposed to send the details by e-mail. I used phpmailer and got it to work. However, I decided to make it more responsive and instead of opening another page each time the e-mail was sent, to show a text like "Sent!" near the submit button without actually refreshing it.
So, here's my troublesome code:

var xhttp = new XMLHttpRequest();   
xhttp.open("POST", "PHPMailer.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

xhttp.onreadystatechange = function () {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
        document.getElementById("conf").innerHTML = xhttp.responseText;
        alert(xhttp.responseText);
    }
};
xhttp.send("referer=index.php&name=" + name + "&addr=" + email + "&phone=" + phone + "&subj=" + subj + "&message=" + message + "&submit=Send");
return false;

The script gets the value of name, email, phone, subj, message correctly. However, when I press the Send button on the form, it does nothing. It never reaches that alert. I tried adding an else to that if, with another alert in it and that would execute 3 times, but the fourth would be nowhere. No response is there, either. I don't get a response even if I add a echo "1"; in my PHP file at the end. Here's the form:

<!-- here's a table -->
<form action="" onsubmit="return checkData();" class="hiddenForm" enctype="multipart/form-data" id="myform">
<!-- skipping the first row to save space -->
<tr>
    <td colspan="2"><i class="mand">*</i><i style="font-size: 10pt"> = required</i></td>
    <td><input type="submit" name="submit" value="Send"></td>
    <td colspan="2" id="conf"></td>     <!-- In this <td> should come the "Sent!" 
                                           message -->                 
</tr>
</form>
</table>

Here's a picture of where the message should appear. So, have you got any idea why doesn't the POST respond? Is there anything wrong with the script?




Aucun commentaire:

Enregistrer un commentaire