ReactJS and PHP Sessions [duplicate] - php

I am using Fetch Api in my application.
I've got a PHP server page to get session data which was already defined before. It seemd like this:
<?php
header('Content-Type: application/json; charset=UTF-8');
header('Access-Control-Allow-Origin: *');
session_start();
// $_SESSION['data'] already defined before
$result = array();
// print_r($_SESSION['data']);
if (isset($_SESSION['data'])) {
$result = $_SESSION['data'];
$result['code'] = 'ok';
} else {
$result['code'] = 'error';
}
echo json_encode($result, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
I also got another html page to get the session data. It seemd like this:
<script>
$(function() {
// use $.ajax
$.ajax({
url: 'session.php',
dataType: 'json'
})
.done(function(res) {
console.log(res);
});
// end
// use fetch
fetch('session.php').then(function(res) {
if (res.ok) {
res.json().then(function(obj) {
console.log(obj);
});
}
});
// end
});
</script>
The problem is, when I use $.ajax(), session data can be correctly showed. But when I use fetch(), the session data was undefined.
So, what goes wrong and how can I fix it? Thanks!

If you want fetch to send cookies, you have to provide the credentials option.
See https://developer.mozilla.org/en-US/docs/Web/API/GlobalFetch/fetch#Parameters for details.

jquery ajax is a usual ajax request and the browser is sending the cookie header with the session id that identify your session.
fetch doesnt - instead a new session is created with out any data
send the php session id either with url or header
have a look at: http://php.net/manual/en/session.idpassing.php

Related

Ajax is not working in server but works fine in local host

Ajax call is not working in entire site. But works fine in localhost. I cannot able to debug this issues.
I have used ajax entire website. I totally fed up.
Anyone please help me to fix this bug!!
One of my Sample Ajax Code:
function advanced_addTopic(cid) {
$.ajax({
url: "assets/php/checkSubtopicStatus.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: {'cid':cid}, // Data sent to server, a set of key/value pairs (i.e. form fields
success: function(data) // A function to be called if request succeeds
{
if(data==="True"){
$("#subtopicDiv").html($("#subtopicDiv"+cid).html());
$("#advanced_testid").val(cid);
var hiddenCourse=$("#createTest").attr('class');
$("#courseHidden").val(hiddenCourse);
$("#advanced_addquestionModal").modal('show');
$("#subtopic").focus();
$("#question").focus();
var tempVal=$("#getID").text();
$("#advanced_courseHidden").val(cid);
} else {
alert("Create subtopics to insert questions!");
}
}
});
My PHP Code is here:
<?php
class loginValidation {
function validate()
{
ob_start();
session_start();
include "../../connection.php";
$id=$_POST['cid'];
$query = mysql_query("select * from advanced_subtopic where testid='$id'");
if(mysql_num_rows($query)>0) {
echo "True";
}
else {
echo "False";
}
}
}
$loginValidation=new loginValidation;
$loginValidation->validate();?>
My Concosole Log
CONSOLE RESPONSE
Instead of
(data==="True")
we should code like
($.trim(data)=="True")
Should trim the data to avoid unwanted space.
Problem solved.

How do i get a php return value via Ajax?

Im creating a validation form in Ajax and PHP. But i don't have a clue how i should get the value from PHP??
For example:
The validation form is in index.php And the page with the function is checkUser.php.
In checkUser i have a global file included with my classes initialized. The checkUser.php look like this:
<?php
$requser = false;
require "core/rules/glb.php";
$user->checkUser($_GET['username']);
The get function comes from the Ajax call i do in the index file. But how do i know that PHP said that the username already exist så that i can make a if statement and paus the script?
Im a beginner, thanks.
And sorry for my english
$.ajax({
type: "GET",
url: "user_add.php",
data: 'username='+$("#jusername").val()+'&email='+$("#jemail").val()+'&password='+$("#jpassword").val()+'&secureSession=23265s"',
success: function()
{
location.href='register.php';
}
});
Jus print out the data, for better help also post the ajax script
<?php
$requser = false;
require "core/rules/glb.php";
print $user->checkUser($_GET['username']);
If you are trying to give a response to the ajax call from php, then you can do it via normal output. Just like
echo json_encode(array("status"=>"FAIL"));
exit();
will send a json response to the ajax call from the php script. like
{"status":"FAIL"}
which you can parse it at the ajax callback and check the status. like
var data = JSON.parse(response);
if(data.status == "FAIL") {
alert("Ajax call returned failed");
}

How to read POST Request data in PHP sent from AngularJS

I am trying to make a post request from my angular js, as below
var postData={
firstName:'VenuGopal',
lastName:'Kakkula'
};
postData=JSON.stringify(postData);
$http({method:'POST',url:'http://localhost/blog/posttest.php?insert=true',data:postData,headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
.success(function (data,status,headers,config) {
alert('Success' + data);
})
.error(function (data, status,headers,config) {
// uh oh
alert('error' + status + data);
});
I am not sure how to read this POST DATA in my PHP REST webservice.
<?php
header("Access-Control-Allow-Origin:*");
header('Access-Control-Allow-Headers:Content-Type');
header("Content-Type:application/json");
if(!empty($_GET['insert']))
{
$result=json_decode($_POST['firstName']);
deliver_response(200,"Got the Post data","GotData $result");
}
function deliver_response($status,$statusmsg,$data)
{
header("HTTP/1.1 $status $statusmsg");
$response['status']=$status;
$response['status_message']=$statusmsg;
$response['data']=$data;
$json_response=json_encode($response);
echo $json_response;
}
?>
I tried the below options
json_decode($_POST['firstName'])
json_decode($_POST['data'])
json_decode($_POST['[postData'])
None of them returned the data, Its always returning the error Undefined index: firstName in F:\xampp\htdocs\Blog\posttest.php on line 10
Can anybody help me how I can read the POST request data sent in php file.
Most likely it is because you are submitting JSON data which is not automagically populated into the $_POST variable per standard form data.
The work around is to manually parse the input into a variable for use.
Example:
<?php
$args = json_decode(file_get_contents("php://input"));
echo $args->firstName;
?>
You can also solve this problem without changing code in server and use $_POST the regular way. Explained here: http://victorblog.com/2012/12/20/make-angularjs-http-service-behave-like-jquery-ajax/

jQuery JSON PHP Request

I've been trying to figure out what I have done wrong but when I use my JavaScript Console it shows me this error : Cannot read property 'success' of null.
JavaScript
<script>
$(document).ready(function() {
$("#submitBtn").click(function() {
loginToWebsite();
})
});
</script>
<script type="text/javascript">
function loginToWebsite(){
var username = $("username").serialize();
var password = $("password").serialize();
$.ajax({
type: 'POST', url: 'secure/check_login.php', dataType: "json", data: { username: username, password: password, },
datatype:"json",
success: function(result) {
if (result.success != true){
alert("ERROR");
}
else
{
alert("SUCCESS");
}
}
});
}
</script>
PHP
$session_id = rand();
loginCheck($username,$password);
function loginCheck($username,$password)
{
$password = encryptPassword($password);
if (getUser($username,$password) == 1)
{
refreshUID($session_id);
$data = array("success" => true);
echo json_encode($data);
}
else
{
$data = array("success" => false);
echo json_encode($data);
}
}
function refreshUID($session_id)
{
#Update User Session To Database
session_start($session_id);
}
function encryptPassword($password)
{
$password = $encyPass = md5($password);
return $password;
}
function getUser($username,$password)
{
$sql="SELECT * FROM webManager WHERE username='".$username."' and password='".$password."'";
$result= mysql_query($sql) or die(mysql_error());
$count=mysql_num_rows($result) or die(mysql_error());
if ($count = 1)
{
return 1;
}
else
{
return 0;;
}
}
?>
I'm attempting to create a login form which will provide the user with information telling him if his username and password are correct or not.
There are several critical syntax problems in your code causing invalid data to be sent to server. This means your php may not be responding with JSON if the empty fields cause problems in your php functions.
No data returned would mean result.success doesn't exist...which is likely the error you see.
First the selectors: $("username") & $("password") are invalid so your data params will be undefined. Assuming these are element ID's you are missing # prefix. EDIT: turns out these are not the ID's but selectors are invalid regardless
You don't want to use serialize() if you are creating a data object to have jQuery parse into formData. Use one or the other.
to make it simple try using var username = $("#inputUsername").val(). You can fix ID for password field accordingly
dataType is in your options object twice, one with a typo. Remove datatype:"json", which is not camelCase
Learn how to inspect an AJAX request in your browser console. You would have realized that the data params had no values in very short time. At that point a little debugging in console would have lead you to some immediate points to troubleshoot.
Also inspecting request you would likely see no json was returned
EDIT: Also seems you will need to do some validation in your php as input data is obviously causing a failure to return any response data
Try to add this in back-end process:
header("Cache-Control: no-cache, must-revalidate");
header('Content-type: application/json');
header('Content-type: text/json');
hope this help !
i testet on your page. You have other problems. Your postvaribales in your ajax call are missing, because your selectors are wrong!
You are trying to select the input's name attribute via ID selector. The ID of your input['name'] is "inputUsername"
So you have to select it this way
$('#inputUsername').val();
// or
$('input[name="username"]').val();
I tried it again. You PHP script is responsing nothing. Just a 200.
$.ajax({
type: 'POST',
url: 'secure/check_login.php',
dataType: "json",
data: 'username='+$("#inputUsername").val()+'&password='+$("#inputPassword").val(),
success: function(result) {
if (result.success != true){
alert("ERROR");
} else {
alert("HEHEHE");
}
}
});
Try to add following code on the top of your PHP script.
header("Content-type: appliation/json");
echo '{"success":true}';
exit;
You need to convert the string returned by the PHP script, (see this question) for this you need to use the $.parseJSON() (see more in the jQuery API).

$.post json request doesn't return any result

Well, another try:
this is all the jquery code i'm using maybe i made something wrong in the code before $.post(); i call the following function with the onclick of the same form...
function setLogin()
{
$('#login-form').submit(function(e) {
e.preventDefault();
//passing form field to vars
var formUsername=$("#login-form #username").val();
var formPassword=$("#login-form #password").val();
//checks on fields lenght
if((formUsername.length<6))
{
$("#ajax-output").html("<div class='error'>Attenzione username troppo breve!</div>");
}
else if((formPassword.length<6))
{
$("#ajax-output").html("<div class='error'>Attenzione password troppo breve!</div>");
}
else
{
$.post(
//the url
'?module=login',
//data got from login form
{
"username": formUsername,
"password": formPassword,
},
//response
function(data){
$("#ajax-output").html(data.reply)
},
//type
"json"
);
}
});
}
i tried with only this code in php file and it still doesn't return anything...
function Login()
{
//just to try
echo json_encode(array('reply'=>'foo'));
}
it still doesn't work...
Are you sure the post is being run in the first place?
Use Firebug! (or chrome's built-in developer tools)
You can use firebug to pick apart every bit of a web page.
It has a "net" tab that shows every request that is made by the browser, including AJAX requests, and their results, headers and contents.
Use it to see if your requests is really being made, and what the result is. Then take it from there.
Make sure that you're setting a header for the content type when responding - the browser may not attempt to use the JSON if it doesn't know it's receiving JSON.
function Login()
{
header('Content-Type: application/json');
echo json_encode(array('reply'=>'foo'));
}

Categories