Framework: CodeIgniter 2.0
I am trying access session data setup in model from view.
This is the code I am testing in view:
<script type='text/javascript'>
function notEmpty(elem, helperMsg){
var num_records = '$this->session->userdata("number_Of_Records_session")';
alert(num_records);
if(elem.value.length > 0){
alert(helperMsg);
elem.focus();
return false;
}else{
window.location="/path/";
}
return true;
}
</script>
When I use PHP code I could retrieve the value from session and display it.
<?php
$numberOfRecords_session =
$this->session->userdata('number_Of_Records_session');
echo "Num records:".$numberOfRecords_session;
?>
But in javascript this line
var num_records = '$this->session->userdata("number_Of_Records_session")';
print this message in alert box:
$this->session->userdata("number_Of_Records_session")
Any advice to retrieve value in javascript and show it alert box is appreciate.
You cannot access your session (stored on server) from JavaScript (executed on client)
So you have to declare a JavaScript variable and define it with PHP
Like this you're defining a string:
...
<script>
var sessionValue = "<?php echo $this->session->userdata('number_Of_Records_session');?>";
</script>
...
If you're sure that there is always a number you could remove the " above, which are defining the variable as string.
If you're not sure about the datatype of the sessionValue you should use parseInt(string,radix):
...
<script>
var sessionValue = parseInt("<?php echo $this->session->userdata('number_Of_Records_session');?>");
if(sessionValue == "NaN") sessionValue = 0;
</script>
...
Related
I want the value I get in $re variale to use in a Javascript function variable var $r:
<?php
include('functions.php');
if(!isLogIn()){<br>
$_SESSION['msg']="You must log in first";
header('location:login.php');
}
$orderid=$_GET['id'];
$Maxid=mysqli_query($db,"sql query here");
$result=mysqli_fetch_assoc($MAxid);
$re=$result['printst'];
<script type="text/javascript">
function print(){
var $r=<?php $re;?>;
if($r==1){
window.print();}
else{
return false}
you can use echo function to inject php result into javascript as follow:
include('functions.php');
if(!isLogIn()){
$_SESSION['msg']="You must log in first";
header('location:login.php');
}
$orderid=$_GET['id'];
$Maxid=mysqli_query($db,"sql query here");
$result=mysqli_fetch_assoc($MAxid);
$re=$result['printst'];
//assuming this is the javascript part
function print(){
var $r=<?php echo $re;?>;
if($r==1){
window.print();}
else{
return false}
You need to pass that variable to your JS file like this
<script>
var $r= '<?php echo $re; ?>';
</script>
// your js file use that variable
function print(){
if($r==1){
window.print();}
else{
return false}
I'm trying to add ajax autosave to my settings page in plugin and made this code:
<?php
function cfgeo_settings_javascript() { ?>
<script type="text/javascript" >
(function($){
$(document).ready(function(){
$("input[id^='cf_geo_'], select[id^='cf_geo_'], textarea[id^='cf_geo_']").on("change keyup", function(){
var This = $(this),
name = This.attr("name"),
value = This.val(),
data = {};
data['action'] = 'cfgeo_settings';
data[name] = value;
console.log(data);
console.log(ajaxurl);
$.post(ajaxurl, data).done(function(returns){
console.log(returns);
});
});
});
}(window.jQuery));
</script> <?php
}
add_action( 'admin_footer', 'cfgeo_settings_javascript');
function cfgeo_settings_callback() {
global $wpdb; // this is how you get access to the database
var_dump($_POST);
if (isset($_POST)) {
// Do the saving
$front_page_elements = array();
$updates=array();
foreach($_POST as $key=>$val){
if($key != 'cfgeo_settings')
update_option($key, esc_attr($val));
}
echo 'true';
}
else
echo 'false';
wp_die(); // this is required to terminate immediately and return a proper response
}
add_action( 'wp_ajax_cfgeo_settings', 'cfgeo_settings_callback');
?>
I find problem that everytime I want to send this simple ajax request I get 0 what is realy enoying.
Here is Console Log when I try to made some change in select option box:
Object {action: "cfgeo_settings", cf_geo_enable_ssl: "true"}
admin.php?page=cf-geoplugin-settings:1733 /wp-admin/admin-ajax.php
admin.php?page=cf-geoplugin-settings:1736 0
What's wrong in my ajax call or PHP script?
I need to mention that both codes are in the one PHP file.
You should have to follow guideline of WordPress ajax method by this admin ajax reference. Please follow this.
https://codex.wordpress.org/AJAX_in_Plugins
Here is a working example with notes included in the comments, there are a lot of don't does in your code and this example addresses those concerns in the code comments.
https://gist.github.com/topdown/23070e48bfed00640bd190edaf6662dc
If I pass an hard coded numeric value from php to javascript, all works perfectly. But if i pass the numeric value from a variable, i get an error:
javascript file (gallery.js)
function goto_anchor(id)
{
var anchor = $("#anchor_" + id);
$('html,body').animate({
scrollTop: anchor.offset().top - 20
}, 1200);
}
php file
....
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" type="text/javascript"></script>
<script src="js/gallery.js" type="text/javascript"></script><?php
$get_cat = 4;
if (isset($get_cat)) { ?>
<script>
$(document).ready(function() {
goto_anchor(4); // this will work PERFECTLY!!!
goto_anchor(<?php echo $get_cat; ?>); // this will NOT work !!!
});
</script><?php
} ?>
I need to pass the $get_cat variable in my php, not the harcoded numeric value. How ??
Thanks
I have such kind of problems before, can not fill
javascriptfunction(<?php echo $phpvirable ?>)
inside javascript function that causes error; Instead , according to your code, can echo it to javascript virable first before using it;
echo '<script> var get_cat = '.$get_cat.'</script>';
into your php
<?php $get_cat = 4; ?>
surely, Your php $get_cat can be captured from such as $_REQUEST['cat'] dynamic value from form submit event towards this page. then u convert it to javascript virable to use in function.
<?php
if(isset($getcat)):
echo '<script> var get_cat = '.$getcat.'</script>';
endif;
?>
// javascript function read predefined javascript virable that confirm work.
// u also avoid using mixed php and javascript statements which looks messy
<script>
$(document).ready(function() {
goto_anchor(get_cat); // this will work then.
});
</script>
I can do that? Im trying to call a javascript function after conditional php "if"
<script type="text\javascript">
functioncall = (function(id){
alert(id);
});
</script>
<?php
if(isset($_get['id']){
echo "<script>functioncall({$_get['id']});</script>";
}
?>
Use $_GET instead of $_get in php condition, I have corrected some of the errors like script tag script type, and PHP $_GET
<script type="text/javascript">
functioncall = (function(id){
alert(id);
});
</script>
<?php
if(isset($_GET['id'])){
echo "<script>functioncall('{$_GET['id']}');</script>";
}
?>
Or just using JS ?
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
And do like...
var id = getQueryVariable('id');
if(id) {
alert(id);
}
Credit : http://css-tricks.com/snippets/javascript/get-url-variables/
As Quentin said you are exposed to XSS attacks. Don't ever put anything into your page from GET variables (url variables) - 'id' in your case.
Anyways, if you want to call a function based on a php condition, you can do something like this:
<script type="text\javascript">
functioncall = (function(id){
alert(id);
});
</script>
<?php
if(condition-goes-here){
?>
<script type="text/javascript">
functioncall(<?php echo 'Put in your php data' ?>);
</script>
<?php } ?>
I haven't checked it, hope it should work. If your condition returns false, your function call will not be put into your page.
It's not a good practice though.
I have a php page to creates a multi-dimentional array called $results.
I would like to:
catch submit of a form button
override default behavior of the submit using jQuery
copy and process $results on separate php using $.post
I have this which is not currently working and am not sure why?:
<form id='download_to_excel' method="post">
<input type="image" name="submit" value="submit" id='xls_download_button' src='images/common/buttons/download.png'>
</form>
<?php
$json_results = json_encode($results);
?>
<script type='text/javascript'>
$(document).ready(function(){
alert($json_results);
$("#xls_download_button").click(function(e){
alert('clicked');
e.preventDefault();
download_xls();
});
function download_xls(){
$.post('./libs/common/export_data_to_excel.php', {json_data : json_results};
}
});
</script>
When selecting the xls_download_button, the alert() never fires nor does any data get passed to export_data_to_excel.php
The export_data_to_excel.php file has the following:
<?php
$results = json_decode($_POST['json_data']);
#include the export-xls.class.php file
require_once('export-xls.class.php');
$date = date('Y-m-d');
$filename = "contacts_search_$date.xls"; // The file name you want any resulting file to be called.
#create an instance of the class
$xls = new ExportXLS($filename, $results);
#lets set some headers for top of the spreadsheet
$header = "Searched Contact Results"; // single first col text
$xls->addHeader($header);
#add blank line
$header = null;
$xls->addHeader($header);
$header = null;
$row = null;
foreach($results as $outer){
// header row
foreach($outer as $key => $value){
$header[] = $key;
}
// Data Rows
foreach($outer as $key => $value){
$row[] = $value;
}
$xls->addRow($header);//add header to xls body
$header = null;
$xls->addRow($row); //add data to xls body
$row = null;
}
# You can return the xls as a variable to use with;
# $sheet = $xls->returnSheet();
#
# OR
#
# You can send the sheet directly to the browser as a file
#
$xls->sendFile();
?>
I do know that the $json_results does display proper JSON encoded values when echoed. But from there are not sure why the rest of the javascript does not run; the alerts never fire nor does the JSON data get passed?
Can you see why this isn't working?
Your PHP-supplied json is not stored as a javascript variable in your js.
$(document).ready(function(){
var json_results = <?php echo $json_results; ?>;
...
This code shouldn't run:
function download_xls(){
$.post('./libs/common/export_data_to_excel.php', {json_data : json_results};
}
It is invalid (the ; doesn't belong there). Try this code:
function download_xls(){
$.post('./libs/common/export_data_to_excel.php', {json_data : json_results});
}
Right now you are just setting a php variable called $results you need to transfear it to you javascript.
<script type="text/javascript">
// set javascript variable from php
var $results = "<?php echo json_decode($json_data); ?>";
</script>
For sure you have an error in your javascript code (you were not closing the parenthesis after $.post), should be:
$(document).ready(function() {
alert($json_results);
$("#xls_download_button").click(function(e) {
alert('clicked');
e.preventDefault();
download_xls();
});
function download_xls() {
$.post('./libs/common/export_data_to_excel.php', {
json_data: json_results
});
}
});
Then you should assign your JSON to a javascript variable inside document.ready
$(document).ready(function() {
var json_results = <?php echo($json_results);?>;
You can't pass a PHP variable to the JavaScript like that: there live in totally different worlds. Use Ajax to get the JSON data from JS.