I have a class that contains 2 functions one for removing post and one for submitting post. The function for submitting the post will redirect to any page I want just fine and if it is the same page it will be displayed with the new post.
The function used for removing the post will refresh or redirect but if it's redirected back to the same page the page does not appear updated until the page is refreshed again (a second time). I have looked and haven't found anything that works or a reason why this is happening. I'm new to php so go easy on me!
Is the page reloading before it know the post has been deleted? What can I do to solve this?
Here is my code:
class userPost{
// For Removing Post
function remove(){
if(($_SERVER['REQUEST_METHOD'] == "POST") && ($_POST['delete_id'])){
if(!$_POST['delete_id'] || !$_SESSION['SESS_USER']){
header('Location: ?id=profile');
}
else{
$delete = mysql_real_escape_string($_POST['delete_id']);
$remove = mysql_query("DELETE FROM Post WHERE post_id = '".$delete."' AND post_member='" . $_SESSION['SESS_USER'] . "'");
if($remove){
header('Location: ?id=profile');
}
elseif(!$remove){ ?>
<script>
$('#div-id').triggerevent(function(){
$('#div-id').html(newContent);
});
</script>
<?php
} // End Else
} // End Else
} // End If
} // End If
} // End Class
You need an exit; after header. Otherwise PHP continues to process the script.
As an aside: Don't continue programming this way. There are so many issues with this script I wouldn't know where to start. A good book to learn PHP the right way is PHP : Ojects, Patterns, and Practices by Matt Zandstra.
Related
Form.php(controller)
public function dispdata()
{
$result['data']=$this->Form_model->displayrecords();
$this->load->view('display_records',$result);
if (!$this->session->userdata('ci_session'))
{
redirect('Form/login');
}
else
{
$this->session->set_tempdata('item',$result,5);
}
}
display_records(view)
<?php
if($this->session->tempdata('item')){
redirect('Form/login');
}
?>
im trying to work with the tempdata concept. i have a registration form where i have stored all the registered details in the datbase and those store details of database i have displayed
it in the view page.
how that i have displayed all the database details in a view page that view page im trying to display only for 5sec and after 5sec it should redirect to the login page. i have tried with the above code but its not working please can anyone tel me where im going wrong ?
The tempdata feature for sessions only affects how long the data is allowed to be stored. The removal of the data, after 5 seconds in your case, won't cause anything else to change on the page.
As far as I can tell you don't need tempdata at all. Try this to see if you get the behavior you want.
public function dispdata()
{
if (!$this->session->userdata('ci_session'))
{
redirect('Form/login');
}
$result['data']=$this->Form_model->displayrecords();
$this->load->view('display_records',$result);
// sleep for 5 seconds
sleep(5);
redirect('Form/login');
}
Why did I remove the else from your code? Because redirect does not return - it ends script execution. So, when the if evaluates to true and the redirect executes this script is done.
<?php
$sPage = $_GET["p"];
//echo ("You picked the page: " . $sPage);
if ($sPage == "") {
$sPage = "home.php";
}
include($sPage);
?>
It came from a php multipage website. I would like to write this same kind of code, but in javascript.
What does this code do?
http://www.tropicalteachers.com/web110/superduper/
this link is where the code came from, the php dynamic one
Okey so let's just start from the top to the bottom. I will try to explain shortly what each php thing does also incase you don't know PHP to well.
$sPage = $_GET["p"];
This code above is getting query parameters that you got in your URL, currently it's getting the query parameters "p" so for example if the url was http://localhost/index.php?p=hola the "$sPage" variable would hold the value "hola".
if($sPage == "") { $sPage = "home.php"; }
Short if statement checking if there was a query parameter with a value, if not we will set the variable value to "home.php"
include($sPage)
So this will litrally just take the file "home.php" in this case and include it in page. So anything that is in the file "home.php" will be displayed on the current page you are at.
To replicate this in javascript it would be similar to using ajax to fetch the content you wanna display. Below i will link to a tutorial that can explain how to accomplish that.
https://www.w3schools.com/jquery/jquery_ajax_load.asp
This doesn't help with the URL part, but that you can google yourself to with the correct termanology
Is it possible to redirect the user to the correct page after headers have been set?
I have developed a plugin in WP that allows users to manage content they have created on the site... for example, they can delete it or disable comments.
The author options appear at the top of the authors post... When the user clicks the button to delete their post, it changes a value in the db to soft delete it:
$result = $this->db->update(
$this->_table,
array('active' => $status), // 0 / 1
array('id' => $id)
);
if($result > 0)
{
$this->setMessage('success', 'Post deleted.');
}
else
{
$this->setMessage('error', 'Some error.');
}
The page appears to refresh as the message is shown, but the post is still showing.. the page must be refreshed again before a 'this post does not exist message' appears.
I have tried lots of WP hooks to try and fire wp_redirect before the header but i'm always getting an 'headers already sent' error.
I know I am using WP but I believe this is a http/php limitation so I decided to post it here.
I wanted to do something like:
if($result > 0)
{
header('Location: ...');
}
else
{
$this->setMessage('error', 'Some error.');
}
Using output buffering is not an option.
This type of redirecting is available in Laravel and you can even pass a message variable to be shown on the next page so it must be possible some how.
Simple and working solution using javascript. Used this type of reirection in my projects. No problems ever :)
if($result > 0)
{
echo "<script>parent.self.location='ENTER YOUR URL HERE';</script>";//enter location..example www.google.com, or profile.php etc
}
else
{
$this->setMessage('error', 'Some error.');
}
You can use the javascripts
window.location.href='enter_your_url_here.php';
There's two ways to do that,
First one using Javascript as #Unni Babu and #ash_8247 answer.
Second way is to use a buffer
//allow redirection, even if my theme starts to send output to the browser
add_action('init', 'do_output_buffer');
function do_output_buffer() {
ob_start();
}
See this post
I have a relatively simple class which deletes a post:
function delete_post($postid, $reason){
//Stuff to delete post
$this->delete_response = 'Thanks, your course has been removed.';
}
This function is called at the top of a page with a form on. If the form is submitted, the same page checks the POST[] and carries out the function, like so:
if(!empty($_POST['removecourse'])){
$courseManager->delete_post($_POST['courseid'], $_POST['cancel-reason']);
echo $courseManager->delete_response;
};
So my problem is... when I refresh the page, the message keeps displaying. I know this is because I am re-submitting the form, and because there is no such P/R/G pattern going on, but as i am new to OOP, im wondering if im doing this the right way, or if anyone could suggest a way similar to PRG or something?
Add an if that test if somthing changed, like mysql_affected_rows
function delete_post($postid, $reason)
{
//Stuff to delete post
if(mysql_affected_rows())
{
$this->delete_response = 'Thanks, your course has been removed.';
}
}
I'm developing a form validation class in PHP. When form validation fails, I can easily redirect again to the form's html page but without error information. I would like to redirect to the form's page with the specific errors about which fields failed and why.
How should I do this? Should I send information back via GET or POST? and in which format? Would really to see some code to see how people tackled this problem.
Thanks!
You could use the header() function. So just check the fields that are posted:
if(!$form->valid()){
$msg = "Form is not valid";
} else {
//Don't know if you want this
$msg = "Form is valid";
}
header("Location: [page where you came from]?msg=" . urlencode($msg));
Then in the page where you're redirecting to use
if(isset($_GET['msg]))
echo urldecode($_GET['msg']);
to echo the message. If you are using other get variables in the location of the header function, of course, use &msg=" . urlencode($msg). (You may also want to return the values that the user submitted, so the user doesn't have to fill out the entire form again if he makes 1 mistake.
I agree with user187291's suggestion of using $_SESSION because:
It doesn't hijack the URI like using $_GET (you would never want a static link to a status message). Users could press "back" to the page with your form and still see a status message because the URI says so.
Print and unset it in the same run, you won't be able to use it more than once (which is what you want?!)
If you're going with AJAX, $_GET is more widely used for retreiving values, which you are doing from the validation controller.
there are number of approaches
pass errors in GET when redirecting back like you said
use sessions to store error info, on the form page check Session for errors
do not redirect after failure, just output form again along with error messages
ajax submits
which one to use depends on the application. For most apps sessions method is most appropriate.
Something like this:
// Pseudo Code
function isValid($parm) {
$return = false;
if(preg_match(/^[a-zA-Z]+$/, $parm) {
$return = true;
}
return $return;
}
$firstname = $_GET["fname"];
$lastname = $_GET["lname"];
$validFirstName = isValid($firstname);
$validLastName = isValid($lastname);
if($validFirstName == true && $validLastName == true) {
echo "It's all good";
// Do what you need to like, Submit
} else {
echo "Please retry";
// Display error message
}
I use a class to interface with $_POST, similar to the following:
// create the object
$post = new PostData();
// register your requirements... write whatever methods you need
// for each call,read $_POST, check criteria, and mark the field
// as good or bad...
$post->required ('LastName');
$post->required ('FirstName');
$post->numeric ('Age');
$post->optional ('MiddleInitial');
$post->regExp ('/\d{3}/','AreaCode');
$post->email ('Email');
// check the status
if (!$post->isValid ())
{
$_SESSION['FailedPostData'] = $post;
header ('Location: page.php');
}
// normal form processing
Then, on page.php, you can see if FailedPostData is in the session, read it to find the info entered last time, as well as which fields that failed. I use a template engine with macros that let me easily re-populate the form inputs and mark the failures. Otherwise you might end up with lots of code for a simple form...
You'll also need a mechanism to be sure that stale FailedPostData doesn't hang around in the session and confuse things.
I am doing it this way. Beginner in php so not sure if this is the best way to do:
HTML Form Page:
<form id="abc" method="post" action="validate.php">
PHP Page
..validation conditions..call a function if things do not match
function display_error($error) {
echo "<html><body><link href='style.css' rel='stylesheet' type='text/css'><br><center><h2>";
echo "$error";
echo "</h2></center><br><br>";
echo "<center><input type='button' value='Go Back' onClick='history.go(-1)' style='width:100px; height:28px; font-size:16px'></center>";
echo "</body></html>";
}
Clicking on the back button takes you back to the html page with the data intact.