0

I've got two pages:

1.php and 2.php

I'm trying to get a PHP variable from 2.php to 1.php through an AJAX request.

This is the script in 1.php

<script>
    jQuery('#refresh').click(function(e){
        e.preventDefault();
        jQuery.ajax({
            type:'POST',
            url: '2.php',
            data: { variable: '<?php echo $PHPvariable ?>' },
            dataType : 'json',
            success:function(response){
                alert(variable);
            }
        })
    });
</script>

For your better understanding, this script is called from within the 1.php file. As you can see I'm trying to retreive the $PHPvariable variable declared in 2.php. Am I doing it correctly??

This is the varialbe delcaration in 2.php

$PHPvariable = 'bla1bla2bla';
$variable = array('PHPvariable ' => $PHPvariable );
echo json_encode($variable);

What is wrong ??

Alex van
  • 187
  • 1
  • 3
  • 12

2 Answers2

0

in 2.php the variable (POST using JS) can be accessed using $_POST['variable']; (in PHP).

sessionVar (JS) in 1.php is undefined (JS), data can be accessed by response.sessionVar (JS) (from success:function(response){).

In 2.php you have to print the data like echo json_encode(array('sessionVar' => $sessionVar)); (PHP).

Update: To prevent confusion I pointed out wether the code parts are PHP or JS.

Update:

You can't expose data and a binary image in a response as there is no multipart response in common HTTP (not sure about SPDY). Either expose an image OR data, not both.

What you can do is to base64 encode the image and output the image as part of the data:

echo json_encode(array(
    'image' => base64_encode($image),
    'variable' => $someVariable),
);

A different approach is not to use ajax but use phps include('2.php'); instead, then the variable is available in 1.php.

Daniel W.
  • 31,164
  • 13
  • 93
  • 151
  • Sorry, you don't get it :P I'm trying to get a $PHPvariable from 2.php to 1.php throught an AJAX request launched from 1.php And then alert it. (Just fixed the wrong alert call) – Alex van Jul 29 '14 at 09:25
  • @Alexvan I got it, don't worry. In 2.php you have to echo the json encoded `$PHPvariable`. – Daniel W. Jul 29 '14 at 09:28
  • Sure now delete my comments and excuse for incovenience – Mirko Cianfarani Jul 29 '14 at 09:30
  • @Alexvan the alert call is still wrong – Daniel W. Jul 29 '14 at 09:30
  • So this is what i wrote in the 2.php file **echo json_encode(array('variable' => $PHPvariable));** so how am i returning it into the 1.php ??? the alert is just to test it – Alex van Jul 29 '14 at 09:31
  • 1
    @Alexvan you return it by the `echo` and you retreive it by `success:function(response)`, your alert is wrong! You can't test with it because `variable` is **`undefined`**. Use `alert(response)` or `console.debug(response)`. – Daniel W. Jul 29 '14 at 10:02
  • @DanFromGermany, ok I modified the alert and added the console.debug as you suggested. But the script is not working still :( So the problem is into something else... – Alex van Jul 29 '14 at 10:06
  • @Alexvan what does 2.php output when you open it in the browser ? (without ajax etc) Can you see the request through the browsers console? (ctrl+shift+i) – Daniel W. Jul 29 '14 at 10:07
  • The 2.php is a file that generates an image with the **imagettftext** function. So the source is interpreted as an image by the **header('Content-Type: image/png');** This file sets a variable as well, I need to get that variable in 1.php... – Alex van Jul 29 '14 at 10:11
  • @Alexvan dude.... that's not possible, there is nothing like "multipart" response. I update my answer. – Daniel W. Jul 29 '14 at 10:13
  • Hum I was afraid of that, so do you have any clues on how to return that variable? I tried to set it as session variable. That works. But 2.php each time it's called generates a new variable that I want to be passed, so if I echo the session variable in 1.php the page itself loads the 2.php page which generates a new variable. And the previously echoed one is wrong... Sorry for the big mess... – Alex van Jul 29 '14 at 10:16
0

For your better understanding, this script is called from within the 1.php file. As you can see I'm trying to retreive the $PHPvariable variable declared in 2.php. Am I doing it correctly??

For passing variable from 1.php and 2.php you have to use the form.

This is a example for the login user

<form action="2.php" method="post">
    <table>
    <tr>
        <td>
            username:
        </td>
        <td>
            <input type="text" name="userName">
        </td>
    </tr>
    <tr>
        <td>
            password:
        </td>
        <td>
            <input type="password" name="password">
        </td>
    </tr>
    <tr>
        <td>
            <input type="submit" name="invio" value="login">
        </td>
    </tr>
    </table>
</form>

Now inside the file 2.php you verification the variable passing.

<?php
ini_set('display_errors', 1);
error_reporting(E_ALL & ~E_NOTICE);

if (isset($_POST['invio']))
    if (empty($_POST['userName']) || empty($_POST['password']))
        $messaggio = "dati mancanti";
    else {
        session_start();
        $_SESSION['userName']  = $_POST['userName'];
        $_SESSION['dataLogin'] = time();
        $_SESSION['ruolo']     = $ruolo[0];

        $messaggio = '<p> <h1 style="color:red">Benvenuto </h1> </p>';


        ;
    }

?>

Now you can print (always inside the page 2.php) the result of message:

<?php
echo $messaggio;
echo $_POST['userName'];
?>

And for return in the page 1.php you can with:

  <?php
header('Location: 1.php');
?>

Inside the script of php.

If you want to use AJAX and without refreshing page I think that you want this exercise

And I suggest for you case this:

var value="your value"
xmlhttp.open("GET","gethint.asp?q="+value,true);

And on gething.php

 <?php
//get the q parameter from URL
 $q=$_GET["q"];

 //lookup all hints from array if length of q>0
 if (strlen($q) > 0)
 {
  echo $q;
}else{
 echo "miss value";
}
?>
Mirko Cianfarani
  • 2,023
  • 1
  • 23
  • 39