Laravel session variable remove after page load when set by ajax - php

I have a simple ajax code which saves the category and subcategory id in session. These two variables save in session but on next reload both values does not exist in session.
This session issue is only with ajax. I have other points where i am storing and retrieving session and it is working file.
Here is my ajax call.
$("#search-select-category").on("click", function () {
console.log("sending ajax");
$.ajax({
type: "POST",
url: $("#select-category-search").prop('action'),
data: {
"_token": $("#select-category-search").find('input[name=_token]').val(),
"category_id": $("input[name='category-search']").val(),
"subcategory_id": $("input[name='subcategory-search']").val(),
},
success: function (response) {
var response = JSON.parse(response);
console.log(response.message);
if(response.error) {
console.log("error is here");
$(".search-category-error span").text(response.message);
$(".search-category-error").show();
}
else {
console.log("selection is good");
$(".search-category-error").slideDown();
$(".select-category-modal").modal('hide');
}
}
});
});
and the function that executes on ajax call is as follows
public function ajax_select_category_search(Request $request) {
$error = false;
$message = "";
if (empty($request->category_id) || empty($request->subcategory_id)) {
$error = true;
$message = "Category or Sub Category is not selected";
}
if ($error == false) {
session(['category_search' => $request->category_id]);
session(['subcategory_search' => $request->subcategory_id]);
}
$response['error'] = $error;
$response['message'] = $message;
echo json_encode($response);
die();
}
I have tried using file and database session but same problem in both cases. I am using laravel 5.3
Session class is also imported in the class i am using and there are no errors when i use this function.

The reason is i had a die() in the php ajax function. I don't know why remove added session when you have a die() in your ajax call. However i removed the die() and it worked perfectly.

Related

Ajax post does not give value to php file, post becomes get

I have this ajax function for login.
Edit: I just noticed that this server runs php7 while other server where the login does work uses php5. What has changed in php that this script doesn't work anymore?
Edit 2: Looks like the server request method isn't post but changed to get, why?
Solution: needed to remove the .php from url: "./ajaxcall/login.php", because I use pretty url htaccess.😅
var InName = $('#InName').val();
var InPass = $('#InPass').val();
alert(InName);
$.ajax({
type: "POST",
url: "./ajaxcall/login.php",
dataType: "json",
data: {InName:InName, InPass:InPass},
error: function (request, error) {
console.log(arguments);
alert("Inlog Can't do because: " + error);
},
success : function(data){
if (data.code == "200"){
$("#InErEr").html(data.msg);
//window.location.reload(true);
} else {
$("#InErEr").html(data.msg);
$('.lds-dual-ring').animate({opacity: 0}, 300);
}
}
});
On the alert(InName); I get the correct value of the username. But when I check in my php file $_POST['InName'] it is empty.
Part of php file
include('../config.php');
if(empty($_POST['InName'])) {
$Ierror = 'Username is required.';
}
if($_POST['InPass'] == '') {
$Ierror = 'Password is required.';
}
$username = $_POST['InName'];
$passwordL = $_POST['InPass'];
// count user in between //
if($Inlognumber_of_rows == 0) {
$Ierror = 'Username not found.';
} else {
// password check //
if(password_verify($salty_pass, $hashed_password)) {
} else {
$Ierror = 'Password incorrect.';
}
}
if ($Ierror == '') {
// do login //
} else {
$showerror = '<span style="color:#F00;">'.$Ierror.$username.$passwordL.$_POST['InName'].$_POST['InPass'].'</span>';
echo json_encode(['code'=>404, 'msg'=>$showerror]);
exit;
}
In the return message, $showerror I only get, Username not found, without the posted values. So the login is not working because of empty values? User is also present in the database of course. I also don't get the empty $_POST errors. So to cap up, in javascript I get the correct value for InName but not in php.
You are close but your error catch is not correct ... try this (Jquery):
var InName = 'something';
var InPass = 'morething';
$.post("./ajaxcall/login.php", {
InName: InName,
InPass: InPass
}, function(data, status) {
console.log(data, status);
}).done(function() {
alert("second success");
})
.fail(function() {
alert("error");
})
.always(function() {
alert("finished");
});
on your php file just do print_r($_POST); and you will receive this in your console...:
Array
(
[InName] => something
[InPass] => morething
)
success
Basically you were trying to print the error where you should have consoled log the request.responeText...
A good trick to know if posts arrived to the php even if the console.log won't show is doing this in the php file:
<?php
print_r($_POST) ;
$newfile = fopen('newfile.txt','a');
fwrite($newfile,json_encode($_POST));
fclose($newfile);
This will print and also store on a local file the post data....
Solution: needed to remove the .php from url: "./ajaxcall/login.php", because I use pretty url htaccess.😅

Send custom error message in Ajax error in codeigniter

I am currently using Codeigniter and working on CRUD operation in one HTML form.
I am using Ajax for this create/read/update.
I have also used Transaction Management as best practices in a database query.
The Problem:
(1) I want separate Error message for Update and Insert Error. Which I did not get in the ajax error section.
(2) I have used the debugger to debug this problem but I do not get it proper.
Here is the Code of my controller.
Controller:
public function save_candidate_experience() {
$this->db->trans_start();
if(empty($postId))){
$query_staus = $this->test_model->insert_function( $data );
if($query_staus != TRUE) {
$msg = array('message'=>'Failed To Save! Erroe Wile Inserting.');
} else{
$msg = array('message'=>'Successfully Insert');
}
} else {
$query_staus2 = $this->test_model->update_function( $data );
if($query_staus2 != TRUE) {
$msg = array('message'=>'Failed To Save! Erroe Wile Updateing.');
}else{
$msg = array('message'=>'Successfully Updated');
}
}
if ($this->db->trans_status() === FALSE)
{
$this->db->trans_rollback();
echo json_encode ($msg);
}
else
{
$this->db->trans_commit();
echo json_encode ($msg);
}
}
This is the Model Code:
public function insert_function() {
$this->db->insert('table_name', $data);
if($this->db->affected_rows() > 0){
return TRUE;
} else{
return FALSE;
}
}
public function update_function() {
$this->db->where('id', $id);
$this->db->update('test_table', $data);
if($this->db->affected_rows() > 0){
return TRUE;
} else{
return FALSE;
}
}
Ajax Code in my view.
$.ajax({
type: 'POST',
async: true,
dataType: 'Json',
url: save_experience,
data: $('#candidata_exp_form').serialize(),
success: function (response) {
//doing something with ajax success
},error: function (msg)
{
alert(msg.message);
// I know I can give alert message here but.
//I don't want to give alert message here.
//I want to indicate user that the error occure whilt insert or update seperately.
}
});
You have to understand 2 things.
Form validation error and ajax error is different.
Ajax error - Is not validation error.
It means, suppose you call a function and there is php error in that function, or 404 error. At that time .error() will be called.
Ajax Success - No error(No syntax error).
So now you should write the logic in ajax success().
$.ajax({
type: 'POST',
async: true,
dataType: 'Json',
url: save_experience,
data: $('#candidata_exp_form').serialize(),
success: function (response) {
alert(response.message);// this will alert you the message which you have put in `json_encode()`
}
});

Having trouble setting cookie via AJAX login with Yii2

I'm using Yii2 and I have setup a login process which works fine (cookies as well) via the standard login page which is not AJAX.
I have built a dropdown login field which works fine at logging them in, however it doesn't seem to set the cookie as the user doesn't stay logged in and there is no bookie created.
I figured that this was because of AJAX and the cookie wasn't being created on the users system, but upon further reading it seems it should work.
I have verified that the cookie value is being set correctly, the only issue is the cookie doesn't seem to being created.
My login code:
JS:
function doLogin() {
// Set file to prepare our data
var loadUrl = "../../user/login/";
// Set parameters
var dataObject = $('#login_form').serialize();
// Set status element holder
var status_el = $('#login_status');
// Make sure status element is hidden
status_el.hide();
// Run request
getAjaxData(loadUrl, dataObject, 'POST', 'json')
.done(function(response) {
if (response.result == 'success') {
//.......
} else {
//.......
}
})
.fail(function() {
//.......
});
// End
}
function getAjaxData(loadUrl, dataObject, action, type) {
if ($('meta[name="csrf-token"]').length) {
// Add our CSRF token to our data object
dataObject._csrf = $('meta[name="csrf-token"]').attr('content');
}
return jQuery.ajax({
type: action,
url: loadUrl,
data: dataObject,
dataType: type
});
}
Controller:
public function actionLogin() {
// Check if they already logged in
if (!Yii::$app->user->isGuest and !Yii::$app->request->isAjax) {
return $this->redirect('/');
}
if (Yii::$app->request->isAjax) {
// Set our data holder
$response = ['output' => '', 'result' => 'error'];
}
// Let's send the POST data to the model and see if their login was valid
if (Yii::$app->request->isAjax and $this->user->validate() and $this->user->login()) {
$response['result'] = 'success';
} elseif (!Yii::$app->request->isAjax and Yii::$app->request->isPost and $this->user->validate() and $this->user->login()) {
//.......
} else {
//.......
}
if (Yii::$app->request->isAjax) {
echo Json::encode($response);
}
}
Model:
public function login() {
// Set cookie expire time
$cookie_expire = 3600 * 24 * Yii::$app->params['settings']['cookie_expire'];
return Yii::$app->user->login($this->getUser(), ($this->remember_me ? $cookie_expire : 0));
}
As I suspected (see my earlier comment) response might not be correctly generated in case of simply echoing the data. Or maybe Content-Type header matters. If someone can confirm this it will be great.
Anyway, I'm glad it works now (data needs to be returned).
And you can use Response handy format as well.
public function actionLogin() {
// ...
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return $response;
}
}

codeigniter function load two pages of same function calls in different ways

I am using two ways for user login in codeigniter:
One is by typing url like this localhost/mySite/login
Other is popup dialog appear when I click a link from localhost/mySite
When I'm following step 2 then calling a function using ajax request.
both time I am calling same function. but when call to the function using Ajax load an additional header.
I used following code for the calling function.
if ($this->input->is_ajax_request()){
echo json_encode(array('status'=>'success','url'=>'auth/enable_account'));
exit();
}
else {
redirect ( "auth/enable_account",'refresh');
}
My jquery code
jQuery('#signin_form').submit(function(event) {
var email = jQuery('#email').val();
var password = jQuery('#password').val();
var remember = jQuery('.dev_signin_remember').is(':checked');
jQuery.ajax({
url:baseurl+'auth/login',
type:'POST',
data:{'email':email,'password':password,'remember':remember},
dataType:'json',
success:function(data){
if(data.status == 'success') {
if(data.url != '') {
window.location.replace(baseurl+data.url);
}
else {
window.location.replace(baseurl+"auth/login");
}
}
else {
jQuery('.dev_signin_error').html('Invalid Username or password');
}
}
});
setTimeout(jQuery.unblockUI);
});

Pass data from JQuery to database via Javascript/AJAX/JSON/PHP

I am attempting to add data to my database from my HTML code via the use of JQuery, AJAX/JSON and PHP using an MVC model. Below is a small sample of what I am looking to achieve.
In my front end I have a checkbox with different options and a button named 'Add'. The selected elements from here are picked up by a Javascript function, which I have tested properly, once this is done I call another Javascript function to do the AJAX/JSON . What I am still fresh on is the actual AJAX/JSON process that sends the data to PHP.
My Javascript function:
function add_fruits(fruit_name, fruit_type){
var success = "Fruit added";
var error = "Fruit not added";
var params = {
'fruit_name' : fruit_name,
'fruit_type' : fruit_type
};
$.ajax({
type: "POST",
url: "add_fruits.php",
async: false,
data: params,
success: function(success){
alert(success);
},
error: function(error){
alert(error);
}
});
}
My PHP function:
<?php
header("Access-Control-Allow-Origin: *");
header('Content-type: application/json');
require_once 'lib/connection_files.php';
if($_SERVER['REQUEST_METHOD'] =='POST')
{
$fruit_name = no_sql_injection($_POST['fruit_name']);
$fruit_type = no_sql_injection($_POST['fruit_type']);
$fruits = new fruits();
$result = $fruits->add_fruits($fruit_name, $fruit_type);
$tmp = mysql_num_rows($result);
if($result == 1)
{//RESULT must return 1 to verify successful insertion to database
//send confirmation to front end
}
else
{
//send error message to front end
}
}
else{
//tell front end there was error sending data via AJAX
}
?>
Note that the add_fruits() function takes care of doing the Queries to the database, I did not include it here because it is irrelevant to my issue.
Just do echo in your PHP:
PHP
else {
//send error message to front end
echo "Error Adding Fruits";
}
JS
success: function(data) {
if (data == "1") {
//data added to db
}
else {
alert(data);
}
}

Categories