Dirty Bird Design
Dirty Bird Design

Reputation: 5533

Passing PHP Result to JS via jQuery .get

I have several instances where a form is brought into the page in an overlay via ajax. On these forms I have a "math validation" question (I know not the most secure). I am using the following to generate the problem:

<?php
    $randomNum = rand(0,9);
    $randomNum2 = rand(0,9);
    $randomNumTotal = $randomNum + $randomNum2;
?>

the random number is displayed in a text box like so:

<input type="text" name="someName" value="<?= $randomNum ?> + <?= $randomNum2 ?>" readonly>

and validated:

...
SomeName: {
    required: true,
    equal: <?php echo $randomNumTotal; ?>   
 }
    ...

This works fine when the form is on the page, hidden and then displayed with a .click function. I would like to store the files remotely and display them via AJAX. No problem doing that, the problem is when I do this, the numbers generated don't match the value. I've tried putting the PHP $randomeNumTotal function on both the form itself that is brought in via AJAX and on the parent page. Neither works.

So my question is this: Can I store the PHP function in a remote file "random.php", then pass the value to it via .get? If so, how do I make "SomeName" value equal the value from the file?

<script>
  $.get( 'random.php', function ( data ) {
    $("SomeName").val('random.php')?//I know this isn't right
 });
</script>

Thanks!

Upvotes: 0

Views: 436

Answers (1)

alex
alex

Reputation: 490263

$.get( 'random.php', function ( data ) {
    $("SomeName").val(data);
});

Should work. Alternatively, you could use jQuery's load() if you wanted to load the content in as the HTML of any element.

Upvotes: 1

Related Questions