-5

I am having trouble trying to append a number to the end of a PHP variable. The problem is because the number I am trying to append is stored in a Javascript variable. Here is my code:

fields.eq(n).attr('value', "<?php echo $_SESSION['fname_" + countItem + "'] ; ?>");

This is not working. I need the number stored in the Javascript variable countItem to append to the end of the $_SESSION variable. The final $_SESSION variable should look like this: $_SESSION['fname_1']. Is there a way of doing this? Thanks

5
  • You want to do this on the server or the client? Commented Dec 4, 2012 at 21:56
  • @Diodeus this would be done in a .php file although most of the file is javascript/ Commented Dec 4, 2012 at 21:57
  • 1
    PHP runs on the server first. Then the server sends the output as HTML/Javascript to the browser, where the Javascript is executed. What you want is impossible. Look into AJAX. Commented Dec 4, 2012 at 21:58
  • You need to use ajax if you want do this by javascript, there's any possibility of making the count in php? Commented Dec 4, 2012 at 21:59
  • three3: you really need to read this: webdevelopersnotes.com/basics/client_server_architecture.php3 Commented Dec 4, 2012 at 21:59

2 Answers 2

0

The problem here is the order that this page is parsed. The PHP will first render the page on the server and then send to the browser. The javascript is then executed on the client-side.

Think of it like this. Anything in-between the

echo $_SESSION['fname_" + countItem + "'] ;

I'm surprised this isn't throwing an error?

What do you actually need to do (the bigger picture). It looks like you are looping and creating several elements. If this is the case you should use PHP to do all of this?

If not then maybe you can use AJAX to call a PHP page that will provide the values from the session.

1
  • The reason it is not throwing an error is because I have changed the .js extension to a .php extension. Yes, you are correct. When a uses clicks a certain button on the site, it adds new fields to the page using javascript. I am trying to pre-populate the newly added fileds with the PHP $_SESSION variable. Commented Dec 4, 2012 at 22:04
0

PHP is a server side language, once the page is parsed, the output is sent to the browser and that's it. So when your page loads, you are calling:

$_SESSION['fname_']; 

You will need to use AJAX to make a call to the server again. You can then pass the javascript variable to the server and do what you need.

Have a look at: http://api.jquery.com/jQuery.get

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.