0

I have a simple function in my php file mean to collect emails and send them to a database.

function add_Email_to_MarketingList()
{
    global $wpdb;
    $mail = $_POST['market'];
    $wpdb->insert('wp_marketing_emails', array('email'=>$mail));
    die();
}

What javascript ajax call would i need to write to get this to work? right now the only thing i have up to is this

var mail = prompt("Exciting things to come, Sign up for our email list!!!");
3
  • You can't call PHP functions directly from Javascript. You make a POST or GET request to the PHP script, and it calls the function based on the parameters. Commented Nov 18, 2013 at 16:41
  • Php will be executed on the Server and will send the result to you. After that your Browser executes the javascript code. This means like Barmar say's that you only can give something to php only through POST or GET Commented Nov 18, 2013 at 16:44
  • So it is good that you already have an understanding that AJAX will be needed for this. It is however bad that you have not included any of your attempted solutions here. You need to try to implement something first. There is plenty of information on making AJAX calls available on the interwebs. Commented Nov 18, 2013 at 16:48

2 Answers 2

0

Probably, an AJAX request is what you need.

Assuming you`re using JQuery:

var mail = prompt("Exciting things to come, Sign up for our email list!!!");

$.post( "url_to_your_php_file", { "market":mail }, function( data ) {

    if(data == true)
        alert('Success!');
    else
        alert('Ooops! Try again later.');
});

You should update your PHP file to have the following code:

function add_Email_to_MarketingList($mail)
{
    global $wpdb;

    if($wpdb->insert('wp_marketing_emails', array('email' => $mail)))
        return true;

    return false;
}

add_Email_to_MarketingList($_POST['market']);

exit();

Also, you should use $_SERVER['HTTP_X_REQUESTED_WITH'] in PHP to detect any AJAX request. Your code would only work with AJAX requests and any direct access to the file would be denied.

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    /* AJAX Here */
}
else {
    die('No direct access allowed.');
}

I would also use Validation FILTERS and filter_var to check the e-mail. Never trust outside input.

1
  • thanks for the filters tip, we have a decent solution up and running. Commented Nov 22, 2013 at 17:18
0

Say you are using a JS framework like jQuery, you would utilize the $.ajax() or $.post() function. See http://api.jquery.com/jQuery.post for examples. You need to specify the URL of the PHP page/script that contains the aforementioned function in the Ajax call. You should be doing a POST, since you are sending a non-idempotent request (inserting into a database).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.