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.");
Related
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.
This is a part of the code in a 'process.php' file:
echo "<script type='text/javascript'> percYes = ".$yes."</script>"
echo "<script type='text/javascript'> percNo = ".$no."</script>"
This 'process.php' file runs in the background (using jQuery/ajax) when the user clicks a butto. The 'echoed' html above replaces the contents of a div. So essentially what I'm trying to do is update some Javascript variables using a background php call, the above solution does not seem to work though, i.e. the script is not being ran once it is placed in the div.
A bonus problem involves using these updated Javascript variables to update a graph. I have a workng javascript graphing function, but the problem is getting the new graph to replace the old one (or just update it, if that's possible).
Thanks.
If all you are trying to do is update some JS vars, you may be better off having your process.php file returning a json string:
$array = ('percYes' => $yes, 'percNo' => $no);
echo json_encode($array);
This will give you a json string that can be evaluated and used in a callback for your JS ajax call.
So if you have a var 'percYes' and 'percNo' in an accessible scope, your callback could look something like this:
function(jsonstr) {
obj = eval(jsonstr);
percYes = obj.percYes;
percNo = obj.percNo;
}
I hope this helps.
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.
I'm using this web service that prints out table using Javascript functions. I need the table to print out in plain html. This could be done if the Javascript string was transferred to a PHP file. So basically, this is similar to AJAX, but it is in reverse.
You could do that with ajax also
var value = 'This is a test';
if ($(value).val() != 0) {
$.post("jquery2php.php", {
variable:value
}, function(data) {
if (data != "") {
alert('We sent Jquery string to PHP : ' + data);
}
});
}
Important thing here is we are using $.post, so we are can gather the information with $_POST
We are sending only 1 value, named variable.
PHP part;
<?php
$jqueryVariable = $_POST['variable'];
echo $jqueryVariable;
?>
I believe, this is the most elegant way to achieve what you want.
not necessarily reverse, You could pass the string as a URL variable (www.yoursite.com/?string=yourvariable) and have PHP process it from there.
I've quoted a ugly method down here But i dont recommend this..
Instead store values in hidden fields in forms and access them through js or do something else..
<?php
echo "<script type=text/javascript>var x = $value; </script>";
?>
then use the variable x in js..
Anyway if you explain ur situation a bit clearer, we can give u best alternate solution
what you should do is use jQuery's .load() to load in the php's html results into the page
in the docs i've linked above they give this example
<script>
$("#success").load("/not-here.php", function(response, status, xhr) {
if (status == "error") {
var msg = "Sorry but there was an error: ";
$("#error").html(msg + xhr.status + " " + xhr.statusText);
}
});
</script>
EDIT
in response to your comment on Pixeler's post. You will not be able to just view the source of a ajax based solution. if your ultimate goal is to be able to read the source you have basically three options
send them to a new page
load in an iframe
do it the way you have, use fire fox and web devloper addon which will allow you to view generated source. (or something similar)
I'm not sure why there is a need to see the source users don't really care about the source typically the developer uses that
I'm using jQuery to load the result of a PHP script into a variable. The script is passed something that the user typed with a GET request. I want to take just what the script spit out into its <body> tag. Here's what I've tried:
JS:
function loader() {
var typed = $('#i').val(); //get what user typed in
$.get("script.php", {i: typed}, function(loaded) {dataloaded = loaded;});
alert($(dataloaded).find('body'))
}
But it just displays [Objec object]. How can I get a useful value that is just the contents of the body of a loaded page?
I know the PHP works, I just need the JS.
The script echos something like 1!!2 (two numbers separated by two exclamation points).
Thanks!
You are trying to access the dataloaded which might not be assigned due to the asynchronous nature of AJAX calls. The only safe place to access it is inside the success callback. Also you could use the .html() function to get the contents of the body tag:
function loader() {
var typed = $('#i').val(); //get what user typed in
$.get('script.php', { i: typed }, function(loaded) {
alert($(loaded).find('body').html());
});
}
Also note that if the script.php only echoes 1!!2 without a <body> tag it won't work.
Without knowing what console.log prints it is hard to say, but try these
alert($(dataloaded).find('body').html());
Or
alert($(dataloaded).find('body').text());
I changed the page that I'm trying to fetch to XML. I'm using $.find to get each element of interest individually from the XML page, which suits this particular app well.
This problem has disappeared, as there is no longer a head section to ignore, and I'm just grabbing individual XML elements anyway.
Thanks for all your time and help!
Use JSON type. I am not sure about whether your Jquery script correct or not but using JSON with a correct usage would solve problem. ie.:
function loader() {
var typed = $('#i').val(); //get what user typed in
$.get("script.php", {i: typed}, function(loaded) {dataloaded = loaded;},"json");
alert($(dataloaded).find('body'))
}
And POST variable from script.php after encoding JSON. Use Php's json_encode() function. You need to create variable as an array. For example:
<?php
$title = 'Hello World';
$content = 'Get well soon Japan!';
$arr=array('title'=>$title,'content'=>$content);
echo json_encode($arr);
?>
And Jquery would be something like:
function loader() {
var typed = $('#i').val(); //get what user typed in
$.get("script.php", {i: typed}, function(loaded) {var dataloaded = loaded.title+" "+loaded.content;},"json");
$("body").html(dataloaded);
}
You may need to use Jquery's parseJson() functions on some situations. Don't think you will need here.