Proper way to handle Ajax response in PHP - javascript

I'm using Ajax to logout from page.
index.php
Logout
custom.js
$(document).ready(function () {
$('.logout-button').click(function () {
dataUrl = "mode=logout";
$.ajax({
url: "ajax.php",
type: "POST",
data: dataUrl,
success: function (data) {
if (data == "OK") {
location.href = 'login.php';
}
}
});
});
});
ajax.php
session_start();
$mode = $_POST['mode'];
if ($mode == 'logout'){
session_unset();
session_destroy();
$_SESSION = array();
echo "OK";
}
Sometimes it works as it should. But sometimes it just reload to same page, even if session is already deleted.
What am I doing wrong?

Related

Security measures for AJAX-PHP scripts

For a link like this
DELETE
i am using this ajax call
$(function() {
$(".delete_msgs").click(function() {
var msgid = $(this).attr("id");
var dataString4 = 'msgid=' + msgid;
$('a#'+msgid).html('<img src="img/loader.gif" class="loading" />');
$.ajax({
type: "POST",
url: "del_msg.php",
data: dataString4,
cache: false,
success: function(data){
if (data == 0) {
//alert('Sent!');
} else {
$('a#'+msgid).html(data);
$('.viewmessage'+msgid).hide();
}
}
});
return false;
});
});
The del_msg.php file contains that code:
if(isset($_POST)) {
$msgid = $_POST['msgid'];
$delmsg = mysql_query("DELETE FROM messages
WHERE id = $msgid") or die(mysql_error());
echo 'Message sent!';
} else {
echo 0;
}
My big question is, how can i protect my send throught AJAX function? Anyone can change the id of the #a element and, consequently, can delete any row from my database.
Is there a more secure way to call php with ajax, or at least, to hide my important variables sent via ajax?

Not recieving values sent via AJAX POST to PHP

I'm trying I'm trying to send a specific section of my URL string, to my php file, to then populate my page accordingly. Everything is working fine, except for the AJAX POST method. I've tried doing var_dump of the POST variable in my PHP, and my array is empty (so I know nothing is getting through).
The success DOES return as being passed, so I don't know where the data is going. I'm testing locally on XAMPP, and I've combed through SoF and no luck on any of the fixes. My code is below.
Screen shot of page:
jQuery AJAX Request:
$(document).ready(function() {
str = window.location.href;
pos = str.search("pages/"); //42
send = str.slice(42, -5);
console.log(send);
console.log(pos);
$.ajax({
type: "POST",
url: "retrieve.php",
data: {
tom: send
},
success: function() {
$.get("retrieve.php", function(data, status) {
$("#main").html(data);
}) //ends GET function
},
error: function() {
console.log(arguments)
}
}); //ends POST request
}); //ends DOC-READY function
PHP:
echo "<i>hello</i>";
echo var_dump($_POST);
$url = $_POST['tom'];
json_decode($url);
echo $url;
Try the below,
Also you don't need to json_decode unless you send a json request,And please make sure all the post values are passing.
Ajax:
$(document).ready(function() {
var str = window.location.href;
var pos = str.search("pages/"); //42
var send = str.slice(42, -5);
console.log(send);
console.log(pos);
$.ajax({
type: "POST",
url: "retrieve.php",
data: {
'tom': send//make sure this is not empty
},
success: function(data) {
console.log(data);
},
error: function(arguments) {
console.log(arguments)
}
}); //ends POST request
}); //ends DOC-READY function
PHP:
if($_SERVER['REQUEST_METHOD'] == 'POST'){
//echo "<i>hello</i>";
//echo var_dump($_POST);
$url = $_POST['tom'];
json_encode($url);
echo $url;
}

How to avoid 500 Internal Server Error if a JS session variable null

I created this script to read from various web sources. This script updates all notifications (mail, post, friends) and their own drop-down window's details and also two side update bars together. I used this script in my top manu.php page.
This script is working well for login user.
Now I pass a session id variable with JavaScript var uid = '<? echo $session->id; ?>'; So when a user is not logged in, my browser console displays 500 Internal Server Error because here the session has no ID so it passes uid= ''
How do I overcome this problem?
Here is my JavaScript script:
var uid = '<? echo $session->id; ?>';
function addmailno(type, msg){
//Do something for display mail/friend/post notification
}
function addmailup(type, msg){
//Do something for display mail/post/friend drop-down.
}
function addside(type, msg){
//Do something for display all friend/new post in side bar.
}
function waitFormailno(){
$.ajax({
type: "GET",
url: "serverforupandside.php",
cache: false,
async : false,
dataType : 'json',
data: "uid="+ uid,
timeout:15000,
success: function(data){
addmailno("MyDivClass", data);
addmailup("MyDivClass", data);
addside("MyDivId", data);
setTimeout(waitFormailno, 15000);
},
error: function(){
setTimeout(waitFormailno, 15000);
}
});
}
$(document).ready(function(){
waitFormailno();
});
serverforupandside.php
<?php
include("db.php");
include_once("mysession.php");
while (true) {
if($_GET['uid']){
global $dbh;
//All php query is here one after one
//Output is here by data
$data = array();
$data['upmail'] = $upmail;
$data['upfollow'] = $upfollow;
$data['uppost'] = $uppost;
// etc all
if (!empty($data)) {
echo json_encode($data);
flush();
mysqli_close($dbh);
}
}
mysqli_close($dbh);
}
?>
Your Javascript code should be modified to:
function waitFormailno(){
$.ajax({
type: "GET",
url: "serverforupandside.php",
cache: false,
async : false,
dataType : 'json',
data: "uid="+ uid,
timeout:15000,
success: function(data){
addmailno("MyDivClass", data);
addmailup("MyDivClass", data);
addside("MyDivId", data);
}
});
}
$(document).ready(function(){
setInterval(waitFormailno, 15000); // calls a function or evaluates an expression at specified intervals (in milliseconds)
});
PHP Code:
<?php
include("db.php");
include_once("mysession.php");
if (!empty($_GET['uid'])) {
global $dbh;
//All php query is here one after one
//Output is here by data
$data = array();
$data['upmail'] = $upmail;
$data['upfollow'] = $upfollow;
$data['uppost'] = $uppost;
// etc all
if (!empty($data)) {
echo json_encode($data);
}
}
Also, you should add validations before filling $data array.

what is required to run ajax - does adding jquery to page processes ajax calls?

I am new to ajax and running xampp on my localhost
I want to communicate with server by using ajax in my own created page.
I want to know is there anything required to add in head section to use ajax calls ?
In my web page's head section there is no javascript file incluided other than this jquery file
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
is this sufficient to make ajax calls like
<script type="text/javascript" language="javascript">
$('#enter').click(function(event){
event.preventDefault();
$.ajax({
type: 'GET',
url: 'functions.php?id=enter_game',
//data: {id: 'enter_game'},
dataType: 'json',
cache: false,
success: function(result) {
if(result){
resultObj = eval (result);
alert( resultObj );
}else{
alert("error");
}
}
});
});
</script>
and in functions.php file
<?php
include("connection_to_db.php");
function is_sufficient_users()
{
$result = mysql_query("SELECT * FROM ".$dbprefix."users") or die ( mysql_error() );
if(mysql_num_rows($result) >= 3 ){
// sufficient users
// start the game
$data = array();
//$word = start_game();
$word = 'Apple';
while($row = mysql_fetch_assoc($result)){
$data['id']['name'] = $row['name'];
$data['id']['ghost'] = $row['ghost'];
}
$data['word'] = $word;
$data['game'] = "Game Starts";
echo json_encode($data);
}else{
$data = array();
switch(mysql_num_rows($result))
{
case 0:
$waiting = 3;
break;
case 1:
$waiting = 2;
break;
case 2:
$waiting = 1;
break;
default:
$waiting = 3;
break;
}
$data['game'] = "Waiting for ".$waiting." more users to start the game" ;
echo json_encode($data);
}
}
if(isset($_GET['id']) && strtolower($_GET['id']) == "enter_game"){
is_sufficient_users();
}
?>
but there is no response, I tried several changing but no success.
Is there a fault in my code or I am not including the ajax connection file or something ?
Any help would be much appreciated.
From your code here
<script type="text/javascript" language="javascript">
$('#enter').click(function(event){
event.preventDefault();
$.ajax({
type: 'GET',
url: 'functions.php?id=enter_game',
//data: {id: 'enter_game'},
dataType: 'json',
cache: false,
success: function(result) {
if(result){
resultObj = eval (result);
alert( resultObj );
}else{
alert("error");
}
}
});
});
</script>
you have commented the data that is being sent to the functions.php page. And in functions.php page you are checking for $_GET['id'] which is not present.
Other than that there is no problem in your code, considering you have the right db connection and the jQuery file is loaded.
If you still have doubt then go with the following code for just testing
<script type="text/javascript" language="javascript">
$('#enter').click(function(event){
event.preventDefault();
$.ajax({
type: 'GET',
url: 'functions.php?id=enter_game',
cache: false,
success: function(result) {
console.log(result);
}
});
});
</script>
functions.php
<?php
echo "This is just to see if Ajax is working and it does !";

ajax request to codeigniter controller from javascript

I am making an ajax request from my codeigniter view in javascript function but nothing happens and the success alert (ok) pops up
function show_drop_downn(){
document.getElementById("drop_downn").style.visibility = "visible";
$.ajax({
type: "POST",
url: "http://localhost/ok/index.php/search/ajax_delete_ntify",
success: alert('ok'),
});
}
This is my controller it is working perfect, when i copy paste the url (used in ajax request) in my browser every thing goes good, controller makes a call to the model and it works perfect
function ajax_delete_ntify()
{
echo "incontroller";
$email=$this->session->userdata('email_of_user');
$this->load->model('search_peoplee');
$data['userid']= $this->search_peoplee->get_userid_from_email($email);
foreach ($data['userid'] as $row)
{
$one=$row->userid;
}
$this->search_peoplee->delete_notifications($one);
return;
}
View :
function show_drop_downn(){
document.getElementById("drop_downn").style.visibility = "visible";
$.ajax({
type: "POST",
url: "http://localhost/ok/index.php/search/ajax_delete_ntify",
success:function(
console.log("success");
)
});
}
Controller :
function ajax_delete_ntify()
{
echo "incontroller";
$email=$this->session->userdata('email_of_user');
$this->load->model('search_peoplee');
$data= $this->search_peoplee->get_userid_from_email($email);
$res=$this->search_peoplee->delete_notifications($data[0]->userid);
if($res){
echo json_encode(array('success'=>true));
}else{
echo json_encode(array('success'=>false));
}
}

Categories