Javascript function fails with global vars - javascript

I have used this function to submit to any url or 'self',
with or without a querystring, many times without any problems.
function submitu(url, q) {
var frm = document.<?php echo $formname ?>;
if (url == '') {url = '<?php echo $thispage?>'; }
frm.action = url+q; frm.submit(); }
If I try to move the PHP vars outside the function, as below, it stops working (frm undefined error)
var thispage = '<?php echo $thispage?>';
var frm = document.<?php echo $formname?>;
function submitu(url, q) {
if (url == '') {url = thispage;}
frm.action = url+q; frm.submit();}
I also tried var frm = document.forms[''];
I don't have any other conflicting javascript,
(1). Can anyone tell me why this is not working?
(2). And why the first method also fails if the function is placed
inside and at the top of the jquery $(function() {.....} ready function?
Many thanks

It fails because when outside the function, var frm = document.formname;
will be run immediately when the page loads, i.e. before the form element has actually been constructed, so you get 'undefined'. When inside the function, it is only run when the function is run, by which time the DOM is complete and it can find it.

Related

passing data using post array in java-script

i am try to load B.php from A.php after execution in the function and pass some data using a post array from A.php to B.php within same time.
code list as follows
A.php
<script type="text/javascript">
alert_for_the_fucntion();
window.location.href = "B.php";
function alert_for_the_fucntion() {
$.post("B.php", {action: 'test'});
}
</script>
B.php
<?php
if (array_key_exists("action", $_POST)) {
if ($_POST['action'] == 'test') {
echo 'ok';
}
}
?>
for testing purpose i tried to echo something in the B.php. but currently this is not working. have i done any mistakes? or is there any possible method to do this.
Your code does this:
Tells the browser to navigate to B.php (using a GET request)
Triggers a POST request using XMLHttpRequest
The POST request probably gets canceled because the browser immediately leaves the page (and the XHR request is asynchronous). If it doesn't, then the response is ignored. Either way, it has no effect.
You then see the result of the GET request (which, obviously, doesn't include $_POST['action']) displayed in the browser window.
If you want to programmatically generate a POST request and display the result as a new page then you need to submit a form.
Don't use location. Don't use XMLHttpRequest (or anything that wraps around it, like $.ajax).
var f = document.createElement("form");
f.method = "POST";
f.action = "B.php";
var i = document.createElement("input");
i.type = "hidden";
i.name = "action";
i.value = "test";
f.appendChild(i);
document.body.appendChild(f);
f.submit();
If you want to process the results in JavaScript then:
Don't navigate to a different page (remove the line using `location)
Add a done handler to the Ajax code
e.g.
$.post("B.php", {action: 'test'}).done(process_response);
function process_response(data) {
document.body.appendChild(
document.createTextNode(data)
);
}
Try this:
Javascript:
<script type="text/javascript">
window.onload = alert_for_the_fucntion;
function alert_for_the_fucntion() {
$.post("B.php",
{
action: 'test'
},
function(data, status){
if(status=="success"){
alert(data);
}
}
);
}
</script>
PHP
<?php
if(isset($_POST['action'])){
echo $_POST['action'];
}
?>

Retrieve value of a Jquery variable name containing a variable in itself

In the top of my Jquery I've got many variables (associated with values) called : files_1, files_2, etc.
They are created in a script, in the bottom of my page :
<script>
$(function () {
<?php foreach ($folders as $f) { ?>
var files_<?=$f['request_id']?> = 0;
<?php } ?>
…
});
</script>
In my html I've got a link like :
Delete
data-request-id parameter gives me a number, the ones you've got in my variables names on top. In my example, it's data-request-id="2" : files_2.
Next, I've got a Jquery function that catch data values from links :
$('.request-files').on('click', 'a.delete', function (e) {
e.preventDefault();
var $link = $(this);
var $id = $link.data('request-id');
console.log(files_$id); // <-- It doesn't work
});
What I need to do is to retrieve the value of the variables files_x. In my example, I tried to get them using files_$id but it doesn't work.
Any idea ?
If you have your variables defined in the global scrope, they are attached to the window object. So you should be able to access your variables by using bracket notation on the window object:
$('.request-files').on('click', 'a.delete', function (e) {
e.preventDefault();
var $link = $(this);
var $id = $link.data('request-id');
console.log(window['files_' + $id]); // <-- It DOES work
});
UPD: your variables are in the closure of document.ready function ($(function() {...});), so you won't be able to access them from other scopes. I assume that your click handler is within that closure as well. I can suggest creating a separate object with properties named file_<ID> - it will work much alike as with window:
<script>
$(function () {
var filesMap = {};
<?php foreach ($folders as $f) { ?>
filesMap['files_' + <?=$f['request_id']?>] = 0;
<?php } ?>
…
$('.request-files').on('click', 'a.delete', function (e) {
e.preventDefault();
var $link = $(this);
var $id = $link.data('request-id');
console.log(filesMap['files_' + $id]);
});
});
</script>
I am not familiar with PHP, so the string concatenation in request_id part might be different, but the logic remains.

How can I set a javascript boolean variable by a php variable? [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 1 year ago.
I have some information from my db that is being loaded onto my page, but I would like to be able to use an if statement regarding the value of this, and then assign a javascript value to be a boolean value. How can I go about this? (at the moment I am just printing the value)
<?php
if ($_SESSION['loggedin'] = true){
print_r($_SESSION['userlevel']); // THIS IS WHAT I WANT TO SPECIFY IN AN IF STATEMENT
}
?>
<script>
var userloggedin = false;
</script>
What I would like to do in pseudocode:
<script>
var userloggedin = false;
function somefunction(){
if (userloggedin == true){
//Do stuff...//
}
}
</script>
Sorry for my lack of knowledge on the subject, I'm only beginning to learn backend web development.
Have you tried searching the forum for any previous posts with regards to parsing PHP variables to javascript?
With a simple search I found a feed relating to parsing PHP variables to JavaScript here:
Get variable from PHP to JavaScript
Anyway, from my understanding of your problem does this serve as a suitable answer?
<?php
if ($_SESSION['loggedin'] == true){
$userLevel = $_SESSION['userlevel'];
$userLoggedIn = true;
}
else {
$userLevel = null;
$userLoggedIn = false;
}
?>
<script type="text/javascript">
var userLoggedIn = "<?php Print($userLoggedIn); ?>";
var userLevel = "<?php Print($userLevel); ?>";
if (userLoggedIn == true) {
if (userLevel == "levelOne") {
//Your code here
}
else if (userLevel == "levelTwo") {
//Your code here
}
else {
//Your code here
}
}
</script>
You can echo bits of Javascript code from PHP, like this:
<script>
var userloggedin = <?php echo ($_SESSION['loggedin'] ? 'true' : 'false'); ?>;
</script>
First change your if statement to use == double equal signs if you want the expression to work as expected. Then you can simply echo a variable into javascript as in example below:
Simple solution would be similar to:
<?php
if ($_SESSION['loggedin'] == true){
$logged_in = "true";
} else {
$logged_in = "false";
}
?>
<script>
var userloggedin = <?php echo $logged_in;?>;
</script>
You can set a javascript variable with a php value by:
<script>
var jsVar='<?php echo $phpVar ?>';
</script>
A simple solution would be just to echo variable value in script tag. But this is unsafe, because variable is global, meaning it can be modified in client-side console.
Better solution would be an ajax request and php script that returns some response, this way the variable is scoped to ajax response function, so it's safe from modifications. Here's an example:
...
echo json_encode($_SESSION['loggedin'] ? 'true' : 'false');
...
In javascript, you can use jquery .get() request:
$.get("userLoggedIn.php", function(data) {
var response = JSON.parse(data);
if(data === true) {
// user is logged in
}
else {
// not logged in
}
});
If it's important that this functionality is handled before anything else, an synchronous ajax request:
$.ajax({
url: "userLoggedIn.php",
async: false, // this makes request synchronous
success: function (data) {
var response = JSON.parse(data);
if (data === true) {
// user is logged in
} else {
// not logged in
}
});
Synchronous request means that client will wait for request to finish before doing anything else. It's not recommended to be used a lot, but sometimes it's the only way to go about.

Sending multiple GET variables in URL with Javascript

I'm trying to retrieve multiple $_GET variables within PHP. Javascript is sending the URL and it seems to have an issue with the '&' between variables.
One variable works:
//JAVASCRIPT
var price = "http://<site>/realtime/bittrex-realtime.php?symbol=LTC";
//THE PHP END
$coinSymbol = $_GET['symbol'];
echo $coinSymbol
OUTPUT: LTC
With two variables:
//JAVASCRIPT
var price = "http://<site>/realtime/bittrex-realtime.php?type=price&symbol=LTC";
//THE PHP END
$coinSymbol = $_GET['symbol'];
$type = $_GET['type'];
echo $coinSymbol
echo $type
OUTPUT: price
It just seems to ignore everything after the '&'. I know that the PHP end works fine because if I manually type the address into the browser, it prints both variables.
http://<site>/realtime/bittrex-realtime.php?type=price&symbol=LTC
OUTPUT ON THE PAGE
priceLTC
Any ideas? It's driving me nuts - Thanks
UPDATE - JAVASCRIPT CODE
jQuery(document).ready(function() {
refresh();
jQuery('#bittrex-price').load(price);
});
function refresh() {
setTimeout( function() {
//document.write(mintpalUrl);
jQuery('#bittrex-price').fadeOut('slow').load(price).fadeIn('slow');
refresh();
}, 30000);
}
Separate the url and the data that you will be sending
var price = "http://<site>/realtime/bittrex-realtime.php";
function refresh() {
var params = {type:'price', symbol: 'LTC'};
setTimeout( function() {
//document.write(mintpalUrl);
jQuery('#bittrex-price').fadeOut('slow').load(price, params).fadeIn('slow');
refresh();
}, 30000);
}
And in your PHP use $_POST or you can do it like this
$coinSymbol = isset($_POST['symbol']) ? $_POST['symbol'] : $_GET['symbol'];
Refer to here for more information jquery .load()

How to change cookie through Ajax + PHP?

I am trying to modify a Cookie through an Ajax petition but it doesn't work. It modifies the Session but not the cookie. Here is my code:
HTML:
<li class="en_GB" id="1" onclick="changeLanguage('en_GB;1')"><span></span>ENGLISH</li>
Javascript:
function changeLanguage(lang){
$.ajax({
url: 'lib/loadLanguageList.php',
data: {lan: lang},
type: 'POST',
success: function(data){
location.reload();
}
});
}
PHP (loadLanguageList.php) / Action:
if(isset($_POST['lan']) && preg_match("/([a-z]+_[A-Z]+;[0-9]+)/", $_POST['lan'])){
setUserLanguage($_POST['lan']);
}
PHP (loadLanguageList.php) / function EDITED*:
(Following the suggestion of #MikeBrant, I've edited the function)
function setUserLanguage($lan){
$locale['value'] = "";
$locale['id'] = "";
if(isset($lan)){
$lan = explode(";", $lan);
$locale['value'] = $lan[0];
$locale['id'] = $lan[1];
} else if (!isset($_COOKIE["locale"])){
$lan = $this->getUserLanguage();
$locale['value'] = $lan[0]['value'];
$locale['id'] = $lan[0]['id'];
}
setcookie("locale","",time()-2592000);
setcookie("locale_id","",time()-2592000);
setcookie("locale",$locale['value'],time()+60*60*24*30);
setcookie("locale_id",$locale['id'],time()+60*60*24*30);
print_r($locale);
$_SESSION['locale'] = $locale['value'];
$_SESSION['locale_id'] = $locale['id'];
require_once(ROOT."/lib/utils/localization.php");
}
But the cookie is not being deleted and the print_r print $locale variable as it should be. I don't understand why the setcookie function didn't work.
First, let's rewrite your function to where it makes better logic sense in terms of the code path flow (i.e. we have simplified the conditionals).
function setUserLanguage($lan){
$locale['value'] = "";
$locale['id'] = "";
if(isset($lan)){
$lan = explode(";", $lan);
$locale['value'] = $lan[0];
$locale['id'] = $lan[1];
if(!isset($_COOKIE["locale"])){
setcookie("locale",$locale['value'],time()+60*60*24*30);
setcookie("locale_id",$locale['id'],time()+60*60*24*30);
} else {
$_COOKIE["locale"] = $locale['value'];
$_COOKIE["locale_id"] = $locale['id'];
}
} else if (!isset($_COOKIE["locale"])){
$lan = $this->getUserLanguage();
$locale['value'] = $lan[0]['value'];
$locale['id'] = $lan[0]['id'];
setcookie("locale",$locale['value'],time()+60*60*24*30);
setcookie("locale_id",$locale['id'],time()+60*60*24*30);
}
$_SESSION['locale'] = $locale['value'];
$_SESSION['locale_id'] = $locale['id'];
require_once(ROOT."/lib/utils/localization.php");
}
Now let's walk through the use cases here. Let's say the user already has a locale cookie set and they are trying to change it.
This user would pass this conditional:
if(isset($lan))
And should fail this conditional
if(!isset($_COOKIE["locale"]))
This means this code block would be executed:
$_COOKIE["locale"] = $locale['value'];
$_COOKIE["locale_id"] = $locale['id'];
This would change the cookie value for the duration of the script execution only, as nothing in the response to the browser would trigger a change in cookie value.
My guess is that you want to ALWAYS call setcookie().
Also I would think the whole (!isset($lan)) section of code could be removed in favor for throwing some kind of error, as having a "set" function without passing it a value doesn't seem to make much sense.

Categories

Resources