How to call a javascript function script from php - javascript

<?php
echo "<script type='text/javascript'>error_warning('Error!'); </script>";
?>
<!DOCTYPE html>
<html stuff>
<div id="alert_box" class="alert"></div>
</html stuff>
<script type="text/javascript">
function error_warning(warning){
var div = document.getElementById('alert_box')
div.style.display='block';
div.textContent=warning;
setTimeout(function(){ div.style.display = "none"; }, 5000);
}
</script>
This code is heavily simplified down but the key values are presented. I am trying to run a Javascript function at the bottom of the code from php. In the full code, the php echoes that script when something occurs. I have tried similar code:
echo "<script> alert('Error!') </script>";
This works but I'd rather create my own alert message which occurs in the top right corner of the page. The div is set to display: none, but I'm trying to run call the function which sets the display: block. All the css is dealt with and I have tested it works with a button.
I am running my code on XAMPP apache mysql. This is the error type when loading the page:
Uncaught ReferenceError: error_warning is not defined
at account.php:1
What I've gathered is that as the php is running server side, that the function is not defined so it can't see it hence returning the error. I've tried several solutions like putting the script before the php and they haven't worked.
Can anyone help?
Thanks

The solutions for this problem are...
Call function after it is defined.
for this you can use some server side variable to active the function call at the end of the page.
<script> function popAlert(errorType){//do something} </script>
<?php if($error == 1) echo "<script>popAlert(1);</script>";?>
Put your function in a separate .js file and include it in your page.
<?php
if($error == 1) echo "<script>popAlert(1);</script>";
?>
<script src="errors.js"></script>
Use Ajax to get response from .php file and then determine what needs to be popped up
Ex:-
$.post("url", "data", function(data, status){
if(status == "success"){
if(data == 1) popAlert(1);
if(data == 2) popAlert(2);
}
});
Extras
I recommend you to use Sweat alerts reference here
Ex:-
function popAlert(type){
if(type == 1){
Swal.fire({
icon: 'success',
title: 'You did it...!'
})
}
if(type == 2){
Swal.fire({
icon: 'error',
title: 'Oops, something went wrong...!'
})
}
}
<script src="https://cdn.jsdelivr.net/npm/sweetalert2#10.10.1/dist/sweetalert2.all.min.js"></script>
<h1>Click on buttons to pop alert</h1>
<button onclick='popAlert(1)'> success </button><br/>
<button onclick='popAlert(2)'> error </button><br/>
For any queries comment down.

There are multiple options to do this. Ajax or a simple echo. But for your problem, it is enough to simply add the onload function to the script echo.
<?php
echo "<script type='text/javascript'>window.onload = () => {error_warning('Error!')}; </script>";
?>
Another possible option would be to call the function after it has been declared.
<!DOCTYPE html>
<html stuff>
<div id="alert_box" class="alert"></div>
</html stuff>
<script type="text/javascript">
function error_warning(warning){
var div = document.getElementById('alert_box')
div.style.display='block';
div.textContent=warning;
setTimeout(function(){ div.style.display = "none"; }, 5000);
}
</script>
<?php
echo "<script type='text/javascript'>error_warning('Error!'); </script>";
?>

Related

Passing PHP variable via AJAX to PHP variable in another DIV

I've been working on this for a whole day but think I'm getting confused on the various methods available while I learn AJAX. I want my website to display the results of Python script. I can do that.
The problem is the script's results change randomly (it's the status of my garage door) and my site is clunky if the garage door's status changes. Usually the user has to keep reloading the page to get a current status. I'm trying to have the DIV that shows the status to update every 5 seconds thus showing the new status.
The Python script takes about 4 seconds to run, so I want to keep calling it as a function and pass it as a DIV on my site where I want to display the results.
If possible, one PHP file (index.php). Here is the skeleton of what I'm looking to do. My get_status function works, but I'm at a loss on the rest of it.
Thank you.
EDIT: Code updated with minor tweaks spotted by the commenters.
<html>
<body>
<?php
function get_status(){
$status = shell_exec('python /path/to/garage_door/myq-garage.py status'); //Equals either 'Open' or 'Closed'
echo $status;
}
?>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js">
var java_status = <?php echo json_encode(get_status) ?>;
// I have no idea how to pass a variable from PHP thru javascript to PHP on the
// same page. Trying to pass on results of get_status function every 5 seconds.
setInterval(function(){
$.ajax({
url: "index.php"
type: "POST"
dataType: "json"
data: ({status: java_status}),
success: function(data){
$("#status_div").html(data);
}
})
}, 5000);
</script>
<div id="status_div">
<?php
$new_status = json_decode(data);
?>
// I have no idea how to get that status variable here.
The Garage Door Status is: <?php
echo $new_status;
?>
</div>
</body>
</html>
To do this properly you have to have valid HTML and you don't need to send the PHP script any parameters. In addition, you need to separate your PHP from the rest of the code, else you will get back all of the markup in your AJAX response:
PHP Script - php_python.php
<?php
function get_status(){
$status = shell_exec('python /path/to/garage_door/myq-garage.py status'); //Equals either 'Open' or 'Closed'
echo $status;
}
get_status(); // execute the function
?>
HTML Page - index.php (note the use of a document ready handler because the script is at the top of the page)
You also need to separate <script> tags, using one to load the jQuery library and another to describe your JavaScript functions.
<html>
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){ // you need a document ready handler if you put the script at the top of the page
setInterval(function(){
$.ajax({
url: "php_python.php",
type: "POST",
dataType: "text",
success: function(data){
$("#status_div").html('The Garage Door Status is: ' + data);
}
})
}, 5000);
});
</script>
</head>
<body>
<div id="status_div"></div>
</body>
</html>
If you're just learning jQuery's AJAX here are some basic tips for setting it up and trouble-shooting problems.
Create a page and named it status.php
status.php include these code:
$status = shell_exec('python /path/to/garage_door/myq-garage.py status');
echo $status;
Make another page index.php and include-
<div id="status_div">
</div>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
setInterval(function(){
$.ajax({
url: "status.php",
dataType: "html",
success: function(data){
$("#status_div").html(data);
}
})
}, 5000);
</script>
Hope this will help you
If you are using ajax, you can make your life very easy:
function_status.php:
<?php
function get_status(){
$status = shell_exec('python /path/to/garage_door/myq-garage.py status'); //Equals either 'Open' or 'Closed'
return $status; //avoid echo in such functions, try to not produce side effects
}
ajax_server.php:
<?php
require_once("function_status.php");
echo get_status();
index.php:
<?php
require_once("function_status.php");
?>
<html>
<body>
<div id="status">
<?php echo get_status(); ?>
</div>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js">
<script type="text/javascript">
( //run function immediatly
function($){ //in this anonymous function, $ is always jQuery
function updateStatus(){
$.ajax({
url: "ajax_server.php"
type: "POST"
dataType: "json"
data: ({status: 1}),
success: function(data){
$("#status").html(data);
}
});
}
//first call it onload
$(function(e){
updateStatus();
}
//and then every 5 seconds
setInterval(updateStatus, 5000);
);
}
)//run function immediatly
(jQuery); //pass parameter jQuery to immediate execution of anonymous function
</script>
</body>
</html>
it is not a very clean way, and i used the <?php echo get_status(); ?> only, because your python script takes 4 seconds, so you would have no status for the first 4 seconds.
else you could change it to index.html and have a nicely seperated html and php, if you anyway want to populate the html with ajax.
if you really want to hack it into one file, you need an
if(isset($_POST['status'])){
echo get_status();
}else{
//output the html around the whole thing
}

Jquery AJAX function with $.post not going through, can't find any syntax errors

<script type="text/javascript">
function swapContent(cv) {
$(".loading").html("loading-gif").show();
$.post( "one.php", {contentVar: "cv"},function(data) {
$(".loading").html(data).show();
alert('Info Sent!');
});
}
</script>
And "one.php"
<?php
$contentVar=$_POST['contentVar'];
if ($contentVar == "con1") {
$row_number = $published_posts;
echo "<script type='text/javascript'>alert('$message');</script>";
}
else if ($contentVar == "con2") {
}
?>
I put the alert in the $.post so I can tell where my script is failing. I recieved alerts at every stage in the script up until $.post ceased to display the alert. Meaning that is where the code is faulted. But from what I can tell there doesn't seem to be any syntax errors, what could be the reason this is not working?
Got it to work! Had to specify the exact location of the file I was trying to post to. Due to the files being within a wordpress theme, I had to specify their location with <?php echo get_template_directory_uri();?>
$.post( "<?php echo get_template_directory_uri();?>/one.php", {contentVar: "cv"},function(data)

Correct way to set cookie from jQuery and read from php

I've tried to read the cookie values in PHP that are set via jQuery. But it's not read in first time page load. But I saw it's already set by the jQuery and can read the same value from the jquery.
When trying to read that cookie value from PHP it's not display the value when page rendered first time. But again refresh the page it's give the value from php.(I need to refresh page 2 time to get the correct value)
I used both head tag and onload method to place the setCookie() function. But result was same.
I used this jQuery library to write cookie.
Here's code I used to read and write the cookie.
<?php
if (!isset($_SESSION)) {
session_start();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
body{
background: #666666;
}
</style>
<script src="js/jquery.min.js" type="text/javascript"></script>
<script src="js/jquery.cookie.js" type="text/javascript">/script>
<script>
setCookie();
function setCookie() {
console.log('on Load');
var data_spl = $(location).attr('href').split('#?camlist=')[1];
if (data_spl != undefined) {
var len = data_spl.split(',').length;
$.cookie("len", len);
console.log($.cookie("len"));
} else {
console.log('undefined');
}
}
</script>
</head>
<body>
<?php
for ($i = 0; $i < 100; $i++) {
echo "<script>console.log('START');</script>";
echo "<script>console.log('" . $_COOKIE['len'] . "');</script>";
echo $_COOKIE['len'];
echo "<script>console.log('END');</script>";
}
echo "WIDTH & HEIGHT :" . $_SESSION['width_x'] . "-" . $_SESSION['height_y'];
?>
</body>
</html>
EDITED:
I used another php page to set session value that are came from java script and call that page via jQuery like shown in bellow.
var len = $(location).attr('href').split('#?data=')[1].split(',').length;
$.post('set_session.php', {params: len}, function (retparams) {
if (retparams.has) {
console.log('sucessfuly sent the paramlen!');
} else {
alert("can't read camarauids for grid making");
}
}, 'retparams');
set_session.php
<?php
if (session_status() == PHP_SESSION_NONE) {
session_start();
$_SESSION['urllen'] = 0;
}
if (isset($_POST['params'])) {
$_SESSION['urllen'] = $_POST['params'];
echo json_encode(array('retparams' => 'has'));
echo json_encode(array('datalen' => $_SESSION['urllen']));
} else {
echo json_encode(array('retparams' => 'error'));
}
?>
Then I try to read the session value ($_SESSION['urllen']) from index.php page. But it's also same as the above.(I need to refresh page one more time to get the correct value that are set from the jQuery post function.)
As already mentioned in the comment section your Cookie isn't present on first page Load because it isn't set yet. (If you set the Cookie directly in JS or via AJAX is essentially the same)
The only way to effectively get the Information is ether with a page reload or a redirect or via AJAX request (depends on what fits your needs). For Example you could redirect in JS after the Cookie got set with:
//set your cookie in JS
window.location = location.host;
more Information about JS redirects can be found here or you search your way thru Google.
You can also set your Cookie in PHP and redirect with the header() function:
header('Location: http://www.example.com/');
More Information for PHP redirects can be found here or on Google ;)
You could check this with ajax.
Here is a simple example:
<?php
if(isset($_GET["checkIfLoggedIn"]) && boolval($_GET["checkIfLoggedIn"]) === true) {
header("Content-Type: text/json");
die(json_encode(array("isLoggedIn" => $_COOKIE["isLoggedIn"])));
exit();
} else {
var_dump($_COOKIE);
}
?>
<html>
<head>
<script type="text/javascript" src="jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="js.cookie.js"></script>
</head>
<body>
<script type="text/javascript">
function checkIfLoggedIn() {
console.log("checking...");
jQuery.post("?checkIfLoggedIn=1", function(data) {
if(data.isLoggedIn == true) {
alert("Logged im.");
} else {
alert("NOT logged in!");
}
});
}
</script>
Set logged in to true<br/>
Set logged in to false
</body>
</html>

Load JavaScript before Redirecting (CodeIgniter)

This is my code. I already tried, flush(); window_location.. but still it fails. What shall I do? I also tested if the value of $result is being passed and it's fine. The only problem is the JavaScript is not loading. I have other codes with this coding structure but works fine and shows the JavaScript before loading.
function accsettings()
{
$this->load->model('admin_model');
$result = $this->admin_model->accsettings();
if ($result==0)
{
echo '
<script type="text/javascript">
alert("Congratulations! Your profile has been updated.");
</script>
';
$res2 = $this->admin_model->accset_audit();
}
else if ($result==1)
{
echo '<script type="text/javascript"> alert("Error! Current password is not correct."); </script>';
}
else
{
echo '<script type="text/javascript"> alert("New password does not match with the confirmation."); </script>';
}
redirect('/main/accsettings');
}
I would not recommend this way to show 'JavaScript' alert message, if you want to show validation message then please set variable controller and check on view.
In you code you are using headerlocation method to redirect page that is not show up result on browser.
Please use refresh method to show buffer result on browser
redirect('/main/accsettings', 'refresh');
//similar to
header( "refresh:0;url=/main/accsettings" );
You should do the redirect also inside the javascript when you want this to be executed.
Here's how you could achieve this:
<script type="text/javascript">
alert("Error! Current password is not correct.");
setTimeout(function () {
window.location.href = "http://www.google.nl"; //will redirect to google.
}, 2000); //will call the function after 2 secs.
</script>

Redirect to a page/URL after alert button is pressed

i have referred to this two questions call php page under Javascript function and Go to URL after OK button in alert is pressed. i want to redirect to my index.php after an alert box is called. my alert box is in my else statement. below is my code:
processor.php
if (!empty($name) && !empty($email) && !empty($office_id) && !empty($title) && !empty($var_title) && !empty($var_story) && !empty($var_task) && !empty($var_power) && !empty($var_solve) && !empty($var_result)) {
(some imagecreatefromjpeg code here)
else{
echo '<script type="text/javascript">';
echo 'alert("review your answer")';
echo 'window.location= "index.php"';
echo '</script>';
}
it's not displ ying anything(no alert box and not redirecting). when i delet this part echo 'window.location= "index.php"'; it's showing the alert. but still not redirecting to index.php. hope you can help me with this. please dont mark as duplicate as i have made tose posts as reference. thank you so much for your help.
You're missing semi-colons after your javascript lines. Also, window.location should have .href or .replace etc to redirect - See this post for more information.
echo '<script type="text/javascript">';
echo 'alert("review your answer");';
echo 'window.location.href = "index.php";';
echo '</script>';
For clarity, try leaving PHP tags for this:
?>
<script type="text/javascript">
alert("review your answer");
window.location.href = "index.php";
</script>
<?php
NOTE: semi colons on seperate lines are optional, but encouraged - however as in the comments below, PHP won't break lines in the first example here but will in the second, so semi-colons are required in the first example.
if (window.confirm('Really go to another page?'))
{
alert('message');
window.location = '/some/url';
}
else
{
die();
}
window.location = mypage.href is a direct command for the browser to dump it's contents and start loading up some more. So for better clarification, here's what's happening in your PHP script:
echo '<script type="text/javascript">';
echo 'alert("review your answer");';
echo 'window.location = "index.php";';
echo '</script>';
1) prepare to accept a modification or addition to the current Javascript cache.
2) show the alert
3) dump everything in browser memory and get ready for some more (albeit an older method of loading a new URL
(AND NOTICE that there are no "\n" (new line) indicators between the lines and is therefore causing some havoc in the JS decoder.
Let me suggest that you do this another way..
echo '<script type="text/javascript">\n';
echo 'alert("review your answer");\n';
echo 'document.location.href = "index.php";\n';
echo '</script>\n';
1) prepare to accept a modification or addition to the current Javascript cache.
2) show the alert
3) dump everything in browser memory and get ready for some more (in a better fashion than before) And WOW - it all works because the JS decoder can see that each command is anow a new line.
Best of luck!
Like that, both of the sentences will be executed even before the page has finished loading.
Here is your error, you are missing a ';'
Change:
echo 'alert("review your answer")';
echo 'window.location= "index.php"';
To:
echo 'alert("review your answer");';
echo 'window.location= "index.php";';
Then a suggestion:
You really should trigger that logic after some event. So, for instance:
document.getElementById("myBtn").onclick=function(){
alert("review your answer");
window.location= "index.php";
};
Another suggestion, use jQuery
Working example in php.
First Alert then Redirect works.... Enjoy...
echo "<script>";
echo " alert('Import has successfully Done.');
window.location.href='".site_url('home')."';
</script>";
<head>
<script>
function myFunction() {
var x;
var r = confirm("Do you want to clear data?");
if (r == true) {
x = "Your Data is Cleared";
window.location.href = "firstpage.php";
}
else {
x = "You pressed Cancel!";
}
document.getElementById("demo").innerHTML = x;
}
</script>
</head>
<body>
<button onclick="myFunction()">Retest</button>
<p id="demo"></p>
</body>
</html>
This will redirect to new php page.

Categories

Resources