TransitDataHead
TransitDataHead

Reputation: 275

Javascript/jquery .load passing variable

Stuck on a jquery/javascript function that is attempting to .load a set PHP script but passing get variable parameters. As an aside this is set to happen automatically after 5 seconds. New to posting here but have read a lot of posts and can't seem to find exactly what I am doing wrong.

This function works:

function LoadMyPhpScript()
{
    $('#MyDiv').load('hello.php');
}
setTimeout(LoadMyPhpScript,5000); 

This function does not work:

function LoadMyPhpScript2(cPhpParamString)
{
    var strURL = 'hello.php';
    strURL = strURL + cPhpParamString;
    $('#MyDiv2').load(strURL);
}
setTimeout(LoadMyPhpScript2('?MyVar1=0&MyVar2=1'),5000); 

Here's the hello.php

<?php
echo '<p>Hello, I am loaded with get values of MyVar1=' . $_GET['MyVar1'] . ', MyVar2=' . $_GET['MyVar2'] . '</p>';
?>

Note: this is just a mock-up, would use regex to validate gets, etc in production.

RESOLVED

Here is what I ended up with, thank you!

function LoadMyPhpScript1(cPhpParamString)
{
    $('#MyDiv1').load('hello.php'+cPhpParamString);
}
setTimeout(function() { LoadMyPhpScript1('?MyVar1=0&MyVar2=1'); },5000); 

Upvotes: 1

Views: 3451

Answers (2)

Hackerman
Hackerman

Reputation: 12295

Better try this way:

File help3.html:

<html>
    <head>
    <script type='text/javascript' src='http://code.jquery.com/jquery-1.8.3.js'></script>
    <script type='text/javascript'>
    function LoadMyPhpScript2(cPhpParamString)
    {
        var strURL = 'help3.php';
        strURL = strURL + cPhpParamString;

      $.ajax({
      url: strURL
      }).done(function(data) { // data what is sent back by the php page
       $('#MyDiv').html(data); // display data
      });


    }
    setTimeout(LoadMyPhpScript2('?MyVar1=0&MyVar2=1'),5000); 

    </script>
    </head>

    <body>

      <div id="MyDiv">

      </div>

    </body>
    </html>

File help3.php:

<?php
echo '<p>Hello, I am loaded with get values of MyVar1=' . $_GET['MyVar1'] . ', MyVar2=' . $_GET['MyVar2'] . '</p>';
?>

Test on my localhost, and both files on the same folder.

Upvotes: 0

Jason P
Jason P

Reputation: 27022

When you do this:

LoadMyPhpScript2('?MyVar1=0&MyVar2=1')

You are executing the function and passing the result to setTimeout

Try this:

setTimeout(function() { LoadMyPhpScript2('?MyVar1=0&MyVar2=1'); },5000); 

However, sending the url querystring like that is an odd way of doing it. Something like this might be better:

function LoadMyPhpScript2(myVar1, myVar2)
{
    var strURL = 'hello.php';
    $('#MyDiv2').load(strURL, { myVar1: myVar1, myVar2: myVar2 });
}
setTimeout(function() { LoadMyPhpScript2(0, 1); },5000); 

Upvotes: 5

Related Questions