I'm in the process of building an ajax contact-form for a WordPress theme and am running into an issue when submitting the form; the console keeps saying it can't retrieve my mail-form.php file (used to format the email) when I'm pretty sure I've got the url right.
Here's the code that I'm using:
jQuery.ajax({
type: "POST",
url: "<?php echo get_template_directory_uri(); ?>/mail-form.php",
cache: false,
data: "name=" + name + "&email=" + email + "&message=" + message,
success: function (html) {
jQuery("#contact-form").slideUp("slow");
jQuery("#contact-form").after("<p><span class='center' id='send-message'>Your message has been sent! We will reply shortly!</span></p>");
jQuery("#send-message").fadeIn("slow");
}
});
Here is a link to the form... http://wordpress-dev.designer17.com/contact/
The last time I used this it worked just fine, so I'm quite bewildered by this.
Because you're using PHP within your .js file (line 56):
url: "<?php echo get_template_directory_uri(); ?>/mail-form.php",
What you can do is add this to your main template:
var TEMPLATE_URI = "<?php echo get_template_directory_uri(); ?>";
then within your .js file use:
url: TEMPLATE_URI + "/mail-form.php",
Your JavaScript, $.ajax function call in this case, is client side and is not parsed by php, which is server side. Because of this the JavaScript parser interprets the string "" as a literal string and it is not parsed. To solve this simple use a relative url or generate the JavaScript in a php template which can parse the php code.
Remember: Code is always parsed/rendered serverside, sent back to the client's browser, then client side scripting, JavaScript code in your case, executes in the browser.
I supose you moved your javascript onto a .js file, however unless you instruct your http server to process javascript files as php any php inside them is just text.
Either move the function back into a php file or (better approach) pass the URL as an attribute, for example:
// PHP FILE
<form action="URLGOESHERE" id="form_id">
...
// JAVASCRIPT FILE
var url = $("#form_id").attr("action");
jQuery.ajax({
type: "POST",
url: url,
...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.