June 3, 2010

need to run php script when form is submitted

Question by Brad

I have a form that needs to run a php script once the submit button is clicked, it needs to be ajax.

<form method="post" action="index.php" id="entryform" name="entryform">
<input type="submit" name="submit" value="Submit" onclick="JavaScript:xmlhttpPost('/web/ee_web/include/email-notification.php', 'entryform')" />
</form>

In this situation, using if(form posted) { get results and run script } is not an option, I need to run the script externally, that is why I need it to execute the email-notification.php at onclick

When I point my web browser to domain.com/include/email-notification.php – it runs perfectly.

Any help is appreciated.

This executes the script before you submit the form, now I need to wait to execute the script once the submit button is clicked, possible to do this?

$.ajax({
    type: "POST",
    url: "/include/email-notification.php",
    dataType: "script"
});

Answer by KyleFarris

Check out the $.ajax() function of the jQuery javascript library. It will make you life much much easier and is quite minimal as far as added size to your page (like 12kb or something like that).

Answer by Starx

I suggest using jquery. because of its flexibility and conveinience

If you want to send email notification and then only post the data then do as following:

create a separate page to handle your email notification like email.php

// fill in headers and prepare content
$result = mail(............................);
if($result) { return 1; } else { return 0; }

Then on your form

$('#mysubmitbutton').click(function() {
      $.post(
           'email.php',
           { emailadd: 'my@email.com', content: 'mycontent' }, //send parameters to email.php
           function(data) {
                //now check whether mail sending was successfull
                if(data==1) {
                     //message sending was successful so carry out further operation
                     //.................................
                }
                else { alert("Sorry, email notification was unsuccessfull"); }
           });
});

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!