Calling javascript from php script issue - php

I have a php script which is editing records in mysql table. I have an issue in refreshing the page using javascript by passing the record number.
Pl check below are the few lines of my php script:
if ($mode == "edit")
{
$ids=$_POST[prs_rid];
$edt1=mysql_query("SELECT * FROM ECRDTL_edit WHERE id='$ids'");
$edt2=mysql_fetch_assoc($edt1);
echo "<script>var x=document.getElementById('prs_rid').value</script>";
echo "<script> alert (x);</script>";
echo "<script>document.location.href='ecr-detail-edit.php?prs_mode=edit&prs_id='+x;</script>";
}
I have used alert to see if variable "x" is getting the record value or not, this works fine. But when i use the same in the next line, it is not showing the same record in the edit mode of my php.
But if I put the same line in address bar of a browser like this, it works fine:
http://www.mydomain.com/ecr-detail-edit.php?prs_mode=edit&prs_id=27
Kindly check what could be the issue or is there any other way of refreshing the page passing the record number.

Just use the location.href object which (as specified in MDN window.location) belongs to the window object, not document.
So your last line of code should read like:
echo "<script>location.href='ecr-detail-edit.php?prs_mode=edit&prs_id='+x;</script>";
On another note, you will get better browser support using the script tags as <script type="text/javascript">

Relative URL's don't work when assigned to location.href, it should be absolute or fully qualified.
In your case, absolute will do:
location.href = location.pathname + '?prs_mode=edit&prs_id=' +
encodeURIComponent(x)
The location.pathname gives the path (starting with /) up to the query separator (question mark).
I've also added encodeURIComponent(x) to make sure the value of x is properly escaped if necessary.
Implementation
echo "<script>location.href = location.pathname + '?prs_mode=edit&prs_id=' + encodeURIComponent(x);</script>";

The problem is that window.location needs an absolute, http:// URL. Use the following code:
window.location=window.location=location.protocol+'//'+location.host+location.pathname+"?get_variables_here";

document.location.href='ecr-detail-edit.php?prs_mode=edit&prs_id='+x;
should be
location.href='ecr-detail-edit.php?prs_mode=edit&prs_id='+x;
and also you should use mysql_real_escape_string() to escape malicious data user may pass on to your script.
hence change
$ids = $_POST['prs_rid'];
to
$ids = mysql_real_escape_string($_POST[prs_rid]);
you are missing script type, when you want to use javascript you need to tell to browser that the code being declared is of javascript, you need to change
<script>
to
<script type="text/javascript">
you are missing single quotes in your POST data. add single quotes to the following.
$ids = $_POST['prs_rid'];
one last thing is i would never output javascript with PHP. it is better you keep javascript and PHP different. for example your above code can be changed to.
<?php
if ($mode == "edit"):
$ids = mysql_real_escape_string($_POST['prs_rid']);
$result = mysql_query("SELECT * FROM ECRDTL_edit WHERE id='$ids'") or die(mysql_error());
$row = mysql_fetch_assoc($result);
?>
<script type="text/javascript">
var x = document.getElementById('prs_rid').value
alert(x);
location.href = 'ecr-detail-edit.php?prs_mode=edit&prs_id='+x;
</script>
<?php endif; ?>

Try this..
echo "<script type='text/javascript'>window.location.href='ecr-detail-edit.php?prs_mode=edit&prs_id='+x;</script>";

For this line to execute successfully, var x=document.getElementById('prs_rid').value in PHP, the html dom should be loaded first else it will give an error, which might be the issue here.

Related

setting and getting session variables

I am trying to set a session variable in a php script and get the variable in
a javaScript.
In the php program I put an echo command to see if the variable
is generated. Nothing happens.
In the javascript I try to write the variable to the screen and I see nothing. If I put single quotes around the get command I just get a display of that command.
php:
$full_name = $_POST['Full_Name']; // required
$names = explode(" ", $full_name);
$_SESSION['myvar'] = $names[0];
echo ($names[0]);
javascript:
<script type="text/javascript">
var name = #Session["myvar"];
document.write(name);
</script>
Direct use of PHP in a JS-script is really not useful if you want to make it scalable.
Use it like this
myprintoutscript.js
function writeOnDocument(name){
document.write(name);
}
In most cases it is better to call a js-function from the outside with a variable (in your case the session)
index.php
<script>
//referencing to function in myPrintOutScript.js
writeOnDocument("<?= $_SESSION['myvar'] ?>");
</script>
Or readout a html data-attribute, for example a body
index.php
<body data-session-name="<?= $_SESSION['myvar'] ?>">
and call it from a script:
windowIsLoadedScript.js
var body = document.getElementsByTagName("BODY")[0],
name = body.getAttribute("data-session-name");
//referencing to function in myPrintOutScript.js
writeOnDocument(name);
The more you keep things separated, the easier it is to make your building blocks stack on to each other.
Writing JavaScript with PHP...hmmm...as a programmer that has inherited code where other programmers did this...Please don't. It's hard to see what's going on when you start mixing languages together.
As to your actual problem...generally, you put stuff into the Session that you want to keep "secret", or stuff that you have already properly secured, like the User's ID value of who is logged in so that when they go to the next page, you see the User ID in a session and you trust that data because it came from your server rather than the user. POST, GET, and COOKIE data is insecure, so you don't trust what the user is sending you.
In any case, for stuff that you want to be accessible to both PHP AND Javascript, if you're not using web services, I would suggest using cookies might be the better practice.
setcookie('FirstName',$_SESSION['myvar']);
http://php.net/manual/en/function.setcookie.php
Admittedly, getting cookie values with JavaScript is a pain in itself, but people have already written the code for you, so it shouldn't be as painful:
Get cookie by name
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
var name = getCookie('FirstName');
[EDIT] I would also say that the other poster's answer, putting it into a data-attribute within the HTML, is also a good practice and more clear than writing to JS directly.
<body data-first-name="<?php echo htmlspecialchars($firstName) ?>">
write session_start(); at the starting of the php file.
then catch the variable into js like this.
<script type="text/javascript">
var name ="<?php echo $_SESSION['myvar'];?>";
document.write(name);
</script>

Javascript document.write overwriting a php page

I have this Javascript function:
function capitalizeFL(string) { //takes a string, returns it with first letter capitalized
return string.charAt(0).toUpperCase() + string.slice(1);
}
A file called statuswindow.php, which includes the following:
<?php
$raceV = "<script>document.write(capitalizeFL(\"".$player->race."\"));</script>";
$clasV = "<script>document.write(capitalizeFL(\"".$player->clas."\"));</script>";
echo "You have chosen a " . $raceV. " " .$clasV ."!";
?>
Now the main file, which uses ajax to update and show the player's class and race ($clas, $race), after capitalizing their first letters using capitalizeFL:
Main file includes the following:
$("button").click(function() {
$("#topMenu").load("statuswindow.php");
});
What I would LIKE to happen, is that the html from statuswindow.php will be properly displayed in the main window's #topMenu div.
I'm assuming the problem is due to document.write overwriting the whole page. The question is, how can I do the following, without using document.write?
You can not use document.write after page load. what it does is opens up a new document and replaces what ever you have there with new content.
In this example there is no need to even use document.write. Just use the script tags. jQuery will handle the script tags for you.
You really should just skip using load and use $.get or $.getJSON and handle the response yourself.
Have the server return a JSON object.
{
raceV : "foo",
clasV : "bar",
outStr : "You have chosen a {1} {2}!"
}
and the JavaScript would be
$.getJSON("statuswindow.php", function(data) {
var outString = data.outStr;
outString = outString.replace("{1}",capitalizeFL(raceV));
outString = outString.replace("{2}",capitalizeFL(clasV));
$("#topMenu").html(outString );
})
BUT the real issue is:
Why are you not doing all of this in PHP. There is no reason for JavaScript to do it.
No JavaScript needed!
<?php
$raceV = ucfirst($player->race);
$clasV = ucfirst($player->clas);
echo "You have chosen a " . $raceV. " " .$clasV ."!";
?>
and the jQuery load would be the same
$("#topMenu").load("statuswindow.php");
echo "You have chosen a ".ucFirst($player->race)...
Would make more sense
When you use $.load you do not really want any scripts in the page you load and in this case there is absolutely zero reason to have javascript uppercase the first letter when php has a built-in function to do it
I'm assuming the problem is due to document.write overwriting the whole page. The question is, how can I do the following, without using document.write?
Because is exactly what document.write does.
Try with innerHTML:
For example, if you want to add content to #topMenu, just do:
document.getElementById('topMenu').innerHTML += capitalizeFL(".$player->race.");

get #var from url in php code error

i want to get #var value from url like my url is mydomain.com/index.php#1 so i want to get has(#) value from url which is 1 after some research i got this article http://www.stoimen.com/blog/2009/04/15/read-the-anchor-part-of-the-url-with-php/
i use this code for get has(#) value, this is work fine in JavaScript but this is not work in php my code is :
<script language="javascript">
var query = location.href.split('#');
document.cookies = 'anchor=' + query[1];
alert(query[1]);
</script>
<?php
echo $_COOKIE['anchor'];
?>
this code give me alert value in JavaScript but not echo value. any solution for that ?
Additionally, you seem to set wrong property in JS (it's .cookie, not .cookies):
document.cookie = 'anchor' + query[1];
The cookie you are setting will not be visible to PHP until the next page request. The article you link to states this explicitly:
Of course, yes. This is not working correctly. In fact it’s working
correctly from the second load on, but on the initial load of the page
the $_COOKIE array does not has any anchor key inside. That’s because
this part of the code is executed before the browser setup the cookie
on the client.
There is a "workaround" presented in that article, but frankly: this sort of thing is rubbish and you should simply not put this information (only) in the query fragment if you want PHP to read it.
By article which you sent, you must do a redirect like:
<?php if (!$_COOKIE['anchor']){ ?>
<script language="javascript">
var query = location.href.split('#');
document.cookie = 'anchor=' + query[1];
window.location.reload();
</script>
<?php } ?>
<?php
echo $_COOKIE['anchor'];
?>
You are setting a cookie that wont be passed to php until next reload. Am I wrong?
Client dynamics is the end of the chain.
Use this method to prevent errors:
<script>
query=location.hash;
document.cookie= 'anchor'+query;
</script>
And of course in PHP, explode that puppy and get one of the values
$split = explode('/', $_COOKIE['anchor']);
print_r($split[1]); //to test it, use print_r. this line will print the value after the anchortag

Javascript does not allow me to set variable with PHP?

I have done this several times before but am wondering if perhaps there is a conflict with my bitly class.
I use php to generate a bitly url from long ones. This is stored in a variable called
$url
I can echo the $url variable and know it works fine. However, when I try and place the into the following javascript function (which is called onclick event), the entire action fails.
function fbs_click() {
var uf="<?php echo $url; ?>";
var tf=document.title;
window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(uf)+'&t='+encodeURIComponent(tf),'sharer','toolbar=0,status=0,width=626,height=436');
return false;
}
if I replace with an actual URL, i have no problems. Even if I replace with the word "blah", it works. Something about the php echo is throwing it for a loop.
The php echo renders this is source:
var uf=""http://bit.ly/rfEcJl\n"";
My guess is that doing this instead will solve your issue:
var uf = <?php echo json_encode($url); ?>;
Is the url is of some file in the file system and wrongly it is giving you '\' instead of '/'? in which case JS might crash... I guess.
It may be that url is not in proper form. So just try to console/alert thr url in "uf" variable, and url in winodw.open(...) statement and then check.

PHP Javascript variable help

Is there any way I could get the value of a html text field without using GET or POST or REQUEST? Alternatively, is there any way to get the field value in the same form or page else where.
This works with direct value such as "james", "system" and so on. the only problem is how do i make it work with html field values
Like:
<input type = "submit" onclick = "
<?php $username = "kut";
$result = checkname($username);
if($result)
{
?> alert("success"); <?php
}
else {?> alert("failed"); <?php
}?>
">
How can i replace "kut" with the value of a text field with id = "username" ?
<?php $username = "?>document.getElementById('username').value;<?php"?>
or something like that...???
In short, I need to get the value of a html field else where in the same page inside a javascript function, using PHP... like in the above javascriptFunction(), function
You have fundamental misunderstanding of how client-server architecture works.
PHP can be executed thousands of miles away, even days apart, from place where and when JavaScript does.
First PHP generates whole page, all of HTML, all of JavaScript source code (unexecuted), and then, after PHP is done and gone, browser starts running JavaScript.
These two can't be mixed together like you wanted, even though it may seem so in the PHP source code.
Although you can communicate with the server again using AJAX or similar, you probably should first understand how client-server architecture works and try to solve the problem without AJAX (e.g. handle all of it on server side, or all on client side).
You can not directly call a PHP function in JavaScript. You could set a JavaScript value from php before the page loads via echo. PHP is executed on the server while JavaScript is executed on the client side.
1> I suggest using jQuery to handle the Ajax part.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
function check_user(){
var user_el=document.getElementById('username');
if(!user_el){ return false; }
var username=user_el.value; // this could all be replaced with $('username').val()
$.getJSON('check_var.php',{"user":username},function(data){
if(data.result=='error'){ alert('something was wrong with the PHP stuff'); }
alert(data.userstatus);
});
}
</script>
2> On the PHP side, as check_var.php, you need a script that takes the username input, checks the DB, and sends back the result as JSON data.
<?php
if(!isset($_GET['user']){ exit; }
$username=preg_replace('#['^\w\d]#','',$_POST['user']);
//do your database query. I assume you have that part all set.
//since I'm not filling in all of that, you'll need to fix this next part to work with your system
//let's pretend it's like $found=check_user($username);
//be sure to use mysql_real_escape_string or prepared statements on the $username var since you're working with user input
$status=$some_db_error ? 'error' : 'success';
$results=array('result'=>$status,'userstatus'=>$found);
header('Content-Type: application/json');
echo json_encode($results);

Categories