I've got this php function located in the base /home/index.php
function addEmail() {
$email = htmlentities($_POST['email']);
if (wp_create_user($email, '7777777', $email)) echo 'OK';
die();
}
I've also got this jQuery function located in /home/js/assets.js. The function checks to see if the email is valid and if so, should run the php function above.
$('#submit_btn').click(function () {
var entered = $('#ms_id-2 > input#input_fld').val();
if (isValidEmailAddress(entered) == false) {
alert('Sorry, the email you entered is invalid. Please try again.');
//console.log('No Validation!');
} else {
alert('Thank you. Your email address has been added to the list.');
}
});
So basically, if the email is valid, I need the code to execute that function in index.php. What's the quickest way to do this?
-
You need Ajax: w3schools.com/ajaxandrrs– andrrs2015年08月12日 13:18:53 +00:00Commented Aug 12, 2015 at 13:18
-
To execute the server code from JavaScript , you need to do ajax.AsgarAli– AsgarAli2015年08月12日 13:18:54 +00:00Commented Aug 12, 2015 at 13:18
1 Answer 1
Create a PHP resource which invokes the desired logic. Something as simple as this might do the trick depending on what you want it to do:
<?php
require('index.php');
addEmail();
?>
Then make an AJAX request to that resource:
$.post('theNewPage.php', { 'email' : entered }, function (response) {
// handle the response in some way
});
The point is that JavaScript and PHP can't execute each other's code. One is client-side, one is server-side. They run at different times in different environments. And they communicate by way of HTTP requests in this case.
So if you have code server-side that you want to execute, then you create a page which executes it and you make an HTTP request (in this case an AJAX request) to that page to execute it. The response in the callback function in the JavaScript code will contain the result of that page (which in this case appears to be an echo of 'OK'). You'd examine that response and perform whatever action you intend to perform on the page.