How to set a PHP object in session upon a hyperlink click - javascript

I have two PHP pages: One displays the information about an object retrieved from MySQL database and the other allows the user to edit it. The user is transferred from the first page (the view page) to the edit page upon clicking a hyperlink.
I would like to set the information retrieved from the database in session before passing on to the edit page so as to avoid an extra database call. How can I set an object in session upon a hyperlink click event? I know I could append the object as a variable to the GET request but is there a cleaner way than that?

Put the object into the session ($_SESSION['object'] = $object) when the page one loads (or when you retrieve the object from the database). This way you avoid a second call to the database. If you want to place it into the session upon the click event, a second call would be necessary, since you would have to make an AJAX call to a PHP script that retrieves the object. However, this may only make sense if the user is expected to edit that information, otherwise it is just storing data into sessions for no reason, which may also expose security bugs. If your database call doesn't retrieve millions of records, or you don't have hundreds of millions of users editing data in the same time, I can assure you that the impact on the performance by making a second call will go unnoticed.

Adding an object to the session:
$_SESSION['the_object'] = $object;
(Disclaimer: Will not work if the object contains any non-serializable components like closures)
Now when to do it? Actually, you have to do it on the page that shows the data, because if you do it later when the user clicks the edit link, this already triggers a new request which then would again go to the database - you'd have two requests (one for the list, one for the edit).
Generally, the edit link has the ID of the database entry to be edited. But pay attention to carefully check whether the user is allowed to have access or not, because MySQL will simply increment the ID, so it's easy to guess which IDs are valid. Anyone with a tiny bit of clue can modify a HTML form to tamper with IDs.
The approach with the session is somewhat easier: You only allow to edit what has been stored in the session, so the access control has to be done on the list page only.

For those who may be looking for a code snippet to help do this - here it is
Page 1 - this page just loads data from a DB and displays it in a non-editable mode on the screen. On this page we need an Javascript function that can be activated when the hyperlink is clicked
<script language="JavaScript" type="text/javascript">
function processEditLink(){
$.post('process_session_put.php', <?php echo "{S-Object:'".json_encode($obj_)."'});"; ?>
window.location.href = 'edit_object.php';
}
</script>
To explain the above code - we are taking an object (referred to as obj_) and encoding it into the JSON version by using the inbuilt function json_encode. Remember to ensure your object implements JsonSerializable in order to accomplish this. After that we are passing that JSON string as a POST URI parameter via AJAX to a secret page called process_session_put.php. This call is never visible to the end user and happens secretly when the hyperlink is clicked. The secret PHP page will decode the JSON string back into the PHP object and put it in session for all to use. Finally, once that function is complete, the window redirects to the actual edit page that can access data from session and populate the screen.
Next we should modify the hyperlink to trigger this Javascript function when it is clicked as below
<a class="edit-link" href="javascript:processEditLink(this);return false;">[Edit]</a>
Finally - the PHP page called process_session_put.php - which actually does the background work of decoding the JSON string passed to it back into the object format and putting it in session
<?php
if (!isset($_SESSION))
{
session_start();
}
// OBTAIN THE JSON STRING FROM POST URL, DECODE IT AND PUT IT BACK AS A OBJECT IN SESSION
$_SESSION["E-Object"] = json_decode($_POST["S-Object"]);
?>

Related

Is there a way to send POST data to another form and return the result of that form?

I need to send form data to another page that will allow the user to do something in a form and return the result of that form back to the original page? Is this possible? I know it's not ideal, but the issue is that I need to make a "drop-in" solution that does not need to be integrated with other code. I know it's a very specific request and scenario.
I know how to send POST data that doesn't require any user input on the processing page. i.e. I can send POST data to 'calculate.php' which will do the math and send it back, but if I need additional user input on 'calculate.php', how can I still send it back?
An example of expected results would be:
Page #1: User enters a number and presses submit to go to next page.
Page #2: User enters a second number and presses submit to finish.
Back to Page #1: User receives sum of both numbers.
Obviously, this is a really redundant thing to do, but I'm trying to simplify the problem as much as possible.
EDIT: There a few restrictions I forgot to add.
Page #1 is not my application, I am developing Page #2 as a "drop-in" solution for Page #1. Essentially, I can only use Page #1 to call Page #2 and receive a response from it. The problem is that I need to be able to allow for user input on Page #2.
I know I can post to Page #2 and then post to Page #1 again, but what if I need to maintain the state of Page #1. For example, if there's an open Web Socket connection.
Please note, I understand that this may be impossible or extremely difficult, but if I don't ask I'll never know right?
You want it with PHP or any other language. If you are running Php on server side then you can use Global variables like $_GET and $_POST.
Page #1: Use Post/Get method to send data to second page.
Page #2: Receive all fields' values using Globe variables ($_GET and $_POST). You can use these values as default values of form fields. Now submit this data to page 1 using post or get method.
Back to Page #1: Here you will receive the data of first page from second page and newly posted data from page 2
Either of these should work:
Never leave the page - use AJAX / XMLHttpRequest to call out to other pages to process chunks of data
Do everything on page 1 using "postbacks" -- the form targets are the same page, there is a state variable like "stage=1", and you use JavaScript to add set hidden variables for any additional state that's needed.
... PHP state validation and processing for the different stages ...
... one or more blocks of HTML for the page (PHP if / else can be used to choose between multiple page views) ...
Edit for added restrictions:
Have page 2 use postbacks or AJAX to collect the additional information
I figured out a few ways to do it.
Update a Database (or Data Store of some sort, depends on security needs) and have Page #1 listen for events from a separate page (on the same server as the database). Very similar to the way PayPal's Instant Payment Notification (IPN) works. I was actually able to set up server sent events with it as well.
Essentially, Page #1 sends data to Page #2 where the user will perform the function and then Page #2 will send POST data to a listener somewhere (either on the same server or Page #1's server), the listener will update a database and Page #1 will be listening or pulling to an event handler that will send an update once the database updates.
Use JavaScript Child/Parent Window functions. This is okay if Page #1 and Page #2 are on the same server, but can get messy and browsers have a lot of restrictions and it varies depending on browser.
Page #1 will open Page #2 in a child window, after the user performs a function, Page #2 will call a function that accepts the result data on Page #1.

repopulating $_POST variables transparently in PHP

So.
In a LAMP stack (PHP), I've got this situation where I'm showing an intermediate page based on some variable from the first page --more simply, I have one page called, say, ListOfProjects, from which I can select a project to view.
When I go to that project, there are other page-navigation elements (like looking at individual jobs in the project, say) the user can click. Once I click them, and am navigated away from the intermediate page between ListOfProjects and IndividualJob, I have to resubmit the data that got me there.
That's fine, and if I could do it automatically, I would. However, I haven't found a way to force this behavior and eliminate the extra click and the ugly "Confirm Form Resubmission" screen.
Does anyone know a way I could A) silently force form-resubmission when the user hits the back button or B) avoid the situation where there's a form that needs resubmitting?
I've thought about trying to just pass that project ID to the session variable, but it's well within scope to have more than one individual project open in the same browser, which would make that unwieldy.
Thoughts? Suggestions?
Thanks!
Don't use POST.
When you are getting data from the server, use GET and put the data in the query string.
POST is designed for sending data to the server that will make a change (e.g. updating data in the database), it isn't appropriate for just deciding what data to look at.
Some solution is bypass using jQuery to resubmit a form when click on back:
<?php if (isset($_POST['ListOfProject'])): ?>
<form method="POST" id="backToProject"></form>
<script>$("#backToProject").submit()</script>
<?php endif ?>
Another solution is to use header("Location: ...") to force users to redirect a page, BUT you should remove all previous $_POST request using unset($_POST) such as:
unset($_POST);
header("Location: your_uri://your_path");
Try reload a page and reload a page using javascript into <script> tag such as:
if ($_POST['ListOfProject'])
{
echo '<script type="text/javascript">location.reload();</script>';
}
Try to understand GET/POST method: https://en.wikipedia.org/wiki/Post/Redirect/Get
And I don't recommended using link of sites using $_POST method such as say Quentin user.

Save jquery modified page permanently

I want to save modifications made on a HTML page(modifications made with JQuery), PERMANENTLY! I have read that this thing gets possible by sending an Ajax call and saving it in a table in a database, but what do you actually save in the database? The URL of the page? And what do you retrieve back in the Ajax call so that your modifications actually stay on the page?
This is a Spring MVC based web application, in case this information is needed.
I have no clue how to start or if to start trying saving it, because I have also read that this thing might not be possible, as we're talking about Client-Side modifications.
Modification that I am trying to make:
function versionOne() {
$('#title').addClass('text-center');
$('#title').css({"margin-top":"0px","color":"black", "font-size":"45px"});
$('#title').append('<hr>');
$('#content').addClass('col-md-6');
$('#content').css({"margin-top":"80px","font-size":"20px", "text-align":"center"});
$('#picture').addClass('col-md-6');
$('#picture').css({"border-radius":"25px", "margin-top":"50px"});
}
I'd be grateful for some suggestions!
Thanks :)
Saving the whole page won't work in most cases since it's very hard to also save the JavaScript state. So while you can save a static copy of the page without JavaScript with $('html').html(), that doesn't get you very far (or causes more trouble than it's worth).
What you want is "preferences". The site should remember some specific values. The usual approach is to load the preferences from the database before the server sends the page for the client. Apply them to the elements of the page and send the result to the browser. That way, the page looks as expected when the user sees it.
When the user changes these settings, use JavaScript to update the page and send the changes as AJAX requests to the server to persist them in the database.
When the user returns to the page, the code above will make sure that the page now looks as before.

Django modify model instance from HTML

I want to know if it is possible to directly modify and save a model instance in the HTML Template and not via a view and extra URL.
My user has a Boolean Property, I want to display it as a toggle button on the website and the user should be able to toggle it on or off without leaving the website or reloading it.
class User(AbstractBaseUser, PermissionsMixin):
...
autoplay_enabled = models.BooleanField(default=True)
...
Is this possible without an extra view or form?
Basically I just need to set
request.user.autoplay_enabled = False (or True)
and then save() it
If I can't modify the object directly in the HTML template is it at least possible to just execute a function I have defined somewhere in my Python code, without having the need to create a new view?
What you're asking doesn't make any sense at all. HTML is just sent to the browser for display. You can't do anything "from HTML" without making some kind of request to the server, and the server won't do anything unless that request is received by some code - eg a view connected to a URL.
If you want something to happen without refreshing the page, you need to use Ajax. You can use a simple Ajax POST to a view that toggles the value and saves it - it only needs a dozen lines of code between front and back end.

Chat List Ajax Functionality

I have a chatbox, so when user hits post, it calls a php script to update database, and another php script located within itself to refresh the conversation to display the newly added message.
I thought about how to do this and here is how i have come about:
Have ajax call on button click to POST the data needed to the first php form to update the database (No need to return anything except whether succeed or fail)
Have e same ajax call php script located within itself to refresh the conversation (Note that this php script is located within itself as it is a loop and i use it to echo out the reply divs) in this case, page will not refresh and data can still be sent and obtained.
However, I'm not very sure how to do the second point, being call a php loop within itself to refresh the page and update the newest entry, any suggestions or would it be overly hard to do so such that i should just manually refresh the page.
To be more specific, this is the process flow of how adding a reply will work:
User types reply, clicks post.
Ajax is already attached to post button, so detects the post and fires first POST request to addchat.php
addchat.php contains mysqli code to update the database with the data posted from the ajax, returns success or fail
Once Ajax receives back success request, immediately fire off a command(this is what i am not very sure), that runs the php code located within the same document to echo out the newly updated chat reply (i do have timestamps in my database, so there is the ability to compare time, but note that the function is located within the same script)
After the php code is fired again, it updates the html automatically, since its located within the same script.
I am also not possible whether this is achievable with ajax, because many others use long polling instead to keep checking the database, but because my chat system does not need that high level functionality and the replies aren't that request, so what i am doing is just to get ajax to fire off the retrieval php script whenever somebody posts a reply to update the conversation. this should be more than enough.

Categories

Resources