2

Possible Duplicate:
Call php function from javascript

I understand that php is server side and JavaScript is client side. But I would like to know how to run a PHP method when a JavaScript function is called. Below is my code, I know the error is but how can I perform the php method?

 <script type="text/javascript">
            function toggle()
            {
                var ele = document.getElementById("addCatTextBox");
                var text = document.getElementById("addCatButtonText");
                if(ele.style.display == "block") {
                        ele.style.display = "block";
                    text.innerHTML = "Save category";
                    <?php Category::addCategory($inCatName)?>
                }
                else {
                    ele.style.display = "none";
                    text.innerHTML = "Add new category";
                }
            } 
    </script>

Thanks for your help.

6
  • Brian beat me to it. An ajax call will allow this. Commented Jan 13, 2012 at 20:44
  • what is the result of the php function and what do you want to do with it? Commented Jan 13, 2012 at 20:45
  • The function will not return anything. What it will do is execute a SQL statement "INSERT INTO Categories (catName) VALUES ('".$inCatName."')"; Commented Jan 13, 2012 at 20:47
  • How do I perform an ajax call to this method? Commented Jan 13, 2012 at 20:48
  • this is a dupe of stackoverflow.com/q/7165395/301816 Commented Jan 13, 2012 at 20:48

3 Answers 3

2

Using the Prototype library (www.prototypejs.org):

Javascript:

<script type="text/javascript">
  function toggle()
  {
      var ele = document.getElementById("addCatTextBox");
      var text = document.getElementById("addCatButtonText");
      if(ele.style.display == "block") {
              ele.style.display = "block";
          text.innerHTML = "Save category";

          var options={
            method: 'get',
            parameters: 'inCatName='+ele.value,
            onSuccess: function(xhr) {
                // TODO: Whatever needs to happen on success
                alert('it worked');
            },
            onFailure: function(xhr) {
                // TODO: Whatever needs to happen on failure
                alert('it failed');
            }
          };

          new Ajax.Request('addCategory.php', options);

      }
      else {
          ele.style.display = "none";
          text.innerHTML = "Add new category";
      }
  } 
</script>

addCategory.php:

<?php

$inCatName=isset($_REQUEST["inCatName"]) ? $_REQUEST["inCatName"] : null;

Category::addCategory($inCatName);

?>

The idea is that the Javascript sends a GET (or it could be POST) request to the addCategory.php page behind the scenes, passing it whatever info it needs to create the category.

Hopefully this is enough to get you going. There's a lot missing from my code - you'll need to validate the variables addCategory.php receives and perform any other pertinent security checks before letting it anywhere near the database. addCategory.php will also require any include files, etc so that it knows about your Category class. Finally, addCategory.php should really return some form of variable back to the Javascript code that called it so that it knows what the outcome was.

Sign up to request clarification or add additional context in comments.

17 Comments

Wow, great help. Still trying to understand it. I have implemented your code above and added the includes but its not alerting anything. Any reason?
First off, does the Javascript actually get as far as running the Ajax code? Stick an alert('test'); just before the "var options" line.
I have switched all your Ajax coding to the else part as that is when it should have a value in the text box that is shown. I placed an alert above and below the var options and they both show but when I placed one after the new Ajax part it wont get that far.
Probably a javascript error getting in the way. If you're using IE (shudder), is there a little yellow warning triangle on the status bar that you can click on? If you're using a WebKit browser like Safari or Chrome, fire up the Web Inspector and look a the Console tab (you might need to refresh the page and click your button again to see anything).
Uncaught ReferenceError: Ajax is not defined
|
1

You can use an Ajax request to an endpoint that triggers your PHP and then perform Category::addCategory($inCatName)

With Jquery:

$.ajax({
  url: "addCategory.php",
  context: document.body,
  success: function(){
    // whatever you need to do
  }
});

3 Comments

that assumes the use of jQuery, which based on OP's code sample, is not being used.
yes, its just one example, I have no clue what he's using.
it's a dupe question and I already linked the answer that uses plain javascript.
0

This might help. Use ajax to call you php file (categories.php was used in the example). Send a parameter called "function" and set it as "addCategory". In your php file write code to detect if $_GET['function'] is set and also to detect if it is set as "addCategory". If it is, have the code call the function. I also saw that you were trying to pass the $inCatName parameter to the php function. To send this just add it into the url below.

<script type="text/javascript">
        function toggle()
        {
            var ele = document.getElementById("addCatTextBox");
            var text = document.getElementById("addCatButtonText");
            if(ele.style.display == "block") {
                    ele.style.display = "block";
                text.innerHTML = "Save category";
                var xmlhttp;
                if (window.XMLHttpRequest) {
                    xmlhttp=new XMLHttpRequest();
                } else {
                    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
                }
                xmlhttp.open("GET","categories.php?function=addCategory",true);
                xmlhttp.send();
            }
            else {
                ele.style.display = "none";
                text.innerHTML = "Add new category";
            }
        } 
</script>

1 Comment

This method assumes that you are not using any extra javascript libraries.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.