At work (well more like an apprenticeship, dunno) I'm making a wordpress plugin that allows users to submit their posts (it's for a website catalog) with the ability to pay for some premium features. For this I'm using PayU.
I have a shortcode which I put on a page where users end up after the payment, and the shortcode shows appropiate message depending on GET variables. Eg. "your post awaits moderation" with a free post, "payment was successful" when it was so etc.
So when payment in PayU fails it will stick &error=501 to the end of the url, so my code detects that and tells the user their payment failed and their post won't be submitted. And here's the thing.
When the confirmation page url is itself a variable, eg. ?post_id=71, everything works as expected. So for mywebsite.com/?post_id=71&posttype=paid&error=501 the error is read and shortcode acts appropiately. But when the address in folder-like (sorry, really dunno how to call that) eg. /confirmation, error variable gets unnoticed. So with an address like mywebsite.com/confirmation?posttype=paid&error=501 the result is a "payment successful" message. Order of variables doesn't seem to matter, posttype is always interpreted and error is always omitted.
I don't have access to the code right now but it's basically this:
function my_shortcode() {
if(!isset($_GET['posttype'])) {
// some generic text to handle this unexpected condition
}
else if($_GET['posttype'] == 'free') {
// nice message on how the post awaits moderation
}
else if($_GET['posttype'] == 'paid') {
if(isset($_GET['error'])) {
if($_GET['error'] == '501') {
// payment was unsuccessful
} else {
// some generic text cause this isn't supposed to happen too
}
} else {
// payment was successful
}
}
}
As I said, I'd expect the error value to modify the behavior accordingly, instead it only does so when page address is itself a query.
Related
How can i add notification bubble like Facebook in my admin menu (when new user is signup) by using Ajax php also after viewing/clicking the menu bubble disappear.Anybody help???
When a user signs up, I guess you add him/her in your database? If so, I would add a field in your users database called "notificationViewed", which would be false by default when you put that user in the database.
When you connect or refresh you admin menu page, your php that serves the page should check the database if any user has a field notificationViewed == false, and COUNT the number of such returned users. In your html tag that represents the buble, add an attribute data-newUsers="<?= COUNT_OF_NEW_USERS ?>".
Now on the client-side...
Have, let's say, id="bubble" hidden by default with CSS:
#bubble {
display:none;
}
With JavaScript, you can access the data-* attributes easily:
var newUsers = document.getElementById('bubble').dataset.newUsers; // holds the number
or with jQuery:
var newUsers = $('#bubble').data('newUsers'); // same thing
At this point, you can check if newUsers > 0. If so, populate the bubble with the number (if you want), and do a nice fadeIn animation. Example in jQuery:
if (newUsers > 0) {
$('bubble').text(newUsers).fadeIn();
}
Now, we want to be able to detect when the bubble is clicked, in order to hide the bubble and discard the new users signed up. Again, with jQuery:
$('#bubble').click(function() {
$.post('discardNotifications.php', {usersNotified: newUsers}, function(data) {
if (data === "ok") { // php script returns this string if all went right
$('#bubble').fadeOut(function() {
$('#bubble').remove(); // remove the element from the DOM, to prevent further clicks of the element
}); // nice fadeOut animation of the bubble
}
}
});
The function will only be called if the POST request was successful. The POST request is directed to discardNotifications.php, which must be in the same directory as your admin-menu html file (if not, just change the relative path). The second parameter of the call is a litteral object containing the number of new users notified, which is sent to your back-end.
Back on the back-end, inside discardNotifications.php...
You must check if there's a POST parameter called "usersNotified", then query your users database and update at most the number given by "usersNotified". This takes into account that maybe new users subscribed since you refreshed your admin page, and you want the notification of these new users. Not selecting a maximum of "usersNotified" would possibly ignore them. Example (but not complete):
if (isset($_POST['usersNotified']))
{
$number = $_POST['usersNotified'];
// update the "notificationViewed" field to TRUE for at most $number different users
echo "ok"; // everything went right
} else {
echo "bad";
}
There are obviously changes you can make, and you have to implement some of the database handling. Tell me if it works!
Ps: there might be little errors in my code snippets, I didn't test everything.
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 am trying to figure out how to abort a running WordPress function. When the user deletes a custom post type (in my case, a store), I want to check to see if there are any associated posts with that store. I am running a query and checking to see if there are returned results. If we return 1 or more results, I want to abort the delete and present the user with an error message stating that they must delete the associated post. I am using the action 'before_delete_post'. Here is what I'm going for:
if (count($results)==0){
//delete the data
} else {
//abort the delete.
}
Thanks in advance for the assistance.
if you are using before_delete_post you could have something like this:
function prevent_delete_custom_post() {
if (count($results)==0){
//delete the data
} else {
wp_redirect(admin_url('edit.php')); //here you can try to get the variables that you have in the url to redirect the user to the same place.
exit();
}
}
add_action('before_delete_post', 'prevent_delete_custom_post', 1);
Remember that 'before_delete_post' action is fired before post metadata is deleted.
http://codex.wordpress.org/Plugin_API/Action_Reference/before_delete_post
And 'delete_post' action is fired before and after a post (or page) is deleted from the database.
http://codex.wordpress.org/Plugin_API/Action_Reference/delete_post
Currently, I am having one page that display query options and does the form validation and another page that process the query and shows the result if validation is successful. I am trying to combine these two pages together such that the user would not need to go back and forth the two pages every time to make some query changes.
The structure of the two page process is as follows:
**Validation Page**
if (post detected)
{
validate input
if (no error)
{
record query options
redirect to results page
exit
}
else
{
output error message
}
}
display form
**Results Page**
if (query options are set)
{
process query
display results
}
else
{
redirect to validation page
}
I have seen the concept being implemented simply in search engine pages where the search box and the results are in one page. I am looking to implement something like that using the POST method with a form containing both select and input boxes.
You can just set the form action to itself (or leave it blank along the lines of action = "" and it will point to itself anyhow, then use a simple check to see whether any form data has been submitted to determine if you should show the empty page or the search results:
if(isset($_REQUEST['searchStuffs']) // Not sure if you are GET or POST'ing
{
if(!empty($_REQUEST['searchStuffs'])
{
// do stuff here to get the form result, then display it
}
else
{
// The form was submitted empty, so show an error
}
}
else
{
// Display the normal search/form page as it hasn't been sent.
}
You can also use the following approach (which I would probably use though it is some extra work):
$searchBool=false;
if(isset($_REQUEST['searchStuffs']) // Not sure if you are GET or POST'ing
{
if(!empty($_REQUEST['searchStuffs'])
{
if(...)// valid search criteria
{
$searchBool=true;
// Do stuff to get search results
$searchResults='some output or data';
}
}
}
// Echo normal input form
if($searchBool)
{
echo $searchResults;
}
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.