Do I really have to reload my page twice? - javascript

I am currently working on a project including the Facebook SDK. I already made it to Login/Logout myself using the javascript code.
I'm using an AJAX POST request to save the userID and the name from the response in a Session.
The problem here is, that I actually have to reload the page twice, the first time to get the POST parameters and save them into a $_SESSION.
The second refresh is needed to load the Session.
Is there a clean way to avoid that?
javascript: $.post( "login.php", { id:userID, name:response.name } );
login.php:
$_SESSION['name'] = $_POST['name'];
$_SESSION['userID'] = $_POST['id'];
I appreciate every kind of help. Thank you.
edit:
I would like to give the user who logged in with facebook additional oppurtunities on my website. The only way I know how to do this is with a Session in PHP. Whenever he logged in I created a Session who said that a person is logged in.
Now I have to do the same with a facebook login. It worked local with the PHP SDK already, but the webspace does not support that kind of SDK. That is why I have to dodge to the javascript one.
Is there another way to make sure a person is logged?

You are using AJAX,
So you can avoid reloading of Page,
<?php
session_start();
if (isset($_GET['name'])) {$_SESSION['name'] = $_GET['name'];}
if (isset($_GET['userID'])) {$_SESSION['userID'] = $_GET['userID'];}
if(isset ($_POST['name'] ) && isset ($_POST['userID'])){
$_SESSION['name']= $_POST['name'];
$_SESSION['userID']= $_POST['userID'];
}else{
$_SESSION['userID'] = 0;
}
?>
and javascript code is:
$.post( "/login.php", { id:userID, name:response.name } );

Related

JavaScript function won't run after using header(), but does run if no use of header() (in php)

I apologize if my question title is at all confusing, this is my first post and despite reading https://stackoverflow.com/help/on-topic I feel like I may still have some flaws in my question-writing abilities.
TL;DR: JavaScript animation works if I do not use header("location: ProjectUserProfile.php?UploadSuccessful"), but doesn't if I do (and I need to). Any reasons or solutions?
Anyway,
The context:
I have a html form embedded in a php document which is used to upload an image, delete an image, etc.
The main code takes place on ProjectUserProfile.php (and works perfectly), and after the image has been uploaded, I use header("location: ProjectUserProfile.php?UploadSuccessful") to return to the page, and prompt a refresh.
The problem:
If I do not use header("location: ProjectUserProfile.php?UploadSuccessful"), the image will not change, etc, so it is a necessity for me to use it. However, recently I have implemented "slide in notifications" if you will which display success and error messages. These work correctly normally, but fail to appear if I return to the page using header("location: ProjectUserProfile.php?UploadSuccessful").
<?php
// all the uploading etc that works occurs here
header("location: ProjectUserProfile.php?UploadSuccessful");
echo "<script> openMessage('Information','The duplicate files were successfully uploaded!') </script>";
?>
After redirecting to ProjectUserProfile.php?UploadSuccessful, there is failure to acknowledge openMessage, and so nothing happens.
Whereas, had I not used header("location: ProjectUserProfile.php?UploadSuccessful"), the "notification" would slide in and work.
Does anyone have any solutions or suggestions?
Relevant code for the javascript function 'openMessage()' below:
function openMessage(Purpose, DisplayText){
var notificationDiv = document.getElementById("slideinNotification");
if(notificationDiv){
alert("exists");
}
else{
alert("does not exist");
}
document.addEventListener("DOMContentLoaded", function(event){
if(Purpose == "Information"){
document.getElementById("slideInNotification").style.backgroundColor = "#4CAF50";
}
else if(Purpose == "Warning"){
document.getElementById("slideInNotification").style.backgroundColor = "#FF9800";
}
else if(Purpose == "Error"){
document.getElementById("slideInNotification").style.backgroundColor = "#F44336";
}
document.getElementById("notificationMessage").innerHTML = DisplayText;
moveElement();
});
}
<?php
if($filesWereDeleted == true){
$connection = new mysqli("localhost", "root", "root", "project");
$result = $connection -> query("UPDATE UserProfileImage SET UploadStatus = 1 WHERE UserUniqueID = '$userProfileId'");
header("location: ProjectUserProfile.php?DeletionSuccessful");
echo "<script> openMessage('Information','The profile image was successfully deleted!') </script>";
}
?>
<div id = "slideInNotification" class = "slideNotification">
<p id = "notificationMessage" class = "notificationInfo"></p>
×
</div>
First, your UPDATE query exposed to SQL Injection, if you get the id from the user, I hope note, read about prepared statement.
Second, about your problem, you echo the notify script in the same response you send the Location header , so before the the browser even load your JavaScript code it redirect the client to the new page when your notify javascript code not echoed...
If your problem is that user updates it's image and it's doesn't appear due it cached you can use uniqid() in the get query of image src or modify time, more effective
The thing is, once you use header("location: ProjectUserProfile.php?DeletionSuccessful"); you're not supposed to write anything into the output, as the browser will ignore it. That aside, I'm not exactly sure about how a single line of <script> openMessage('Information','The duplicate files were successfully uploaded!') </script> could mean anything to the browser, since that wouldn't constitute an HTML document by itself, unless you're receiving it through AJAX or loading it into an <iframe>; but even then, I doubt mixing control instructions (a redirect) with view markup (the script tag) would be a good idea.
You're going to have to post the confirmation message in ProjectUserProfile.php, so move your script tag there. You can use that ?UploadSuccessful bit as reference for you to know whether to include your script for the message in the document is necessary or not.

How to pass a php variable from a php file to js file? [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 6 years ago.
I have an html/php composite document that uses the login variable from a user. (This came from a separate php file on signin):
<html> Welcome <?php echo $login; ?> </html>
//Now when the user uses the chatbox, and clicks send, I would like to pass the data (inclusive of the username) from this html file to the .js so it can in turn pass onto another php file. (ps I tried the following but to no avail, as the .js file is external to the html/php composite):
$("#newMsgSend").click(function()//triggers script to send the message
{
$("#newMsgCnt").val(''); // clears the box when the user sends a message
var username = "<?php echo $login; ?>";
alert(username);
});
Your current code is likely introducing an XSS vulnerability. Instead, take advantage of the fact that valid JSON is valid JavaScript:
var username = <?php echo json_encode($login); ?>;
In some situations, it may also be better to use an XMLHttpRequest or WebSocket that requests the data from another URL (typically encoded as plain text, XML or JSON). One scenario for that would be notifying the user once new items have been added after the user loaded the webpage.
when the user logs in, create a session for that user and populate it with the data (such as username, email, phone number or whatever) from the database - as followings (assuming that the login is correct and authentic:
$_SESSION['user'] = $row; //where $row is the row of data returned from the db
Then whenever you want to access that information include the following at the top of the page:
session_start();
and then access the information such as
$userfirst_name=$_SESSION['user']['first_name'];
then your html will be something like:
<h1> Welcome <?php echo "$userfirst_name"; ?> </h1>
note that session start must be at the top of each page you are wanting to access the sessiobn variables. Then to clear the user details (such as when the user logs out you can use the following:
unset($_SESSION["user"]);
Thanks to both: Ivan Rodriguez Torres and phihag. I got a solution somewhere in the middle of both posts:
<input id="login" readonly type="text" <?PHP echo "value= '$login'/>"; ?>
Ivan's suggestion was somehow returning an "undefined" variable for me. The above works like a charm though. Hope its safe and doesnt lead to any problems.
Thanks again guys

How do i call a specific function from a functions page when an anchor tag is clicked

Before i go on, I'm aware that this question has been asked a couple of times but it doesn't deal with specificity.
I have a functions.php script which contains a couple of functions and i would like to call a specific function when the user clicks on an anchor tag.
I have gone through most of the questions in this manner and i understand that this would be done through javascript and ajax load the page specified with the on-click attribute.
My question is when this happens(page is being loaded) how do I call a specific function out of the functions.php script and if I have required it on the current page where the anchor tag exists will it cause complications?
To be more precise i have a register.php page which does the following; take user data then validate, if validated insert into DB and send a mail to the user to verify his account then redirect to a registration_complete.php page which has the option of resending the link if user didn't receive it. Hence clicking the link will run a specific mail function in the functions.php file.
The Code is written below
register.php
<?php
session_start();
$_SESSION['name'] = hmtspecialchars($_POST['name']);
//validation code goes here
if (isset ($_POST)){ //check that fields are not empty etc...
// insert into db code...
// email the user code...
// redirect to registration_complete.php code..
}
?>
<form method='post' action="">
<input type="text" name="name" id="name">
<input type="text" name="email" id="email">
<input type= "submit" value="submit">
</form>
registration_complete.php
<?php
require'functions.php'
session_start();
$Name = $_SESSION['name']
$RegisterationComplete = "Thank you . ' ' . ' $Name' . ' ' . for registering pls click on the link in the email sent to the email address you provided to verify you account. If you didn't recieve the email click on the resend email link below to get on resent to you. Please make sure to check your spam folder if you did not see it in your inbox folder."
?>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
function doSomething() {
$.get("somepage.php");
return false;
}
</script>
Resend Verification Link
Please not that i have copied the js code from one of the answers related to my question
functions.php
<?php
//connect to db code
// insert into db code
// send verification link code using PHP Mailer function..
?>
So when ajax loads the functions.php page how does javascript call the exact function(PHP Mailer).
I just want to state that i am new to programming i'm only a bit conversant with php. My knowledge of Javascript and Ajax can be said to be negligible. Also want to say a big thank you to all contributors.
Javascript will never call PHP functions, since PHP is running on the server and Javascript is running in the web-browser. The server and the web-browser are assumed to be different machines, the only exception being testing by developers. Therefore, if you have a function in functions.php called foo, Javascript will not be able to call it.
As you have already mentioned in your question, this might involve AJAX, which is surely true, but let's be more exact: when your Javascript code intends to "execute" a PHP function, it needs to trigger a request to the server. Not necessarily with AJAX, as you can trigger form submission, or anchor click as well. The request will reach the server, which will handle it.
Now, since we know that the life cycle is as follows:
Javascript detects that foo has to be executed
Javascript triggers a request to the server
Server is requested
Server handles the request
Server responds
The missing piece in the puzzle is to let the server know that it has to execute foo. To achieve this, the server has to determine somehow whether foo needs to be executed. This can be done with various way, including get params or post params. Next, you need to modify your Javascript code or html structure to let the server know that the function needs to be executed.
You can add a get parameter to the href of the anchor tag, for instance, but in general, you need to let the server know what the intention is and at server-side you need to handle that intention.
Also, you are doing validation on the server. This is ok, but may I advise you to validate the inputs on client-side and prevent posting if the input is invalid, to reduce server load... On server-side, if the post is valid, you need to execute the needed functions.
Also, this part is not exactly correct:
if (isset ($_POST)){
This is not the right approach to check whether this was a post request. You need
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
instead.
It is not important if the Request comes from javascript or a regular server Request (user clicks on link). You need to check the GET or POST parameters and redirect the Request to a specific function.
<?php
if( isset( $_GET['method'] ) ) {
// NOTE: untested and REALY unsecure Code
$method = $_GET['method'];
if( function_exists( $method ) ) {
call_user_func( $method );
}
}
else {
echo '<a id="link" href="?method=foo">klickme</a>';
}
function foo(){
echo 'in method';
}
?>
<div id="answer"><!-- server answer here --></div>
when you now have a link
http://yourSite.com?method=foo
and the function foo gets executed.
Now the JS part you have to check if the user clicks on a link, or sends a form. Then you have to send the request to server using Ajax and handle the result from the Server.
// inject the serverData in DOM
function loadSuccess( e ) {
document.getElementById( 'answer' ).innerHTML = e.target.response;
}
// handle click, open ajax request
function doClick( e ) {
e.preventDefault();
var ajax = new XMLHttpRequest();
ajax.open("GET", e.target.href ,true);
ajax.send();
ajax.addEventListener('load', loadSuccess);
}
var link = document.getElementById( 'link' );
link.addEventListener( 'click', doClick );

Javascript, PHP, and SQL Security - Basic validation of information received.

I have been developing a social network. I have noticed some security issues where the user can change the variables in javascript/jquery to other user_id's, text content, and other information that has been loaded into the scripts. And this is all done via the inspect tool or other software that can edit the languages. They can even rewrite the functions.
I load data onto the page via php and sql after sending the url_id to a php function.
I have javascript and jquery scripts that in return use this data to perform ajax, post, and get requests and to perform functions.
How can I stop the user from changing these variables before they are sent off to the server? For example when a user makes a post they can change the id to make it someone else's post, or when they click delete an image they can delete someone else's and it gets more complicated. This is a huge concern.
These scripts are included in the php pages or in php scripts that are loaded via ajax.
How can I stop this? Can you give me an easy explanation? I have been searching for months on how to stop this. I still don't understand how to stop the user from doing so. If there is another way could to do this? Can you provide me with true 100% examples? What are the other options I have?
Here are some snippets of my code
<? if (login_check($mysqli) == true) : ?>
<script>
$.post("auto/online.php?q=<? echo $id ?>");
function o() {
setTimeout(function() {
$.post("auto/online.php?q=<? echo $id ?>");
o();
}, 6e4);
}
</script>
<? endif; ?>
<?php echo '<div class="post-btn" onclick="ajaxPost(postenter.value,\''.$name.'\',\''.$id.'\');" title="Post">Post</div>'; ?>
function ajaxPost(content,name,id) {
var ip = '<?php echo $ip ?>';
content = content.replace(/<br\s*\/?>/mg,"\n");
var postArray = [content, id, ip];
postArray = JSON.stringify(postArray);
alert(postArray);
if (content.length == 0) {
alert('Oops it looks like your post is empty.');
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("postenter").innerHTML = "";
var html = xmlhttp.responseText;
alert(html);
$(html).hide().insertAfter("#wrapper").fadeIn(500);
document.getElementById("postenter").value = "";
}
}
xmlhttp.open("POST", "auto/post.php", true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send('data=' + postArray);
}
}
<? if ($id == $user) : ?>
<div class="modalSetPro" onclick="setProImage(<? echo $picID; ?>,<? echo $uid; ?>)">Set Profile</div>
<div class="modalSetBac" onclick="setProCover(<? echo $picID; ?>,<? echo $uid; ?>)">Set Background</div>
<div class="modalDelImg" onclick="delItemPre(<? echo $picID; ?>, 1, <? echo $uid; ?>)">Delete</div>
<? endif; ?>
function delItemPre(itemID, type, user) {
var modArr = [itemID, type, user];
modArr = JSON.stringify(modArr);
$("#LoadMe").load('modals/del_modal.php?p=' + modArr);
}
How can I stop the user from changing these variables before they are sent off to the server? For example when a user makes a post they can change the id to make it someone else's post, or when they click delete an image they can delete someone else's and it gets more complicated. This is a huge concern.
You can't.
Your server side code should evaluate the user's privileges and decide whether or not they can do the action. JavaScript validation is more for the user experience - guiding and preventing mistakes.
You are not able to prevent this, which is why server-side validation is required.
Here is a stackoverflow discussing it: Why do we need both client side and server side validation?
There is some good information here:
http://www.w3schools.com/php/php_form_validation.asp
Basically, you want to put your validations in the PHP page that you are posting your ajax to.
Store and check all insecure data on server side, not client. This way user can't change it.
First of all when you are working on client side you have no control how user interact with you jquery or javascript code. So thumb rule is that never expose sensitive data in html or java script.
More over If you are curious about security you have not required to load User id in hidden field or any other client side code(html). In you case like when user is replying to any post you have to crosscheck at server side whether current logged in user is authorized to perform this task or not. also cross check whether this post is relate to current logged in user.
I have no knowledge about php but in asp.net we can create a session at server side and when user post data get the User id from session not from html content posted by user.

Get Ajax to work for all Users on Wordpress

some Plugins that use Ajax in Wordpress only work when you are logged in as admin or added these hooks:
add_action('wp_ajax_my_action', 'my_action_callback');
add_action('wp_ajax_nopriv_my_action', 'my_action_callback');
But I'm really having a hard time with getting everything to work for non-admin users and I'm wondering if there is a easy way (for js/php noobs) to tell wordpress to globally activate all ajax functions for alls users, wether logged in or not.
I know this is probably a very stupid and risky way if that is possible somehow, but please let me know!?!!?
PHP wise, you've hit the nail on the head with your code above. This is required for each AJAX action, as each action will of course call a different function.
Now, I'm making the assumption that you are using the default Wordpress AJAX call -
jQuery.post(ajax_object.ajax_url, data, function(response) {
If that is indeed the case, for front end calls it is likely that ajax_object.ajax_url is not set. To set this, add the following to your functions.php file -
<?php
add_action('wp_head', 'plugin_set_ajax_url');
function plugin_set_ajax_url() {
?>
<script type="text/javascript">
var ajax_object = {};
ajax_object.ajax_url = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
<?php
}
?>

Categories