how to recover and pass multiple php variables in my AJAX call - javascript

I need to pass my PHP variables defined (earlier in my page) in my Ajax call.
And I have a lot of variables defined so I cannot do it var by var in my code.
My first question is, is there a way in PHP to loop on every defined variable ? like get my $var1, $var2
I think I could do it earlier in my PHP page between <script> tags but this is really not clean.
My AJAX call is like so:
function add_content_in_divs(class_name, target_div) {
var page_name = 'displayer/' + class_name + '_informations.php'
$.ajax({
url:page_name,
type: 'GET',
data: {//need to pass my PHP vars here},
success: function (resp){
target_div.html(resp);
}
})
}
My final goal is to include a part of PHP code in my div, knowing that this include contains $vars defined in my main PHP page. So my includes parts of code doesn't recognize my PHP vars in.
There is an example of code part I have to include.
if (isset($detail)) {
echo '<div class="row"><span class="font-weight-bold">City detail: </span>' . $detail . '</div>';
}

Related

How to Pass PHP Session Variable to external JS file in Symfony

Currently I am working in One PHP Symfony Project Regarding the Performance Evaluation of an Employee.
So I need to know how we can get PHP session variable of an employee (Employee Role) Please see the php file ( $role = $_SESSION['empRole']; ) to an external js file.(js file also attached). I am using PHP Symfony framework.
Actually I need to check who is logged in to the website.if it is admin/core members / Hr.
I need to apply validation to some fileds only when the Coremembers login the website.
Here is the code section that I need to pass $role to External JS file(in pastebin)
public function executeIndex(sfWebRequest $request) {
if (isset($_SESSION['empId'])) {
$role = $_SESSION['empRole'];
if ($role == "admin") {
$empId = $this->getUser()->getAttribute('empId');
$team_members = GroupwareEmployeesPeer::getAllSubordinatesId($empId`enter code here`);
$nc = new Criteria();
$nc->add(PeD`enter code here`ates`enter code here`Peer::NAME, 'Dashboard');
$resultset = PeDatesPeer::doSelect($nc);
So Can you guys give me a solution regarding this, since I am stuck with this for a long time.
Please see thepastebin code for php and external js file.
https://pastebin.com/kbkLjSFa - PHP File.
https://pastebin.com/M60Rg64U - JS file
Yes you can get the php variable into the js file.
Method I:
Rename your .js file to .js.php and pass the php variable as a query string to this file where you link this file in your page.
So, if you have some test.js file, rename it to test.js.php and use it in your page like this
<script src="test.js.php?session_var=<?= $your_var_here;?>&any_var=<?= $any_php_var;?>"></script>
And in your js file, retrieve the values from query string parameters
So inside test.js.php, you can simply
var some_var = "<?= $_GET['session_var']";
var any_var = "<?= $_GET['any_var'];?>";
//rest of your logic goes here
Method II:
Use an AJAX request.
var some_var, another_var;
$.ajax({
url : '/url-which-returns-session-vars', //return the session data in json from this url
asnyc : false,
dataType : 'json',
success : function(res){
some_var = res.some_var;
another_var = res.another_var;
}
});
//rest of the logic goes here.
Both of these methods work. But I prefer the first method, since I don't have to write extra code.
Edit:
Suppose the response of the ajax call looks like this
{
some_var : 'value here',
another_var : 'another value here'
}
So res in the success function argument contains this response and since the response is a JSON you can access these values using the . notation.
Thus,
some_var = res.some_var;
another_var = res.another_var;
and since these variables are global variables, you can use them anywhere in your code in this file.
?> <script> var php_variable = '<?php $variable ?>'; </script> <?php
Global variable should be declared before external js file include . in js file access it using this variable name php_variable
After the above code . jquery external file should be included here
<script src="external.js" ></script>
external.js
consol.log(php_variable);

PHP session variable not persisting through AJAX call

I wanted to use HTML links to change a session variable in PHP. To do this, I set up an HTML "a" tag that would call a javascript function that looks like this:
function changeValue(name){
data = "key='person'&value=" + _name;
$.ajax({
url: www_root + "/funcs.php?func=set_session_var",
type: "post",
data: data,
success: function(data){
console.log(data);
}
});
}
Then, I had the funcs.php script which had the set_session_var function like this:
function set_session_var(){
session_start();
$key= trim($_GET["key"]);
$value= trim($_GET["value"]);
$_SESSION[$key] = $value;
session_write_close();
echo $key;
}
Then, the original php/html page would reload, but it would first load an external page (call it item.php) that settled all of the php session stuff. Looks like this:
session_start()
$session_id = session_id();
$sc = $_SESSION['person'];
However, the $sc variable always shows up as empty, despite the AJAX success function returning the right value. I've checked the session_id's for both scripts, and they are the same. I have also tried to set a session variable in item.php, and it persists. It's just that when I set a session variable using the funcs.php script it doesn't save.
Any and all ideas are appreciated!
You're sending quotes:
data = "key='person'&value=" + _name;
^------^
which means you're effectively doing:
$_SESSION["'person'"] = $value;
^------^-
Note that those single quotes have become PART of the session key name.
Try
data = "key=person&value=" + _name;
^----^--- no quotes
instead.

How to print JavaScript with PHP

I need to pass some JS variable to PHP and am having some trouble.
I have tried the following:
$product_id = "<script> var prod_id_one = $('ul.products li:nth-child(1) a.button').attr('data-product_id')</script>";
echo $product_id;
But this just prints it as a string:
`<script> var prod_id_one = $('ul.products li:nth-child(1) a.button').attr('data-product_id');</script>`
How would I store that JS variable and then echo it using PHP? I am quite new to PHP, so any help would be appreciated!
By doing it your way, it's just impossible. PHP can't "read" or "interact with" javascript directly in the same page.
You have to understand that PHP is a preprocessor, it generates HTML on the server, then the generated page is sent to the client. In this page, the PHP code has entirely disappeared. You can only see what it generated (that is, HTML or JS). Then, the javascript code runs, and it has no idea it was generated using PHP, and no idea of PHP's presence whatsoever.
In order to pass variables to a PHP script, you have to call the file with GET or POST methods :
(JS)
$.get( 'myScript.php', { // This is calling the PHP file, passing variables (use get or post)
variable1 : "Hello",
variable2 : "world!"
}, function(data){ // PHP will then send back the response as "data"
alert(data); // will alert "Hello world!"
});
(myScript.php)
$variable1 = $_GET['variable1']; // or POST if you're using post
$variable2 = $_GET['variable2'];
echo $variable1 . " " . $variable2; // Concatenates as "Hello world!" and prints it out.
//The result of the PHP file is sent back to Javascript when it's done.
Of course, this is a very basic example. Never read and use directly what is sent to PHP (as I just did), because anyone could inject whatever they'd want. Add securities.
JavaScript runs on the client side while PHP runs on the server. They execute at completely different times in the page lifecycle, so they cannot communicate in the manner you have used.
Instead you could to use AJAX to send a value in JS to a PHP page.
Thanks for the assistance, very much appreciated! I have managed to get it done by using ajax as suggested:
<script type="text/javascript">
jQuery("document").ready(function(){
var $ = jQuery
$("form").submit(function(){
var data = "";
data = $(this).serialize() + "&" + $.param(data);
var prod_id_one = $('#prod1').val();
var prod_id_two = $('#prod2').val();
var prod_id_three = $('#prod3').val();
var prod_id_four = $('#prod4').val();
$.ajax({
type: "GET",
url: "my_ajax_url_here",
data: data,
success: function(data){
window.location = "price-calculator?width="+ $('#wpti-product-x').val() + "&height=" + $('#wpti-product-y').val() + "&id1=" + prod_id_one + "&id2=" + prod_id_two + "&id3=" + prod_id_three + "&id4=" + prod_id_four;
}
});
return false;
});
});
</script>
It is now working with the above code. Thanks again!

How to convert javascript variable into php variable?

Im new in programming and Im trying to make a program that would register a selected space in my database. I want to convert js variable str into $phpvar php variable. Please help me
$('#btnShowNew').click(function () {
var str = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
item = $(this).attr('title');
str.push(item);
});
<?php
include "accounts/config.php";
$phpvar='"+str+"';
mysql_query("INSERT INTO sample (sample) VALUES ('".$phpvar."')");
//echo $phpvar;
?>;
})
});
As the previous speakers already explained, you need to think in terms of client-side running code and server-side running code.
Whenever you want to share a state between those two parts of your application you need some communication mechanism.
Client -> Server
For this you need to make a HTTP request. This can either be a post or a AJAX call. For the latter one just have a look at jquery.ajax as you're obviously already using jQuery anyway.
$.post({
"savesample.php",
{myPostVar: str}
}).done(function() {
alert("sample saved.");
});
Of course you need a serverside script to handle this request:
<?php
$yourVar = $_POST["myPostVar"];
// TODO use mysqli::escape_string or similar!!
mysql_query("INSERT INTO sample (sample) VALUES ('".$yourVar."')");
?>
Server -> Client
This is a lot easier. You can of course use ajax again (GET requests on your php file, which generates a nice javascript-compliant output like JSON).
Or just write your variable to an inline-script-tag:
<script>
<![CDATA[
var yourJsvar = '<?= $yourPhpVar ?>';
]]>
</script>
Further Reading
As your php file is an open gate for all kinds of misuse you should secure it using one-time authorization tokens. Once you are used to the basic concepts, go on with the following topics:
CORS
SQL injection
Authenticated AJAX calls
You'll want to POST to a PHP listener. You don't want PHP tags inside of a JS function in this way. The only reason for PHP tags inside of a JS function would be if you were getting data from PHP to JS, not the other way around.
Look up Jquery post for more information.
The order in which languages run is PHP -> HTML -> CSS -> Javascript. You can NOT go backwards from that order.
On the other hand, you can send Javascript information through an AJAX call. AJAX is an Asynchronous Javascript call which can communicate with PHP!
So for instance (using JQuery)
$.ajax({
url:"someurl",
type:"POST or GET",
data:{query:"SELECT * FROM table"}, //Any data to pass along? Like strings or data?
datatype:"JSON", //This is the return type of the information you want if any
success: successfulHandlerfunction()
error: errorHandlerfunction()
});
That is just some basic grounds. You can find more information on AJAX calls through http://www.w3schools.com/ajax/
I hope this helps!
JS
$('#btnShowNew').click(function () {
var str = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
item = $(this).attr('title');
str.push(item);
});
$.ajax({
type: "POST",
url: "save.php",
data: {items: str},
success: function(responce) {
alert(responce);
}
});
});
Create save.php file
<?php
include "accounts/config.php";
$items = $_POST['items']; // Validation HERE!!!
foreach ($items as $item) {
// Insert to DB
}
echo 'Saved';
?>
Separate languages = separate files. (if you can...)
In PHP always check user input.
Use PDO.
This is not possible because the js code is client side and php is server side. What you would need to do is to make an ajax request to a php script in order to send the data for the variable. Here is an example:
Client(browser):
$.ajax({url:"http://domain.com/accounts/config.php?variableToSend=variableValue",success:function(result){
alert("Variable was successfully sent.");
}});
Server(Apache)
config.php
<?php
$varToSend = $_GET["variableToSend"]
//Do whatever you want with the variable
?>

Ajax and rewrite engine

I have a problem with ajax and rewrite engin. I made a site, where I use this load more script:
http://www.9lessons.info/2009/12/twitter-style-load-more-results-with.html
Everything works fine on users profile page (I am getting posts from users feedback), when the url looks like this: example.com/user.php?u=ExampleUser
but I have this in .htaccess:
RewriteRule ^u/(.*) user.php?u=$1 [L]
So if I type something like example.com/u/ExampleUser I get the username like:
$username = $_GET['u'];
But in this way when I click on the load more it doesn't load more posts from the user, it just starts to lead the site itself to the div box (like it is an iframe...).
Please help me, it is necessary.
Here is my script, which should load more info from MySQL database($id is userid from DB):
$(function() {
// More Button
$('.more').live("click",function() {
var ID = $(this).attr("id");
if (ID) {
$("#more" + ID).html('<img src="moreajax.gif" />');
$.ajax({
type: "POST",
url: "ajax_more.php",
data: 'lastmsg='+ID+'&user='+<? echo $id; ?>,
cache: false,
success: function(html) {
$("#container").append(html);
$("#more"+ID).remove();
}
});
} else {
$(".morebox").html('The End');
}
return false;
});
});
Not knowing the entire context of your code, it looks like when the ajax call is made, the final url is something along the lines of domain.tld/u/ajax_more.php.
I get around this issue by maintaining a list of constants in the javascript object.
For example, I have a paths.php file that contains this:
<?php
header("Content-Type: text/javascript");
echo "
myNamespace.paths = {
RELATIVE_FOLDER: '<?=RELATIVE_FOLDER?>',
// add more as required...
}
";
?>
This is included in the page just like a regular script (with script tags), and from that point forward, myNamespace.paths will contain your constants, as returned by the server.
In my case, if the URL was "http://www.example.org/path/to/my/dev/env", I would have RELATIVE_FOLDER set to /path/to/my/dev/env/ on the server-side, which would then be included into the paths object.
Later, in your ajax calls:
$.ajax({
type: "POST",
url: myNamespace.paths.RELATIVE_FOLDER + "ajax_more.php",
// ... everything else
});
I notice you have no problem with directly injecting PHP into your scripts. This is not necessarily a bad thing, but it does make it harder for you to minify your js. This is the reason why I went with a separate file to store the constants, instead of directly injecting it into the javascript itself with <?= ... ?> tags.

Categories