Load JavaScript before Redirecting (CodeIgniter) - javascript

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>

Related

How to call javascript function from form in a php echo?

what the bellow code does is making sure the user isn't allowed to submit a comment unless he's signed in by using $_SESSION['login_user'] supervariable. But it's giving me an error. I think the problem is because I'm calling a javascript function in onsumbit="return(checkUser())". There's something wrong there but I don't know why.
I have the following code:
<script type="text/javascript">
// notice the quotes around the ?php tag
function checkUser() {
<?php
if(isset($_SESSION['login_user'])){
$isExist = true;
}
?>
else{
$isExist= false;
alert( "Please register first!" );
}
var htmlString="<?php echo $isExist; ?>";
return isExist;
}
</script>
...
...
<?php
echo "<form method='POST' onsubmit="return(checkUser());" action='".setComments($connection, $res['post_id'])."'>
//echo "<form method='POST' action='".setComments($connection, $res['post_id'])."'>
<input type='hidden' name='uid' value='".$_SESSION['login_user']."'>
<input type='hidden' name='date' value='".date('Y-m-d H:i:s')."'>
<textarea name='message'> </textarea><br>
<button type='submit' name='commentSubmit'>Comment</button>
</form>";
getComments($connection, $res['post_id']);
?>
....
If this is not the right method to stop the user from submitting a comment, then what could be another method?
In addition to what #RonaldT said, you need to understand that the PHP code is executed on the server before being sent to the browser. So checking for $_SESSION['login_user'] inside a Javascript function is kind of silly, since it will always be the same until the user refreshes the page (only then will PHP re-check the value).
So your function can be simplified like this:
<script type="text/javascript">
// on page load, define a global variable using PHP
var isLoggedIn = <?php echo isset($_SESSION['login_user']) ? "true" : "false"; ?>;
function checkUser() {
// check that global variable every time checkUser() is called in Javascript
if (!isLoggedIn) {
alert( "Please register first!" );
}
return isLoggedIn;
}
</script>
Keep in mind that this kind of "security" is extremely easy to fool (any user can just open their browser console, type isLoggedIn = true; and voila), so be sure to check on the server as well when the form is submitted.
Or better yet: if a user is not allowed to do something, don't give them the opportunity. Why display the form at all if the user will not be allowed to submit it anyway?
<?php
if (!isset($_SESSION['login_user'])) {
echo "Please register to add a comment";
} else {
echo "<form [...everything else...] /form>";
}
getComments($connection, $res['post_id']);
?>

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)

How to stop messages to show if page refresh when we get a GET parameter?

Hi i am trying to implement notifications when certain event happens in PHP. Suppose a user is changing its password and after the form is submitted the action takes it to update.php, if the password was succesfully changed the page will redirect to change.php?err=1 where 1 has a noty notification which shows password changed succesfully. If there was some problem it redirects to change.php?err=2.
The code for updating password in update.php :-
$sql="UPDATE user_credentials SET password=? WHERE id=?";
$stmt = $result->prepare($sql);
$stmt->bind_param("si", $hash,$id);
if($stmt->execute()) {
header('Location: ../change.php?err=1');
}
else {
header('Location: ../change.php?err=2');
}
The below code for is for showing messages in change.php.
if(isset($_GET['err']))
{
$error_id = $_GET['err'];
if ($error_id == 1) {
echo "<script> noty({text: 'Password Changed Successfully',layout: 'topRight',timeout: 2500,closeWith: ['click', 'hover'],type: 'success'});</script>";
}
else
if ($error_id == 2) {
echo "<script> noty({text: 'Something went wrong',layout: 'topRight',timeout: 2500,closeWith: ['click', 'hover'],type: 'success'});</script>";
}
}
Now if the page is refereshed it will show the message again and again. I want to show the message only when it is redirected not on refreshes.
I thought of a workaround using sessions like this:-
if ($error_id == 1) {
if(!isset($_SESSION['notify'])) {
$_SESSION['notify'] = TRUE;
echo "<script> noty({text: 'Password Changed Successfully',layout: 'topRight',timeout: 2500,closeWith: ['click', 'hover'],type: 'success'});</script>";
}
}
But it stops the message on refreshes but it doesn't show when page is redirected.
I am just starting to learn php so please let me know what I am doing wrong or what else could be better way to solving this problem. Any help is highly appreciated.
Well in addition to
if(isset($_GET['err'])){}
you can add:
if(isset($_GET['err']) && $_SERVER['HTTP_REFERER'] == YOUR_PREV_PAGE){}
In your case it is update.php
This kind of functionality typically works best when you use an ajax call, that means: without refreshing the page.
You could call update.php in the background (see docs of the link pasted above), and decide in the callback of that ajax function what notification to show, based on the response of your update.php script.
EDIT: simple example
$.ajax({
url: "/update-password.php",
data: {
user: "some-user",
pass: "new-pass"
}
}).done(function(response) {
// Show notification, decide on contents based on response
});
Use SESSION instead of GET for error messages. Set an error at the time it's detected, prior to your header() call:
session_start();
$sql="UPDATE user_credentials SET password=? WHERE id=?";
$stmt = $result->prepare($sql);
$stmt->bind_param("si", $hash,$id);
if($stmt->execute()) {
$_SESSION['error'] = "You password was changed.";
header('Location: ../change.php');
}
else {
$_SESSION['error'] = "We could not change your password.";
header('Location: ../change.php');
}
In change.php (and in any other page were a message might be set), do something similar to this:
session_start();
if (strlen($_SESSION['error'])) {
echo $_SESSION['error'];
$_SESSION['error'] = false;
}

Alert msg box display blank page behind

I am displaying a message box at the client browser. It works fine but i see a blank page at the back when this alert message box pops up. But I want to the user to see his browsing page always and pop up this message box. Here is my code.`
if($_POST['submit']=="Save")
{
$language=$_POST['pbx_lan'];
if($language!="")
{
$query="update `account_detail` set `prompt_language`= '$language' WHERE `org_id`='".$_SESSION['account_id']."'";
$result = $mysqli->query($query) or die($mysqli->error);
$_SESSION['check_update'] = "1";
// setcookie("msg","Language Successfully Updated",time()+5,"/");
echo '<script>
confirm("You have selected '.$language.'");
window.location = "'.SITE_URL.'index.php?view=pbx_prompts."
</script>';
// header("location:".SITE_URL."index.php?view=view_service");
}
else
{
setcookie("err","No Language Selected.Please Select Language",time()+5,"/");
header("location:".SITE_URL."index.php?view=view_service");
}
}`
When an confirm() is called the page stops loading. When you add the confirm() at the end of the page, the page is loaded before the confirm() is shown
<body>
TEST123
<script>
confirm('test');
</script>
</body>
instead of
<body>
<script>
confirm('test');
</script>
TEST123
</body>
For your code this means that
echo '<script>
confirm("You have selected '.$language.'");
window.location = "'.SITE_URL.'index.php?view=pbx_prompts."
</script>';
has to move to the bottom of your body tag
Also copy the required if statements so that the code is only executed when neccesary.
The complete code at the bottom of your body tag should be something like this:
if (!empty($language) && $_POST['submit'] == "Save") {
echo '<script>
confirm("You have selected '.$language.'");
window.location = "'.SITE_URL.'index.php?view=pbx_prompts."
</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