Pass PHP Variable into Java Script window.location - php

I am trying to pass a php variable into a java script window.location that returns a user to the current list view after deleting an item from the database. I can't seem to get the syntax correct.
Code:
function confirmation(a) {
var currString = "<? echo $currString ?>";
var answer = confirm("Are you sure you want to delete this item?")
if (answer){
alert("The item has been deleted")
window.location = "list.php?s='. $currString .'&=delete=true&id=" + a;
}
else{
alert("The item has not been deleted")
}

Try this:
function confirmation(a) {
var currString = "<?php echo $currString ?>";
var answer = confirm("Are you sure you want to delete this item?");
if (answer){
alert("The item has been deleted")
window.location = "list.php?s=" + currString + "&=delete=true&id=" + a;
}
else{
alert("The item has not been deleted");
}

you are pasing php variable to JS variable
var currString = "";
and in window.location you are passing again php variable which is wrong,
so do it like this
window.location = "list.php?s=" + currString + "&=delete=true&id=" + a;

The syntax issue was solved by other answers, but you need to take care of an additional issue: URI encoding your variable when you use it in the URL:
window.location = "list.php?s="
+ encodeURIComponent(currString)
+ "&=delete=true&id=" + a;
or else you will run into problems of your variable contains characters like &.

echo "<script>alert('System info has been Save')</script>";
echo "<script>window.location='customer_detail.php?
customer_id=".$customer_id."'</script>";

Related

redirect to page in php using jquery

I am trying to redirect to same page in php using jquery as below:
echo "<script>
var url = window.location.href + '?a=eud';
alert(url);
$(location).attr('href',url);
</script>";
When I execute above, I am getting alert message, but its not redirecting.
Sorry if its a dumb query, but i am new to php and having basic knowledge on jquery.
You were almost there, you just have to get the PHP to echo the actual redirect command:
echo"
<script>
var url = window.location.href + '?a=eud';
location.href = url;
</script>";
You can use
window.location = url;
try this
echo "<script>
var url = window.location.href + '?a=eud';
window.location = url;
</script>";
echo"<script>
var url = window.location.href + '?a=eud';
window.location.replace(url);
</script>";

Can I put store a string in jquery ajax like this?

See the code below. I don't know if that possible or not, I have a string like $id in my search.php, I want to put it into bp_core_get_user_domain(), the reason I need to do that because bp_core_get_user_domain() is not working in my search.php.
$.post("search.php",
{
search_text: $(".result_tag").text()
},
function(data)
{
var $user_link="<?php echo bp_core_get_user_domain(can I put a string here? )?>";
$("#result").html($user_link)
});
try this
var $user_link = "<?php echo bp_core_get_user_domain('" + your_string_here + "') ?>";

Use a PHP variable inside a jquery click()?

I have this,
$(document).ready(function(){
$('#link').click(function(){
var user_login = <?php $base_url; ?>;
window.location = user_login + '/login';
});
});
note that $base_url is global variable. This works in FF but not on Chrome and IE. Thanks.
You need to add quotes around the php tags to designate that the value of $base_url is a string:
$(document).ready(function(){
$('#link').click(function(){
var user_login = "<?php echo $base_url; ?>";
window.location = user_login + '/login';
});
});
That way, when the browser gets this block, it will look something like:
$(document).ready(function(){
$('#link').click(function(){
var user_login = "http://www.example.com"; // after php is executed
window.location = user_login + '/login';
});
});
You need to echo the variable, not just simply have it in a code block. And for safety, to prevent introducing JS syntax errors, you should json-encode the value:
var login = <?php echo json_encode($base_url); ?>;
See below, note the quotes around the PHP echo
$(document).ready(function(){
$('#link').click(function(){
var login = '<?php echo $base_url; ?>';
window.location = user_login + '/login';
});
});
I suppose its a PHP file, you need to surround your variable contents by quotes to javascript
$(document).ready(function(){
$('#link').click(function(){
var login = <?php '\''.$base_url.'\''; ?>;
window.location = user_login + '/login';
});
});
Run this script in a PHP file, not in a .js file, and don't forget tho ECHO your variable and add quotes (in javascript), as said in other answers !

How to access PHP session variables from jQuery function in a .js file?

How to access PHP session variables from jQuery function in a .js file?
In this code, I want to get "value" from a session variable
$(function() {
$("#progressbar").progressbar({
value: 37
});
});
You can produce the javascript file via PHP. Nothing says a javascript file must have a .js extention. For example in your HTML:
<script src='javascript.php'></script>
Then your script file:
<?php header("Content-type: application/javascript"); ?>
$(function() {
$( "#progressbar" ).progressbar({
value: <?php echo $_SESSION['value'] ?>
});
// ... more javascript ...
If this particular method isn't an option, you could put an AJAX request in your javascript file, and have the data returned as JSON from the server side script.
I was struggling with the same problem and stumbled upon this page. Another solution I came up with would be this :
In your html, echo the session variable (mine here is $_SESSION['origin']) to any element of your choosing :
<p id="sessionOrigin"><?=$_SESSION['origin'];?></p>
In your js, using jQuery you can access it like so :
$("#sessionOrigin").text();
EDIT: or even better, put it in a hidden input
<input type="hidden" name="theOrigin" value="<?=$_SESSION['origin'];?>"></input>
If you want to maintain a clearer separation of PHP and JS (it makes syntax highlighting and checking in IDEs easier) then you can create JQuery plugins for your code and then pass the $_SESSION['param'] as a variable.
So in page.php:
<script src="my_progress_bar.js"></script>
<script>
$(function () {
var percent = <?php echo $_SESSION['percent']; ?>;
$.my_progress_bar(percent);
});
</script>
Then in my_progress_bar.js:
(function ($) {
$.my_progress_bar = function(percent) {
$("#progressbar").progressbar({
value: percent
});
};
})(jQuery);
You can pass you session variables from your php script to JQUERY using JSON such as
JS:
jQuery("#rowed2").jqGrid({
url:'yourphp.php?q=3',
datatype: "json",
colNames:['Actions'],
colModel:[{
name:'Actions',
index:'Actions',
width:155,
sortable:false
}],
rowNum:30,
rowList:[50,100,150,200,300,400,500,600],
pager: '#prowed2',
sortname: 'id',
height: 660,
viewrecords: true,
sortorder: 'desc',
gridview:true,
editurl: 'yourphp.php',
caption: 'Caption',
gridComplete: function() {
var ids = jQuery("#rowed2").jqGrid('getDataIDs');
for (var i = 0; i < ids.length; i++) {
var cl = ids[i];
be = "<input style='height:22px;width:50px;' `enter code here` type='button' value='Edit' onclick=\"jQuery('#rowed2').editRow('"+cl+"');\" />";
se = "<input style='height:22px;width:50px;' type='button' value='Save' onclick=\"jQuery('#rowed2').saveRow('"+cl+"');\" />";
ce = "<input style='height:22px;width:50px;' type='button' value='Cancel' onclick=\"jQuery('#rowed2').restoreRow('"+cl+"');\" />";
jQuery("#rowed2").jqGrid('setRowData', ids[i], {Actions:be+se+ce});
}
}
});
PHP
// start your session
session_start();
// get session from database or create you own
$session_username = $_SESSION['John'];
$session_email = $_SESSION['johndoe#jd.com'];
$response = new stdClass();
$response->session_username = $session_username;
$response->session_email = $session_email;
$i = 0;
while ($row = mysqli_fetch_array($result)) {
$response->rows[$i]['id'] = $row['ID'];
$response->rows[$i]['cell'] = array("", $row['rowvariable1'], $row['rowvariable2']);
$i++;
}
echo json_encode($response);
// this response (which contains your Session variables) is sent back to your JQUERY
You cant access PHP session variables/values in JS, one is server side (PHP), the other client side (JS).
What you can do is pass or return the SESSION value to your JS, by say, an AJAX call. In your JS, make a call to a PHP script which simply outputs for return to your JS the SESSION variable's value, then use your JS to handle this returned information.
Alternatively store the value in a COOKIE, which can be accessed by either framework..though this may not be the best approach in your situation.
OR you can generate some JS in your PHP which returns/sets the variable, i.e.:
<? php
echo "<script type='text/javascript'>
alert('".json_encode($_SESSION['msg'])."');
</script>";
?>
This is strictly not speaking using jQuery, but I have found this method easier than using jQuery. There are probably endless methods of achieving this and many clever ones here, but not all have worked for me. However the following method has always worked and I am passing it one in case it helps someone else.
Three javascript libraries are required, createCookie, readCookie and eraseCookie. These libraries are not mine but I began using them about 5 years ago and don't know their origin.
createCookie = function(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
}
else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
readCookie = function (name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
eraseCookie = function (name) {
createCookie(name, "", -1);
}
To call them you need to create a small PHP function, normally as part of your support library, as follows:
<?php
function createjavaScriptCookie($sessionVarible) {
$s = "<script>";
$s = $s.'createCookie('. '"'. $sessionVarible
.'",'.'"'.$_SESSION[$sessionVarible].'"'. ',"1"'.')';
$s = $s."</script>";
echo $s;
}
?>
So to use all you now have to include within your index.php file is
$_SESSION["video_dir"] = "/video_dir/";
createjavaScriptCookie("video_dir");
Now in your javascript library.js you can recover the cookie with the following code:
var videoPath = readCookie("video_dir") +'/'+ video_ID + '.mp4';
I hope this helps.
Strangely importing directly from $_SESSION not working but have to do this to make it work :
<?php
$phpVar = $_SESSION['var'];
?>
<script>
var variableValue= '<?php echo $phpVar; ?>';
var imported = document.createElement('script');
imported.src = './your/path/to.js';
document.head.appendChild(imported);
</script>
and in to.js
$(document).ready(function(){
alert(variableValue);
// rest of js file

include path and ajax not working?

I couldn't get "castMyVote" function to execute. It worked when I cast a vote in poll.php but not in index.php. I have ensure all php and js are in correct path. I tried another function "displayvotewithoutvote" in Index.php, I could display statistic without vote.
index.php:
include('poll.php');
poll.php:
<img src="images/vote_button.gif">
ajax.js:
function castMyVote(pollId,formObj)
{
var elements = formObj.elements['vote[' + pollId + ']'];
var optionId = false;
**for(var no=0;no<elements.length;no++){
if(elements[no].checked)optionId = elements[no].value;
}**
Poller_Set_Cookie('dhtmlgoodies_poller_' + pollId,'1',6000000);
if(optionId){
var ajaxIndex = ajaxObjects.length;
ajaxObjects[ajaxIndex] = new sack(); //an api from simple ajax code kit
ajaxObjects[ajaxIndex].requestFile = serverSideFile + '?pollId=' + pollId + '&optionId=' + optionId;
prepareForPollResults(pollId);
ajaxObjects[ajaxIndex].onCompletion = function(){ showVoteResults(pollId,ajaxIndex); }; // Specify function that will be executed after file has been found
ajaxObjects[ajaxIndex].runAJAX(); // Execute AJAX function
}
}
Update: in ajax.js as showing above, it doesn't response after I include alert after, I afraid something wrong here:
for(var no=0;no<elements.length;no++){
if(elements[no].checked)optionId = elements[no].value;
}
Please try this code in your poll.php
<img src="images/vote_button.gif" onclick="castMyVote(<?php echo $pollerId;?>,document.forms[0])">
This may help you.
Thanks,
Kanji
are you getting the pollid in the js?
var pollid="";
onclick="castMyVotepollid,....
try this

Categories