Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Is it possible to call a function from PHP using onsubmit from javascript? If so could someone give me an example of how it would be done?

function addOrder()
    {
    $con = mysql_connect("localhost", "146687", "password");
        if(!$con)
                {
                die('Could not connect: ' . mysql_error())
                }

    $sql = "INSERT INTO orders ((user, 1st row, 2nd row, 3rd row, 4th row)
    VALUES ($session->username,1st variable, 2nd variable, 3rd variable, 4th variable))";

    mysql_query($sql,$con)
        if(mysql_query($sql,$con))
                {
                echo "Your order has been added";
                }
                else
                {
                echo "There was an error adding your order to the databse: " . mysql_error();
                }

Thats the function I am wanting to call. Its an ordering system, you type in how much of each item you want, hit submit and it should add the order to the table.

share|improve this question
 
What problem are you trying to resolve? Could you elaborate a bit? –  roosteronacid Oct 21 '08 at 10:39
 
Looks like you don't know exactly how this client/server thing work, php runs on the server, javascript in the client, there is no way where you can directly make that call, you will have to use a library,see XAJAX suggestion bellow that is what I use (it doesn't get more trasparent than that). –  levhita Oct 21 '08 at 14:15
add comment

7 Answers

up vote 16 down vote accepted

You can not call a PHP function from Javascript...

Javascript is a client language (it's executed on the Web browser, after receiving the web page) while PHP is on the server side (it's executed before the web page is rendered). You have no way to make one call another.

...but you can get the result of an external PHP script

There is a Javascript function called xhttprequest that allows you to call any script on the Web server and get its answer. So to solve your problem, you can create a PHP script that outputs some text (or XML, or JSON), then call it, and you analyze the answer with Javascript.

This process is what we call AJAX, and it's far easier to do it with a good tool than yourself. Have a look to JQuery, it's powerful yet easy to use Javascript library that has built-in AJAX helpers.

An example with JQuery (client side) :

$.ajax({
   type: "POST", // the request type. You most likely going to use POST
   url: "your_php_script.php", // the script path on the server side
   data: "name=John&location=Boston", // here you put you http param you want to be able to retrieve in $_POST 
   success: function(msg) {
     alert( "Data Saved: " + msg ); // what you do once the request is completed
   }
share|improve this answer
add comment

Sounds like you want AJAX.

This is too big a topic for a single answer, but that should get you going.

Basically, the Javascript will send an HTTP request to a PHP script on your server and then do something with the response. JSON is probably something you'll want to learn about too.

share|improve this answer
 
And this is a too much general answer, you should at least give some to direction to a library. I suggest XAJAX. –  levhita Oct 21 '08 at 14:17
add comment

It's indirectly possible to call a PHP function using JavaScript. As other people have already mentioned, you're going to want to do some type of request - this doesn't necessarily have to be Ajax. It could be synchronous. Without knowing exactly what you're trying to accomplish, here's what I would suggest:

  • Attach an event handler to the form's submit option (or use the standard submit if you're not going to use Ajax)
  • Bundle up any parameters that will need to be passed to the PHP function either in a POST or in the query string of the address to the page.
  • Fire the request (either asynchronously or via submit)
  • In the PHP script that is the target of the request, pull out of the parameters from the $ _ POST or $ _ GET.
  • Call the PHP function that you need with the parameters.
  • Echo back the response and parse it as needed once the request completes.

Again, this is a bit general but so is your question. Hopefully this gives some sort of direction.

share|improve this answer
add comment

The closest you are going to get will be xajax which will let you wrap a PHP function into an AJAX call. I've used it quite a bit before I started working with Zend Framework and found it too hard to implement in an OO way.

With xajax you write a PHP function that does all of your regular logic and then returns a ObjectResponse object that manipulates the browser through AJAX (alert boxes, change HTML, CSS, etc). You register your function with xajax and then xajax will spit out some javascript into your HTML's section.

In your HTML you just call that javascript function that xajax generated and it takes care of the rest through AJAX.

share|improve this answer
add comment

You will want to do something like:

<form action="add_order.php" method="POST" id="add_order_form">
<!-- all of your form fields -->
<input type='submit' value='Add Order'>
</form>

<script type="text/javascript">
$("#add_order_form").submit(function() {
    var action = $("#add_order_form").attr("action");
    var data = $("#add_order_form").serialize();
    $.post(action, data, function(json, status) {
        if(status == 'success') {
            alert(json.message);
        } else {
            alert('Something went wrong.');
        }
    }, "json"); 
    return false;
});
</script>

And then have a PHP file named add_order.php with something like:

$success = 0;
$con = mysql_connect("localhost", "146687", "password");
if(!$con) {
    $message = 'Could not connect to the database.';
} else {
    // SANITIZE DATA BEFORE INSERTING INTO DATABASE
    // LOOK INTO MYSQL_REAL_ESCAPE_STRING AT LEAST,
    // PREFERABLY INTO PREPARED STATEMENTS
    $query_ok = mysql_query("INSERT INTO `orders` ....");
    if($query_ok) {
        $success = 1;
        $message = "Order added.";
    } else {
        $message = "Unable to save information";
    }
}

print json_encode(array('success' => $success, 'message' => $message));

For this beauty to work you will have to go to the jQuery website, download it, and include the jquery.js file.

I haven't tested the above but it should work. Good luck.

share|improve this answer
add comment

Yes, another great and easy tutorial for learning ajax is:

http://24ways.org/2005/easy-ajax-with-prototype/

Prototype is another thing I recommend if you havent gone to far with your project and need to revert a lot of functionality.

http://www.prototypejs.org/

Good luck!

share|improve this answer
add comment

Sorry, your question is too basic. Depending on what PHP function you want to call on formsubmit Ajax will not help you. Are you aware of the fundamental (clientside/serverside) differences between PHP and JavaScript?

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.