Nicolas Papaconstantinou Nicolas Papaconstantinou - 1 month ago 7
Javascript Question

How to retrieve information from PHP and use it in javascript

I am interested to retrieve the name and the email of the user from my contact form and use it to display something like this: "Thank you for your message $name, we will reply to the following email: $email" I want to make changes to the .done function

Here is the javascript:

$.ajax({
type: 'POST',
url: "sendemail.php",
data: {
Name: $form.find("input[name='name']").val(),
Subject: $form.find("input[name='subject']").val(),
Email: $form.find("input[name='email']").val(),
message: $form.find("textarea[name=message]").val(),
},
beforeSend: function () {
form.append(form_status.html('<p style="font-weight:bold;color:white;"><i class="fa fa-spinner w3-text-white w3-spin" style="font-size:50px"></i> Email is sending...</p>').fadeIn());



}
}).done(function (data) {
//here is the function i want to insert the information
form_status.html('<p style="color:white;" class="text-success w3-animate-fading"><i class="fa fa-check fa-2x" aria-hidden ="true"></i>\n\
Message sent. Thank you for contacting us phpName, we will reply to the following email: phpEmail <i class="fa fa-smile-o fa-2x" aria-hidden="true"></i> </p>')
.delay(7000).fadeOut();



});

Answer

var name = $form.find("input[name='name']").val();
var email = $form.find("input[name='email']").val();

$.ajax({
    type: 'POST',
    url: "sendemail.php",
    data: {
        Name: name,
        Subject: $form.find("input[name='subject']").val(),
        Email: email,
        message: $form.find("textarea[name=message]").val(),
    },
    beforeSend: function() {
        form.append(form_status.html('<p style="font-weight:bold;color:white;"> < i class = "fa fa-spinner w3-text-white w3-spin" style = "font-size:50px" > < /i>Email is sending... < /p>').fadeIn());
    }
}).done(function(data) {
    //here is the function i want to retrieve the data from php
    form_status.html('<p style="color:white;" class="text-success w3 - animate - fading "><i class="fa fa - check fa - 2 x " aria-hidden ="true "></i>\n\
            Message sent. Thank you for contacting us ' + name + ', we will reply to your email shortly. <i class="fa fa - smile - o fa - 2 x " aria-hidden="true "></i></p>')
        .delay(7000).fadeOut();
});

Since you already have the name and email information in the form I dont understand why you just dont use that. You dont even need to ask for that information from the server. However I suggest that in the sendemail.php file you return an object containing status if the email could be sent or not. This way you can display an error message if something went wrong serverside. For instance like this:

{
    success: true,
    message: '',
    errorCode: ''
}

Comments