Jump to content

Send data from JavaScript to PHP page


PGCoder

Recommended Posts

Hello w3schools community, i build a feedback form for my website. I use JQuery to create the form and check the input validation.This works fine but when the user fill out the form I am not able to send me a mail. I can't run a php code in a javascript function so I use a the ajax function by JQuery to send data to a php page. The problem is that something must be wrong with the data transmission because i can't send a mail. If I run the PHP page (sendEmail.php) I receive an email. But if I fill out the form and want to submit - the ajax function doesn't call the PHP page. I could be wrong but the form validation and the mail php code is working well . . . so ajax must be the problem! Here is the relevant code for this form I have now: HTML FORM:

<div class="fieldgroup">				    <label for="subject">Subject:</label>				    <input type="text" name="subject" id="subject">			    </div>			    <div class="fieldgroup">				    <label for="name">Name:</label>				    <input type="text" name="name" id="name">			    </div>			    <div class="fieldgroup">				    <label for="email">Email:</label>				    <input type="text" name="email" id="email">			    </div>			    <div class="fieldgroup">				    <label for="message">Message:</label>				    <input type="text" name="message" id="message">			    </div>			    <div class="fieldgroup">				    <input type="submit" value="Submit" class="submit">			    </div>

JAVASCRIPT VALIDATION + AJAX:

$(function($,W,D)  {  var JQUERY4U = {};  JQUERY4U.UTIL =  {  setupFormValidation: function()  {  //form validation rules  $("#register-form").validate({							   rules: {							   subject: "required",							   name: "required",							   email: {							   required: true,							   email: true							   },							   message: "required"							   },							   messages: {							   subject: "Please enter a subject",							   name: "Please enter your name",							   email: "Please enter a valid email address",							   message: "Please enter your message"							   },							   submitHandler: function(form) {                               							   $.ajax({									  type: "POST",									  url: "sendEmail.php",									  data: { sendSubject : subject, sendName: name, sendEmail: email, sendMessage: message }									  }); 								    form.submit();							   }							   });  }  }  $(D).ready(function($) {			 JQUERY4U.UTIL.setupFormValidation();			 });  })(jQuery, window, document);

PHP PAGE (sendEmail.php):

<?php    $sendSubject = $_POST['sendSubject'];    $sendName = $_POST['sendName'];    $sendEmail = $_POST['sendEmail'];    $sendMessage = $_POST['sendMessage'];	 if(mail($sendEmail, $sendSubject, $sendName, $sendMessage)){	 echo 'sent';	 } else {	 echo 'failed';	 }?>

Thanks,PGCoder

Link to comment
Share on other sites

You can verify all of that yourself with your browser. If you open the developer tools in your browser there should be a place that you can see the ajax request going out, including the data that it contains and the server's response. There are links in my signature for the various developer consoles. If I took a guess I would say the variables that you're trying to send with the ajax request are not defined.

Link to comment
Share on other sites

I am using Safari on my iMac. But I am not able to see the ajax request.
where are you looking? Did you find Safar's developer tools? The links are right in JSG's signature like he said
Use a debugger: Firefox, IE, Chrome, Safari, or Opera
Link to comment
Share on other sites

Javascript can't send email, that's why you're sending an ajax request. You should see a request going out to sendEmail.php. If you don't see that, then it's not going out. If it's not going out then check the Javascript error console for error messages.

Link to comment
Share on other sites

if you are not seeing the request go out (i.e. a request being made to sendEmail.php in the network connections tab) then it seems like you might have an error in your code. Have you checked for any errors in the console tab?

Link to comment
Share on other sites

Edit:I changed the code to following and now I can run the code without any issue/warning. The problem is that ajax doesn't work - the debug console said "Details: -":

$(document).ready(function(){    $("#register-form").validate({    rules:  {	    subject:"required",	    name:"required",	    email: {		    required:true,		    email:true	    },	    message:"required"    },       messages: {	    subject: "Please enter a subject",	    name: "Please enter your name",	    email: "Please enter a valid email address",	    message: "Please enter your message"    },       submitHandler: function(form) {	   	    $.ajax({				  type: 'POST',				  data: ("#register-form").serialize(),				  url : 'sendEmail.php'				  success: function (html) {					  alert('done');				  },				  error: function(data, textStatus, jqXHR) {					  alert('error')				  }			  });   	    form.submit();    }    });});

Original: I debugged the javascript file "Javascript Validation/Ajax" is the issue: Error target to the last line: })(jQuery, window, document);Following error output @ console: TypeError: '[object Object]' is not a function (near '...})(jQuery, window, doc...')

Edited by PGCoder
Link to comment
Share on other sites

That error probably means that jQuery is not defined, that you aren't including the jQuery code. As for the other code, it's probably not correct to have form.submit in the submit handler. You want to send an ajax request instead of submitting the form normally. That code does both.

Link to comment
Share on other sites

I get my code to work now. But I have a new issue :-/The messages are sent multiply times - so it happens that I receive 10 times the same message and sometimes only one. What could this bug be? Here is the new javascript code:

$(document).ready(function(){    $("#register-form").validate({    rules:  {	    form_subject:"required",	    form_name:"required",	    form_email: {		    required:true,		    email:true	    },	    form_message:"required"    },       messages: {	    form_subject: "Please enter a subject",	    form_name: "Please enter your name",	    form_email: "Please enter a valid email address",	    form_message: "Please enter your message"    },       submitHandler: function(form) {   	    $.post('sendEmail.php', $(form).serialize(), function () {  $("#form_output").html("<b>Thank you for contacting us. We have received your message and look forward to answer you as soon as possible.</b>");  $("#requestSummary").hide();  $(".fieldgroup").hide();  $(".back_form").hide();  //$("#register-form").hide();  //form.submit();	    },'json');    }    });});

Here is the php file to send an email:

<?php//Request Form$s_output = $_POST['selection'];	    $s_b_output = $_POST['selection_business'];	    $s_o_output = $_POST['selection_opsy'];	    $s_i_d_output = $_POST['selection_ios_device'];	    $s_i_v_output = $_POST['selection_ios_version'];	    $s_a_d_output = $_POST['selection_android_device'];//Form$subject=$_POST['form_subject'];$name=$_POST['form_name'];$email=$_POST['form_email'];$message=$_POST['form_message'];$header="";$mail_to="";   	    //Business	    if($s_output=="Business") {  $mail_to="business@mydomain.com";   $header="Form Output: " . $s_output . " -> " . $s_b_output;	    }	   	    //Support	    if($s_output=="Support") {		 $mail_to="support@mydomain.com";   $header="Form Output: " . $s_output . " -> " . $s_o_output . " -> " . $s_i_d_output . " -> " . $s_i_v_output;	    }$content=$header . "\n\nName: " . $name . "\nEmail: " . $email . "\nMessage: " . $message;mail($mail_to, $subject, $content);?>

Link to comment
Share on other sites

I only send one $.post at the first submit click and if that was successful I hide the complete form ( $("#requestSummary").hide(); + $("#.fieldgroup").hide(); + $("#back_form").hide(); ).When I fill out the form I receive always one email - where can I see the number of $.post send?I thought that users click the submit button multiply times - but after one successful $.post I hide the complete form. :-/

Edited by PGCoder
Link to comment
Share on other sites

where can I see the number of $.post send?
right in the networks tab, like we've mentioned. multiple requests will show on multiple lines.
Link to comment
Share on other sites

My debugger tells me following:Network Requests: sendEmail.php(Name) - XHR(Type) - 200(Status) - No(Cached) - 157B(Transfered) - 279ms(Latency) - 1.8ms(Duration)Javascript & Events: Event Dispatched(Type) - submit(Details) - jquery.min.js:2(Location) - 15.32s(Start Time) - 9.2ms(Duration) Does the Ajax request take too long? Also I can only see one debug line @ Network Requests but no multiply calls ...

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...