Security issues while sending variable from Javascript to PHP - javascript

I'm developing JavaScript game. I need to insert some records (such as score, time, level, etc.) to database.
To do It I can use JavaScript in following:
function jsFunction() {
var jsScore = 1000;
window.location.href = "file.php?score=" + jsScore;
}
And in PHP file I could use $_GET['score'];
But looks like this way is not secure, user could change score at address bar directly in browser. Am I wrong?
How could I do It in more secure way?

Maybe sending the data via AJAX post would be more appropriate. Technically the user could still edit it using the dev console but it much less visible.
<script>
function jsFunction() {
var jsScore = 1000;
$.post( "file.php", { score: jsScore})
.done(function( data ) {
alert( "Data Loaded: " + data );
});
}
</script>

You can make use of the jquery library and send the ajax request to the php page. like below.
function jsFunction() {
var jsScore = 1000;
$.ajax({
method: "POST",
url: "file.php",
data: { score: jsScore }
}).done(function(response){
//you can perform some activity after score saved etc..
}).fail(function(response){
//you can perform some activity if score do not saved etc..
})
}
then you can access the score using $_POST['score']; in php.

Try sending data in post using ajax. This will not show data in url and is also secure as the data passes in post.Here is the code
var score = '1000';
var time = '10';
$.ajax({
url: 'file.php',
type: "POST",
data: {score: score, time: time,},
success: function(posData) {
// success code here
},
});
In file.php you can get all parameters in
print_R($_POST);

Related

Insert data into MySQL Databse with PHP/AJAX, execute success option AFTER it's inserted (Callback)

I've been trying to make a simple site, and I can't quite wrap my head around some of the things said here, some of which are also unrelated to my situation.
The site has a form with 3 input boxes, a button, and a list. The info is submitted through a separate PHP file to a MySQL database, once the submit button is clicked. I'm supposed to make the list (it's inside a div) update once the info is successfully sent and updated in the database. So far I've made it work with async:false but I'm not supposed to, because of society.
Without this (bad) option, the list doesn't load after submitting the info, because (I assume) the method is executed past it, since it doesn't wait for it to finish.
What do I exactly have to do in "success:" to make it work? (Or, I've read something about .done() within the $.ajax clause, but I'm not sure how to make it work.)
What's the callback supposed to be like? I've never done it before and I can get really disoriented with the results here because each case is slightly different.
function save() {
var name = document.getElementById('name');
var email = document.getElementById('email');
var telephone = document.getElementById('telephone');
$.ajax({
url: "save.php",
method: "POST",
data: { name: name.value, email: email.value, telephone: telephone.value },
success: $("List").load(" List")
});
}
Thank you in advanced and if I need include further info don't hesitate to ask.
From this comment
as far as i know the success function will be called on success you should use complete, A function to be called when the request finishes (after success and error callbacks are executed). isnt that what you want ? – Muhammad Omer Aslam
I managed to solve the issue simply moving the $.load clause from the success: option to a complete: option. (I think they're called options)
I haven't managed error handling yet, even inside my head but at least it works as it should if everything is entered properly.
Thanks!
(Won't let me mark as answered until 2 days)
I would first create an AJAX call inside a function which runs when the page loads to populate the list.
window.onload = populatelist();
function populatelist() {
$.ajax({
type: "POST",
url: "list.php",
data: {function: 'populate'},
success: function(data) { $("#list").html("data"); }
});
}
Note: #list refers to <div id="list> and your list should be inside this.
I would then have another AJAX call inside a different function which updates the database when the form is submitted. Upon success, it will run the populatelist function.
function save() {
var name = document.getElementById('name');
var email = document.getElementById('email');
var telephone = document.getElementById('telephone');
$.ajax({
type: "POST",
url: "list.php",
data: {function: 'update', name: name.value, email: email.value, telephone: telephone.value },
success: function() { populatelist(); }
});
}
list.php should look like this:
<?php
if($_POST['function'] == "populate") {
// your code to get the content from the database and put it in a list
}
if($_POST['function'] == "update") {
// your code to update the database
}
?>
I will show you piece of solution that I use in my project. I cannot say it is optimal or best practices, but it works for me and can work for you:
PHP:
function doLoadMails(){
//initialize empty variable
$mails;
$conn = new mysqli($_POST['ip'], $_POST['login'], $_POST['pass'], $_POST['db']);
// Check connection
if ($conn->connect_error) {
die("");
}
//some select, insert, whatever
$sql = "SELECT ... ... ... ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row, j is counter for rows
$j =0;
while($row_a = $result->fetch_assoc()) {
//for each row, fill array
$mails[$j][0] = $row_a["name"] ;
$mails[$j][1] = $row_a["mail"] ;
$mails[$j][2] = $row_a["language"] ;
$j++;
}
}
//if $mails has results (we added something into it)
if(isset($mails)){
echo json_encode($mails);/return json*/ }
else{
//some error message you can handle in JS
echo"[null]";}
}
and then in JS
function doLoadMails() {
$.ajax({
data: { /*pass parameters*/ },
type: "post",
url: "dataFunnel.php",
success: function(data) { /*data is a dummy variable for everything your PHP echoes/returns*/
console.log(data); //you can check what you get
if (data != "[null]") { /*some error handling ..., in my case if it matches what I have declared as error state in PHP - !(isset($mails))*/ }
}
});
Keep in mind, that you can echo/return directly the result of your SQL request and put it into JS in some more raw format, and handle further processing here.
In your solution, you will probably need to echo the return code of the INSERT request.

How can I refresh a PHP file with itself using Ajax?

Alright guys I'm trying to make a filter system for posts using ajax and a select box. I am able to get the value from the select box no problem. But my issue is that when I try to include the selected value in my PHP file it doesn't do anything. I have a file called public_wall.php. This file contains PHP, Javascript, and HTML. How can I refresh this div whenever a user selects a different filter option? Basically I need the selected value to be passed onto my public_wall.php file and then I want to plug it into the PHP function that fetches the posts thats's in the same file and then I want to refresh that same file to display the filtered results. Here is my Javascript code.
$("#postRatings").on("click", function(e) {
selectedRatingFilter = $("#postRatings option:selected").val();
var dataString = "timeFilter="+selectedRatingFilter;
jQuery.ajax({
type: "POST",
url: site_url+"public_wall.php",
data: dataString,
dataType: "json",
cache: false,
success: function(response){
hideSpinner();
jQuery('#postsPagingDiv').remove();
jQuery('#wsc_midbox').html(jQuery(response.htmls).fadeIn(400));
setpost_ids(response.all_post_id);
jQuery('#paging_in_process').val(0);
}
});
});
When the dataType is set to "json" nothing happens. But when it is set to html it prints some javascript code. Please help. The PHP file is too large to include here, but it basically contains PHP, HTML, and Javascript and some PHP functions that do sql queries. What is the best way to achieve a filter mechanism for my setup?
And on the public_wall.php file I want to get the value like so:
$ratingFilter = isset($_REQUEST['timeFilter']) ? intval($_REQUEST['timeFilter']) : 0;
And then plug it into the PHP function that fetches the posts which is in the public_wall.php file also so that I can filter the posts based on the selected value. And then finally I want to refresh the public_wall.php file with the new results. I hope that makes sense. Please help.
This is the output when I set my dataType to "html"
<script>
function refreshPosts() {/* only posts comments likes and count updated. */
var posts = jQuery("#all_post_id").val();
var arrays = posts.split(',');
var dataString = "postids="+posts;
jQuery.ajax({
type: "POST",
url: site_url+"includes/update_wall.php",
data: dataString,
dataType: "json",
cache: false,
success: function(response) {
var x = response;
//############ skip posts whose comments are being read by users
var ExemptedPostsIDs = jQuery("#exemptedPostsID").val();
var ExemptedArray = ExemptedPostsIDs.split(',');
ExemptedArray = ExemptedArray.sort();
//////////////
for (i=0; i<arrays.length; i++) {
var val = 'row'+arrays[i];
if(x[val]) {
if(!inArray(arrays[i], ExemptedArray))
jQuery("#ajax_wall_"+arrays[i]).html(x[val]);
} else {
jQuery('#PostBoxID'+arrays[i]).parent().fadeOut(500);
}
}
}
});
}
function inArray(needle, haystack) {
var length = haystack.length;
for (var i = 0; i < length; i++) {
if(haystack[i] == needle) return true;
}
return false;
}
function refreshWall() {/* loads new posts real time */
var posts = jQuery("#all_post_id").val();
var pageUsing = jQuery('#pageUsing').val();
var dataString = "update_posts=1&postids="+posts+'&pagex='+pageUsing;
jQuery.ajax({
type: "POST",
url: site_url+"public_wall.php",
data: dataString,
dataType: "json",
cache: false,
success: function(response) {
if(response.all_post_id) {
jQuery('#wsc_midbox').prepend(jQuery(response.htmls).fadeIn(400));
setpost_ids(response.all_post_id);
}
}
});
}
</script>
I suggest you keep the form with select element and any JavaScript on the outer frame.
Via ajax, only load the results to a seperate DIVision below that.
When you put an Ajax response to a div, any JavaScript inside it will not be executed.
For the best throughput with Ajax, you should consider loading a json response via Ajax and create HTML elements on the client side. That way it becomes much easier to pull additional variables to front-end JS from server side along with the same request/response.
But that becomes bit difficult when you have a template engine in the back-end. You can still send the HTML content in a json value, so you can easily pass the "all_post_id" as well..

Pass a value to multiple PHP pages at once with JQuery

My inexperience has me here asking this question.
Can I pass a value to multiple PHP pages in JQuery?
Here is an example of what I am trying to do.
$(function() {
$("#account").change(function() {
$("#facilities").load("displayfacilities.php?q=" + $("#account").val());
$("#facilities").load("updatefacilities.php?f=" + $("#account").val());
});
});
When the user changes a selection within a drop down list, a unique ID will be sent over to displayfacilities.php. I also need that ID in updatefacilities.php which is called from displayfacilities.php.
Is this a bad idea, or is there a better way?
Try to make use of $_SESSION and example of the usage.
This object allows you to store and retrieve data and a usual use case is to share this data across multiple pages within a session.
ex.
$(function() {
$("#account").change(function() {
// store value in superglobal variable and retrieved
// by session_start() in php script, see usage examples above
<?php $_SESSION['some_key'] = *some_value* ?>
// the following value however needs to be sent to server
// either via AJAX or some request.
$("#account").val();
});
});
Hope this helps.
Check this out,
First call ajax, when the response is received, make the second ajax call.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$("#account").change(function() {
var dataString1 = "q="+$("#account").val();
$.ajax
({
url: "displayfacilities.php",
type : "POST",
cache : false,
data : dataString1,
success: function(result1)
{
alert("Response from PHP file 1");
var dataString2 = "f=" + $("#account").val();
$.ajax
({
url: "updatefacilities.php",
type : "POST",
cache : false,
data : dataString2,
success: function(result2)
{
alert("Response from PHP file 2");
}
}
});
});
});
});
</script>

How to send a JQuery Variable to another PHP page via dblclick()?

So guys, I made a listbox and if I dblclick to an item the value of it gets saved into "val", but I can't send it to the next PHP File. I also alerted "val" - the value is really saved in it. I also get the function succes displayed in the browser console. what to do?
thanks
My Function:
$(document).ready(function () {
$("option").dblclick(function () {
var lb = document.getElementById("liste");
var val = lb[lb.selectedIndex].value;
$.ajax({
type: 'POST',
url: 'about.php',
dataType: 'HTML',
data: {
aufid: val
},
success: function (data) {}
});
});
});
PHP Code in about.php:
$id = $_POST['aufid'];
Can you try to see what variables are in the $_POST superglobal?
print_r($_POST);
try to set the url your full adrees
url: 'http://myadress.com/about.php',
java script is running on your local computer so it might send the request to you own pc where no about.php exist

Page Loading Problems - AJAX Related?

I'm running a test website for a bit for me and my friends to play around with before I roll it into my actual site.
One of the things this test website does is have a "feed" where users can insert text/images and etc. through a form.
I use AJAX for inserting content into the "feed" and also use it to refresh the feed.
However after a user plays with it for a while and posts stuff, they eventually can't post or load the page.
I'm a beginner to AJAX or whatever, but what is the cause of this? Is it AJAX related since I'm sending requests often? (10,000 ms too much?)
function WallPost() {
REQUESTED_NAME = document.registerForm.NAME.value;
REQUESTED_BODY = document.registerForm.BODY.value;
if (!localStorage.name) {
localStorage.name = REQUESTED_NAME;
}
$.ajax({
type: "POST",
url: "/wall.php",
data: "NAME=" + REQUESTED_NAME + "&BODY=" + REQUESTED_BODY + "&FORM=1&IP=i",
success: function(msg) {
$("#registerMessage").append(msg);
}
});
document.registerForm.BODY.value = "";
RetrieveWall();
}
function RetrieveWall() {
$.ajax( {
url: "/getwall.php",
success: function(msg2) {
$("#wall").html(msg2);
}
});
window.setTimeout("RetrieveWall()", 10000);
}
$.ajax( {
url: "/getip.php",
success: function(i) {
IP = i;
}
});
10 seconds seems fine, so I doubt the problem is the frequency.
To determine the true problem we would need either javascript console output and/or server logs.

Categories

Resources