I have a php page which is using javascript to produce a calendar on the page. I am trying to pass a variable so that I can reference it on the loaded page.
Below is the script I am using to generate the calendar(along with several others)
<script language="javaScript" type="text/javascript">
function initialCalendar(){
var hr = new XMLHttpRequest();
var url = "calendar_start.php";
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var year = currentTime.getFullYear();
showmonth = month;
showyear = year;
var vars = "showmonth="+showmonth+"&showyear="+showyear;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("showCalendar").innerHTML = return_data;
}
}
hr.send(vars);
document.getElementById("showCalendar").innerHTML = "processing...";
}
</script>
and below is the way I am displaying this onto the php page:
<body onLoad="initialCalendar();">
I have tried using '<?php echo $page; ?>' and '<?php $_POST['$page'] ?>' in the brackets of initial calendar()
however I am having no luck, I hope I have explained correctly and in enough detail to make sence, however if you need anything more please just comment
Thanks,
Ryan
I don't know the layout of your $_POST array, but if I understood the question right you should try:
<body onLoad="initialCalendar('<?php echo $_POST['page'];?>');">
and change your function declaration to:
function initialCalendar(page){
Note that I've used single quotes ' around the value which PHP outputs. This to ensure that it didn't break anything if the value is a string.
Since you are passing variable through parameters like
localhost/project/calendar.php?page=something
use $_GET['page'] rather than the $_POST
Related
In the script below, I currently have a fixed value in the array of $out variable. Example: $out[1]. What I need is for this fixed value (in this case 1), to be replaced by the str value of the function.
str is javascript
$out[1] is php
Someone can help me?
<script>
function teste2(str) {
var xhttp;
if (str == "") {
document.getElementById("cli").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("resimg").innerHTML =
"<img src=" + "<?php echo ("img/base/".$out[1]);?>" + ">"
}
};
xhttp.open("GET", "clique.php?q="+str, true);
xhttp.send();
}
</script>
As mentioned, it doesn't make sense why you are mixing PHP in your JS. If you need data from the server side usable by your client side JS, there are multiple approaches.
The preferred approach is to make an API endpoint you can call and return JSON.
Another approach (not recommended) is to output a JSON object in a script tag on server render and then access it like:
<script>
let data = <?php echo(json_encode($myData)); ?>;
</script>
To answer your question though, you can set the value with JS since the variable you want is client side:
function teste2(str) {
var xhttp;
if (str == "") {
document.getElementById("cli").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
let src = 'img/base/' + str;
document.getElementById("resimg").innerHTML = '<img src="' + src + '">';
}
};
xhttp.open("GET", "clique.php?q="+str, true);
xhttp.send();
}
Well, PHP scripts run on the server side, while Javascript ones run on the client's browser.
Therefore, the value of str will only be resolved at runtime, when the function is called on the user's browser. There is no way for your PHP script to know in advance what the value will be, as your PHP script runs before any JS does.
I am sorry, but I believe you should re-imagine your design here.
Edit: I assume your $out is a PHP variable, right?
Can someone tell me why the div called tellme is showing only showing something for half a second.. or less and then just doing nothing? I have tried everything and just can't get the code to work. It is funny because I have the exact same code on my other page and it works with no problems what so ever, I am trying to call an AJAX call and it is just not working and its not making the div called tellme anything, it's just keeping it blank...
<script type="text/javascript">
function fireWorkerFixed(userid)
{
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "http://private.com/fire_worker.php";
var id = userid;
var vars = "userid="+id;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById('tellme').innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById('tellme').innerHTML = "<div class='alert alert-info'>Please wait, Processing request...</div>";
}
</script>
I have a php page(calendar.php) which is using javascript to load a php calendar(calendar_start.php) and display the calendar in the center of the page.
I am trying to obtain a variable on the calendar_start.php page, however I cannot access variable which I am able to access from the calendar.php page.
below is one of the scripts used on calendar.php to generate canendar_start.php:
<script language="javaScript" type="text/javascript">
function initialCalendar(){
var hr = new XMLHttpRequest();
var url = "calendar_start.php";
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var year = currentTime.getFullYear();
showmonth = month;
showyear = year;
var vars = "showmonth="+showmonth+"&showyear="+showyear;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("showCalendar").innerHTML = return_data;
}
}
hr.send(vars);
document.getElementById("showCalendar").innerHTML = "processing...";
}
</script>
and below is part of the page calendar.php where I am generating the calendar:
<body onLoad="initialCalendar(<?php $_GET['page']; ?>);">
I am unable to grab the variable on calendar_start.php and I would really appreciate any help.
Kindest Regards,
Ryan
EDIT::
This may be helpful, this is the error when I am trying to display the variable on calendar_start.php
Notice: Undefined index: page in C:\wamp\www\project\calendar_start.php
Change $_GET['page'] to $_REQUEST['page'].
$_REQUEST combines $_GET and $_POST together (with $_POST taking precedence). That way you won't have to worry about backward comaptibility if you change it in the future.
It is, however, a bad idea to echo ANY of these variable unsanitized to users browser.
EDIT:
Although your main problem is that you forgot the "echo" command in front of the variable.
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>";
I have made a simple chat script using jquery and AJAX but the huge hole in it is that i can only chat with myself properly :P
heres the javascript for my main file
<script src="http://jqueryjs.googlecode.com/files/jquery-1.2.6.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#status").load('ajaxLoad.php');
$("#userArea").submit(function(){
var hr = new XMLHttpRequest();
var id = '<?php echo $id; ?>';
var name = '<?php echo $name; ?>';
var url = "ajaxPost.php";
var msg = document.getElementById("messages").value;
var vars = "messages="+msg+"&id="+id+"&name="+name;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
$("#status").append(return_data);
}
}
hr.send(vars);
return false;});
});
and heres my 2nd file "ajaxLoad.php"
<?php
include_once "connect_to_mysql.php";
$sql = mysql_query("SELECT messages,id FROM chat");
while($row = mysql_fetch_array($sql))
{
echo $row["messages"];
}
?>
Now what i need is to continually refresh "ajaxLoad.php" so that users can chat in realtime without refreshing the page...any way around this?
// reload every second
setInterval(function() {
$("#status").load('ajaxLoad.php');
}, 1000);
Be careful of making too requests to the server. It's going to be rather intensive.
You can use javascript setInterval to call your php script every x seconds.
https://developer.mozilla.org/en/window.setInterval
If you want to get bleeding edge, you should look into WebSockets.