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.

Community
  • 1
  • 1
Ste Prescott
  • 1,789
  • 2
  • 22
  • 43

3 Answers3

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.

  • 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? – Ste Prescott Jan 13 '12 at 21:14
  • First off, does the Javascript actually get as far as running the Ajax code? Stick an alert('test'); just before the "var options" line. – Matt Ralston Jan 13 '12 at 21:23
  • 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. – Ste Prescott Jan 13 '12 at 21:40
  • 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). – Matt Ralston Jan 13 '12 at 21:43
  • Uncaught ReferenceError: Ajax is not defined – Ste Prescott Jan 13 '12 at 21:45
  • Have you included the prototype library? – Matt Ralston Jan 13 '12 at 21:48
  • How would I do that? :-p – Ste Prescott Jan 13 '12 at 21:50
  • Download it from www.prototypejs.org, save it in a directory on your website, then include it on the HTML page with something like . – Matt Ralston Jan 13 '12 at 21:50
  • Thanks, it is now failing saying GET /addCategory.php?catName=undefined 404 (Not Found) It should get a value from ele.value (The textBox) – Ste Prescott Jan 13 '12 at 21:56
  • Sorry, it was pointing to a old file location. It now alerted it worked but it didn't add in the category – Ste Prescott Jan 13 '12 at 21:58
  • The 404 gave a hint - catName=undefined. That comes from ele.value, ele coming from document.getElementById("addCatTextBox"). Does your or – Matt Ralston Jan 13 '12 at 22:03
  • Just found that, it now gets the correct value but it is not adding it into the database. I have tested the SQL statement and its syntax is correct. Any thoughts? – Ste Prescott Jan 13 '12 at 22:10
  • Is the PHP bit working correctly? Try putting /addCategory.php?catName=whatever in the address bar of the browser and pressing enter. Does it create the category, are there any error messages? – Matt Ralston Jan 13 '12 at 22:14
  • Thanks Matt, you have helped greatly. I'm glad there is a great community of experienced developers to help young developers out :-D – Ste Prescott Jan 13 '12 at 22:20
  • Yes, just now need to get it to re-load in the categories (Preferably without refreshing) any ideas? – Ste Prescott Jan 13 '12 at 22:29
  • You could create the relevant HTML tags on the page programmatically in Javascript using the DOM, but that's a real faff. Probably the simplest would be to have a wrap your categories HTML in a
    then add content to the end of that in your javascript. Have a look at http://pastebin.com/ZXPt0wpr
    – Matt Ralston Jan 13 '12 at 23:03
  • Another way would be to have addCategory.php look up all the categories from the database after it has added the new one. The PHP code would then output a HTML version of all the categories. In the onSuccess function in the Javascript, xhr.responseText would contain this HTML which you could then use to overwrite divCategories.innerHTML (i.e. you'd be refreshing the contents of the
    ).
    – Matt Ralston Jan 13 '12 at 23:07
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
  }
});
stevebot
  • 23,275
  • 29
  • 119
  • 181
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>
Shattuck
  • 2,744
  • 4
  • 21
  • 26