2

Couple questions:

1) I'm trying to have a new random value updated each time a button is pressed. When the button is clicked, a value is generated once... but is not random. So I'm not sure if the function is being called again on click because a new value isn't generated.

2) Can I include the php code within the same file as the jquery when using a server call such as $.get() and call it as a function within that same file?

The reason is, I don't want to have to keep creating new php script files, and would rather throw the code in the same file as the calling jquery.

Meaning...

Instead of $.get("../scripts/NameGenerator2.php",

I do this: $.get("a php function within this same file",

JQuery:

<?php 
   if ($imgid == 1) {
?>
<button onclick="generate()">Generate</button>

<button id="generateButton">Generate</button>

<script type="text/javascript">
    $(document).ready(function() {
        $("#generateButton").click(function(e) {
            //alert("called");
           $.get("../scripts/NameGenerator2.php", 
                function(returned_data) {
                    $("#generated").html(returned_data);
                }
            ).error(function(jqXHR, status, error) {
                console.log("error in $.get")
            });
        });
    });
</script>       
<?php } ?>
<br /><span id="generated"></span><br />

PHP:

<?php 
$adj = array("Happy", "Great", "Mandarin", "New", "Golden", "Ming's");
$noun = array("Dragon", "Sea", "Wok", "Fortune", "Rice", "Empire");
$place = array("Garden", "China", "Village", "Palace", "Kitchen", "Mountain");


$x = rand(0, count($adj)-1);
$y = rand(0, count($noun)-1);
$z = rand(0, count($place)-1);

echo '<p>' . $adj[$x] . " " . $noun[$y] . " " . $place[$z] . '</p>';

?>

Any thoughts? Thanks!

Updated: Only error I seem to be getting is "Object Expected" in my "myJquery.js" file, which is not the file I'm working in, and doesn't seem connected.

enter image description here

When I add in document ready to my function, the button onclick() call seems to break.

enter image description here

15
  • I updated my answer, but all of your jQuery functions need to be in your document ready handler. there are no functions in your document ready handler. Commented Dec 19, 2012 at 19:05
  • @JayBlanchard I thought that handler was optional, or you could multiple instances of it. Commented Dec 19, 2012 at 19:08
  • It is only optional if the jQuery is near the bottom of the page to insure that the DOM elements exist before the jQuery code is called. You can have multiple instances but you do not. Commented Dec 19, 2012 at 19:11
  • @JayBlanchard also, adding that handler seems to break my button onclick="generate()" call, saying "Object Expected". see above Commented Dec 19, 2012 at 19:12
  • 1
    Yes, you can position the button using CSS. Take out your console.log statements (IE chokes on these) and it should work. Commented Dec 19, 2012 at 20:06

2 Answers 2

3

You can call a .php-file with jQuery. But the file should be reachable with your browser and should return qualified data.

With .get() you can define the expected data-type. It can be xml, json, script, or html. If you want to use json (my favourite) the use the php-function json_encode to generate the output.

If you want to use the same file, create a GET-Parameter e.g. ?ajax=1. With your AJAX-request you call the file and append the GET-Parameter. And in your .php-File you can then switch between an normal call and an ajax call which returns an other output.

<?php
    if (!empty($_GET) && !empty($_GET['ajax']) && $_GET['ajax'] == 1) {
        // header("Content-type: application/json");
        // $data = array(some_data);
        // echo json_encode($data);
        echo 'AJAX-call-output';
    } else {
?>
        <!-- [...] -->
        <script type="text/javascript">
            function generate() {     
               $.get("../scripts/NameGenerator2.php",
                    { ajax: 1 },  // GET-Parameter
                    function(returned_data) {
                        //alert("test");
                        $("#generated").html(returned_data);
                    }
                    //, "json"
                );
            }
        </script>
        <!-- [...] -->
<?php
    }
?>
Sign up to request clarification or add additional context in comments.

1 Comment

I get the idea of what you're saying. Can you perhaps provide a quick example?
1

You cannot get a PHP function but you can load the page and get a specific div -

$('#generated').load('../scripts/NameGenerator2.php #pagePart');

You echo out PHP with the proper id's in place, for instance -

echo '<p id="pagePart">' . $adj[$x] . " " . $noun[$x] . " " . $place[$x] . '</p>';

Without using any inline JavaScript this is what your jQuery code might look like -

<button id="generate">Generate</button>

$(document).ready(function() {
    $('#generate').click(function(e){
        e.preventDefault();
        $('#generated').load('../scripts/NameGenerator2.php #pagePart');
    });
});

Based on your update you need to move all of your jQuery functions into the document ready function.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.