use session made from ajax inside blade laravel 4.2 - php

hi so im making a session via ajax when a certain button is clicked here is the code
function cModal(id)
{
alert(id);
$.ajax({
method: 'post',
url: 'http://localhost/dummy/app/putSession.php',
data: {
'dID': id
},
success: function()
{
alert(id);
}
});
}
it is successfull because it alerts the id inside the success:function()
in my putSession.php file here is how i did it
<?php
session_start();
$tId = $_POST['dID'];
$_SESSION["sID"] = $tId;
exit();
?>
but the thing is i can't access it inside my blade file im calling it like this
<div class="modal-content">
<div class="row rowMarg">
<?php session_start(); ?>
#if(Session::has('sID'))
{{ Session::forget('sID') }}
<h6>Information.</h6>
#else
<h6>File details not found.</h6>
#endif
</div>
</div>
it just goes to the file details not found
any idea what im doing wrong? thanks in advance!

use laravel session like
$request->session()->put('user', 'value');
$request->session()->get('user', 'value');
$request->session()->push('user.teams', 'developers');
for more https://laravel.com/docs/4.2/session

Related

Refresh table after request Ajax is success

I am beginner with Ajax. I try refresh a table when user select an option in form-select filter. I use Symfony and Twig.
I get the new datas in the Json format in my console when i select a new filter, but the table does'nt show with the new datas. I failed to find the solution when my request ajax is success.
My Select filter :
{{ form_start(form) }}
<div class="container-fluid">
<div class="row">
<div class="col-fluid">
{{ form_row(form.isAttending) }}
</div>
<button type="submit" class="btn btn-outline-success mb-2">{{ button_label|default('Envoyer') }}</button>
</div>
</div>
<div class="container-fluid">
<div class="row">
<div class="col-1-fluid">
{{ form_row(form.active) }}
</div>
</div>
</div>
{{ form_end(form) }}
In my Controller :
/**
* #Route("/ajax", methods={"GET", "POST"})
*/
public function testAjax(Request $request)
{
if (!$request->isXmlHttpRequest()) {
return new JsonResponse(array(
'status' => 'Error',
'message' => 'Error'),
400);
}
if($request->request->has('isAttending')) {
$preSelect = $request->request->get('isAttending');
return new JsonResponse(
$this->queryFollowingFilter($preSelect),
200);
}
}
In my Template :
<script>
$(document).on('change', '#campagnes_tel_isAttending', function () {
$('#flash').remove();
let $field = $(this)
let $preselect = $('#campagnes_tel_isAttending')
let $form = $field.closest('form')
let data = {}
data['isAttending'] = $field.val()
console.log(data)
$.ajax({
type: "POST",
url: "/campagnestel/ajax",
data: data,
dataType: "json",
success: function(response) {
console.log(response);
}
});
});
</script>
Any ideas ?
According to your question and comments your problem is not Symfony, not Ajax and also not Twig related. You get the correct data and you just do not know how to manipulate the DOM. DOM manipulation is a basic capability of JavaScript.
Here you can learn how to manipulate the DOM: https://www.w3schools.com/js/js_htmldom.asp
And here you can learn how to easily can manipulate it with jQuery which you are obviously using: https://www.w3schools.com/js/js_jquery_dom.asp
Sample:
$('#my-table').append(response.myWhatever);

How to pass a variable in JavaScript if in view it's empty?

So, I created a report system, but in the last step, I have a little problem...In JavaScript I'm using a variable from database for Ajax, but when a post has no comments, I'm getting Undefined variable: key.
Here is my script
if (isset($key)){
$('#yourFormIdComment{{$key+1}}').submit(function(e){
e.preventDefault();
var data = $(this).serialize();
$.ajax({
method:'POST',
url:'/career_report_comment',
data:data,
success: function (result) {
// do something with result
}
});
});
}
Here is my view with variable
#foreach($opinionComment as $key => $comments)
<div class="news-v3 bg-color-white">
<h4 style="font-size: 13px">
{{ $comments->user->username }}</h4>
<p>{{ $comments->comments }}</p>
<ul class="post-shares post-shares-lg">
<li #if ($key === 0) class="active" #endif style="float: right;left: 20px;bottom: 30px"><a data-toggle="modal" data-target="#exampleModalComment{{$key+1}}" href="javascript:void(0)" ><i class="rounded-x icon-flag"></i></a></li>
</ul>
</div>
#endforeach
My question is...how can I pass the variable {{$key+1}}from script even if a post has no reviews/comments?Because this is happening only when I have comments on a post.
Andrew i after talking in the comments and checking your code i might have found a solution to your problem.
You get a error:
Undefined variable: key
You get that error because the key isnt defined.
if (isset($key)){
$('#yourFormIdComment{{$key+1}}').submit(function(e){
e.preventDefault();
var data = $(this).serialize();
$.ajax({
method:'POST',
url:'/career_report_comment',
data:data,
success: function (result) {
// do something with result
}
});
});
}
In the first part of your code you use the variable $key, but the key is defined within the foreach in the second part of your code. That's why you get the error.

Ajax and codeigniter framework issues

I have a problem with AJAX and CodeIgniter, I want to get total count of users in database but there is no data found.
my controller:
public function TotalUsers()
{
if($this->input->post("action")=='GetTotalUsers')
{
$this->load->model("usersmodel");
$totalcount=$this->usermodel->GetTotalUserCount();
echo $totalcount;
}
}
my model:
public function GetTotalUserCount()
{
$query = $this->db->get("users");
return $query->num_rows();
}
My html and jquery:
<div class="col-lg-3 col-xs-6">
<!-- small box -->
<div class="small-box bg-yellow">
<div class="inner">
<h3 id="totaluser"></h3>
<p>Total Users</p>
</div>
<div class="icon">
<i class="ion ion-person-add"></i>
</div>
More info <i class="fa fa-arrow-circle-right"></i>
</div>
</div>
<script>
$(document).ready(function () {
GetTotalUsersCount();
function GetTotalUsersCount() {
var action='GetTotalUsers';
$.ajax({
url:"<?php echo base_url()?>Users/TotalUsers",
method:"post",
data:{action:action},
success:function (data) {
$("#totaluser").html(data)
}
})
}
})
</script>
I think you might be sending it encoded in JSON while the controller is expecting it serialized, although I'm not sure.
Run var_dump() on $this->input->post("action").
If that doesn't give GetTotalUsers, then that's you're problem. You'll need to either set the controller to accept raw post data and decode as json, serialize the data instead of using a javascript object (JSON), or if possible, just remove the action conditional because currently it doesn't look useful as shown.
I suspect that url: is not evaluating to the correct value. There are a couple syntax errors (missing semi-colons) too. Try this JavaScript. Use your browser's "Developer Tools" to examine the headers to see where the post "goes" and that "action" is being posted.
$(document).ready(function () {
GetTotalUsersCount();
function GetTotalUsersCount() {
$.ajax({
url: '<?php echo base_url("Users/TotalUsers"); ?>',
method: "post",
data: {action: 'GetTotalUsers'},
success: function (data) {
$("#totaluser").text(data);
}
});
}
});
I'm curious why you use ajax and don't simply determine and pass the total count to the initial loading of the view?
1.Use Ctrl+Shift+I (or navigate to Current Page Control > Developer >
Developer Tools )or( use right click on your page and then select inspect
element)
2.Go to "Network" tab
3.Find your ajax request in "Name Path" column
4.Click on the specific ajax link

$http.post not working inside ng-click function in Angular Js

I'm developing a project with Anjular js and Codeigniter 3. I have faced some issues with routing in angular js. I have a view page with a list of details of users and inside that list there is a tag with ng-click="myName()". I have declared this function inside my js file and this function works fine.
<div class="container" ng-controller="ListController">
<div class="row">
<div class="col-lg-12 text-center">
<h1>Starter Template</h1>
<p class="lead">Complete with pre-defined file paths that you won't have to change</p>
<div class="row">
<div class="col-sm-6 col-md-4 wow zoomIn" data-wow-delay="0.5s" ng-repeat="items in artists">
<div class="thumbnail">
<img ng-src="{{settings.base_url}}/application/assets/images/profile/{{items.shortname}}.jpg" alt="...">
<div class="caption">
<h3>{{items.name}}</h3>
<p>{{items.bio}}</p>
<p>Button Button</p>
</div>
</div>
</div>
</div>
</div>
</div>
Inside this function "myName()" I have written $http.post for getting a function inside the controller(Codeiginter controller). I'm using auth.php as controller and functionOne() is the function to retrive.
var base_url_abs = window.location.origin;
var base_url = base_url_abs+'/AngularExPack/Angular_Bootstrap_CI_1/';
var base_url_controller = base_url_abs+'/AngularExPack/Angular_Bootstrap_CI_1/index.php/';
myApp.controller('ListController', ['$scope', '$http', 'settings', function($scope, $http) {
$http.get('application/datas/data.json').success(function (data){
$scope.artists = data;
});
$scope.myName = function() {
alert("hai1");
/*
$http.post(base_url_controller+'auth/functionOne/').success(function (response){
$scope.data = response
console.log(response);
//alert($scope.data);
});*/
/**/ $http({
method : 'POST',
url : base_url_controller+'auth/functionOne/',
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data) {
$scope.data = response
console.log($scope.data);
alert($scope.data);
});
}
}]);
When i run this, an error is occured and showing like this inside the console
But i'm getting the correct result when i click on this link and also if i give base_url path inside the href inside a tag.
Button Button
But what i need is inside this myName function i have to access the controller function functionOne() using $http using angular js. Is that possible.?
If anyone knows please help me to find out the solution in ng-click. Correct me if i written wrong code.
Thank you.
you should use
$http({
method : 'GET',
url : base_url_controller+'auth/functionOne/',
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data) {
$scope.data = data
console.log($scope.data);
alert($scope.data);
});

Laravel Ajax request returning whole page rather than just data

I'm trying to use ajax to find the next page on my pagination. However it keeps bringing in the whole body. I've taken a print screen to show the problem.
I'm not an expert on ajax show would appreciate some help as to how I can rectify this issue?
My code is below:
public function viewall()
{
$data["projects"] = $projects = Auth::user()->projects()->paginate(3);
if(Request::ajax())
{
$html = View::make('projects.viewall', $data)->render();
return Response::json(array('html' => $html));
}
return View::make('projects.viewall')->with('projects', $projects);
}
Js/js.js
$(".pagination a").click(function()
{
var myurl = $(this).attr('href');
$.ajax(
{
url: myurl,
type: "get",
datatype: "html",
beforeSend: function()
{
$('#ajax-loading').show();
}
})
.done(function(data)
{
$('#ajax-loading').hide();
$("#projects").empty().html(data.html);
})
.fail(function(jqXHR, ajaxOptions, thrownError)
{
alert('No response from server');
});
return false;
});
viewall.blade.php
#extends("layout")
#section("content")
<div class="container">
<h4>Your Projects</h4>
<div id="ajax-loading" class="alert alert-warning" style="display: none;">
<strong>Loading...</strong>
</div>
#if (Auth::check())
#if (count($projects) > 0)
#foreach ($projects as $project)
<div class="one-third column" id="projects">
{{ $project->project_name }}
{{ $project->project_brief }}
{{ date("d-m-Y", strtotime($project->start_day)) }}
</div>
#endforeach
#else
<h5 class="errorslist">You have no projects click <a class="errorslist" href="/project/create">here to create a project</a></h5>
#endif
#endif
<div class="sixteen columns">
{{ $projects->links() }}
</div>
</div>
#stop
This line:
$("#projects").empty().html(data.html);
will fill the #project up with your returned html which you created here:
$html = View::make('projects.viewall', $data)->render();
So,you just need to change projects.viewall with only 'partial view' that you want to load.
Probably you don't need to extends your main layout.
But you render a view here:
$html = View::make('projects.viewall', $data)->render();
so html is created by Laravel and then you insert it as html into the #projects domElement.
I experienced this kind of problem, just run
dd( json_decode( json_encode( Products::paginate(5) ), true) );
and can get a hint :)
I have read a solution about this here:
http://www.tagipuru.xyz/2016/05/17/displaying-data-using-laravel-pagination-in-the-html-table-without-page-reload/

Categories