PDA

View Full Version : Assign Jquey value to Php Variable inside jquery function



hemi519
01-21-2014, 02:30 PM
Hi All,

I am struck with some issue in jquery. i want to set a php variable inside jquery. Following is the jquery function i am using

$("#edit").on("click", function() {

var yearss = "2002"; // i will get this value dynimaically

<? $years = ?> yearss; // i don't know how to get this in php

// for some reasons i cant use ajax or json, because i am not sending data to another page, i want that php variable inside this jquery function only

});

Can anyone help me or let me know it can't be achieved this way.

jscheuer1
01-21-2014, 04:02 PM
If I understand what you're asking, it cannot. You will need to setup at least a small external PHP script and use AJAX to have the server set the PHP variable $years and it ($years) will not be available on the current page unless it's either refreshed or queries the server via AJAX for the value, which would have to be stored or passed in some way (as a part of a query string to another PHP page/script or set in a cookie or session variable to survive either process). However, at the same time that you set $years, you can set a javascript variable to the same thing. It will be immediately available on the current page to use for anything you like.

In other words, by the time any click event occurs on the page (in fact, by the time any javascript event occurs or even before anything is parsed by the browser) all PHP variables have already been set and parsed and you cannot go back and change any of them except with AJAX. However, you can change how the page looks using just javascript.

traq
01-21-2014, 06:56 PM
To clarify, you can't "go back and change them" even with ajax: you're actually running that php again; starting over, fresh. Ajax is still your most likely solution, however.


for some reasons i cant use ajax or json, because i am not sending data to another page, i want that php variable inside this jquery function only
That wouldn't prevent you from using ajax. You would, however, need to modify the existing page to be able to respond only to the ajax request when needed, without printing the entire page again. In many cases, it's simply easier to create a separate page to handle the ajax request.

Might I ask for what purpose PHP needs this variable? Might help find a solution, if we knew what the problem was.