Laravel 4 render view AJAX html is empty - ajax

public function index($id)
{
$project = Project::findOrFail($id);
if(Request::ajax())
{
$html = View::make('Milestones.indexpartial', $project)->render();
return Response::json(array('html' => $html));
}
return View::make('milestones.index')->with('project', $project)
->with('title','Milestones');
}
$(".ajaxul a").click(function()
{
var url = $(this).attr('href');
$.ajax(
{
url: url,
type: "get",
datatype: "html",
beforeSend: function()
{
$('#ajaxloading').show();
}
})
.done(function(data)
{
$('#ajaxloading').hide();
$(".refresh").empty().html(data.html);
})
.fail(function(jqXHR, ajaxOptions, thrownError)
{
alert('No response from server');
});
return false;
});
Please help me make this work.
I'm new to AJAX and laravel.
my problem was this line here:
$html = View::make('Milestones.indexpartial', $project)->render();
it gives an error. then i changed it to
$html = View::make('Milestones.indexpartial',array('project' => $project))->render();
the request is a success but the html is empty.
Please help me. Thank you.

Related

Ajax laravel dropdown not returning the id of selected value

I am passing the hotel id as a parameter to my function to get all the rooms in that hotel. But it is returning an error. I want to return in a JSON format the id of the hotel.
this is my javascript function
function showRooms($hotel_plan_id) {
var id = $hotel_plan_id;
if (id !== "") {
var token = $('meta[name="_token"]').attr('content');
$.ajax({
url: '/rooms'+id,
type: "Get",
dataType: 'JSON',
data: "{id:" + JSON.stringify(id) + ", _token:" + token + "}",
success:function(data)
{
alert('xdata:' + data);
//$('#'+dependent).html(result);
},
error: function (result) {
alert("Error occur in the rooms()");
}
});
this is my controller
public function rooms(id $id){
$response = array();
$response =$id;
return response()->json($response);
}
this is my route
Route::get('/rooms', 'HomeController#rooms')->name('/rooms');
your URL url: '/rooms'+id, and Route::get('/rooms', 'HomeController#rooms')->name('/rooms'); not valid, please see my code i am edited your code
//Change your js function
function showRooms(hotel_plan_id) {
var id = hotel_plan_id;
if (id !== "") {
$.ajax({
type: "GET",
dataType: 'JSON',
url:'{{ route('rooms', '') }}/'+id,
data:{_token:'{{ csrf_token() }}'},
success:function(data){
alert('xdata:' + data);
//$('#'+dependent).html(result);
},
error: function (result) {
alert("Error occur in the rooms()");
}
});
}
}
//Change your function
public function rooms($id){
return response()->json(['id'=>$id]);
}
//Change your route
Route::get('rooms/{id}', 'HomeController#rooms')->name('rooms');
***Use Route like this in routes.php file:**
Route::get('/rooms', 'HomeController#rooms');
public function rooms(Request $request){
$id = $request->get('id');
$response['id'] = $id;
**Or whatever you want to do and append in response varaible and return**
return response($response)->header('Content-Type', 'application/json');
}

Cannot go to url using ajax in Laravel

I'm using ajax to implement infinite scroll pagination in laravel but I cannot access the url while I can with the enter the url in the adress bar or via the default pagination page list.
I get GET http://localhost:8888/gest/items?page=2 500 (Internal Server Error)
Scripts
<script type="text/javascript">
var page = 1;
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() >= $(document).height()) {
page++;
loadMoreData(page);
}
});
function loadMoreData(page){
$.ajax(
{
url: '?page=' + page,
type: "get",
beforeSend: function()
{
$('.ajax-load').show();
}
})
.done(function(data)
{
if(data.html == " "){
$('.ajax-load').html("No more records found");
return;
}
$('.ajax-load').hide();
$(".row-items").append(data.html);
})
.fail(function(jqXHR, ajaxOptions, thrownError)
{
alert('server not responding...');
});
}
</script>
And the controller
public function index(Request $request, $submenu = null){
$items = Item::paginate(5);
if ($request->ajax()) {
$view = view('data',compact('items'))->render();
return response()->json(['html'=>$view]);
}
return view('layouts.gest', compact('items'), ['submenu' => $submenu]);
}
EDIT
I also tested to add
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
The error was that laravel couldn't find the view data

error in image while uploading through ajax

I am trying to upload image through ajax. at theclient side i am using this code.
$(document).on('change','.image_upload',function(){
readURL(this);
});
///
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
save_profile_image(e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
else {
swal("Sorry - you're browser doesn't support the FileReader API");
}
}
function save_profile_image(image_data){
var image_code = encodeURIComponent(image_data);
$.ajax({
type: "POST",
url: '<?=base_url()."Dashboard/new_valet_picture";?>',
data:'valet_image='+image_code,
success: function(data){
alert('data');
}
});
}
while at the client side i am using codeigniter to save this as image. Image file is created but it won't display because it contains errors.Here is my CI function where this ajax request is being sent.
public function new_valet_picture(){
$user = $this->session->user_id;
$image_data = $this->input->post('valet_image');
$name= "valet_".$user.time().".png";
$profile_image = str_replace('data:image/png;base64,', '', $image_data);
$profile_image = str_replace(' ', '+',$profile_image);
$unencodedData=base64_decode($profile_image);
$pth = './uploads/valet_images/'.$name;
file_put_contents($pth, $unencodedData);
echo $name;
}
can anybody figure out where i am wrong.
you just wrong to pass parameter in ajax request :
this is your code
$.ajax({
type: "POST",
url: '<?=base_url()."Dashboard/new_valet_picture";?>',
data:'valet_image='+image_code,
success: function(data){
alert('data');
}
});
data:'valet_image='+image_code, is wrong pass and change that to data : {vallet_image : image_code}.
just changing the position of encodeURIComponent() helped me
///
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
save_profile_image(encodeURIComponent(e.target.result));
}
reader.readAsDataURL(input.files[0]);
}
else {
swal("Sorry - you're browser doesn't support the FileReader API");
}
}
function save_profile_image(image_data){
var image_code = image_data;
$.ajax({
type: "POST",
url: '<?=base_url()."Dashboard/new_valet_picture";?>',
data:'valet_image='+image_code,
success: function(data){
alert('data');
}
});
}

laravel 4 upvote via ajax post

I can't seem to get my voting system to work in ajax. I'm trying to establish the 'upvote' and have my onclick function call my route and insert a vote accordingly, except nothing happens. I can't see why or where I'm going wrong.
JAVASCRIPT
$( document ).ready(function() {
$(".vote").click(function() {
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
if (name=='up')
{
alert(dataString);
$(this).fadeIn(200).html('<img src="/img/vote-up-on.png" />');
$.ajax({
type: "POST",
url: "http://domain.com/knowledgebase/upvote",
dataType: "json",
data: {id : id},
data: dataString,
cache: false,
success: function(html)
{
parent.html(html);
}
});
}
if (name=='down')
{
alert(dataString);
$(this).fadeIn(200).html('<img src="/img/vote-down-on.png" />');
$.ajax({
type: "POST",
url: "downvote",
data: dataString,
cache: false,
success: function(html)
{
parent.html(html);
}
});
}
return false;
});
});
</script>
ROUTE.PHP
Route::get('knowledgebase/upvote/{id}', 'PostController#upvote');
POSTCONTROLLER.PHP
public function upvote($id)
{
if (Auth::user()) {
if (Request::ajax()) {
$vote = "1";
$user = Auth::user()->id;
$post = Post::find($id);
$checkvotes = Vote::where('post_id', $post->id)
->where('user_id', $user)
->first();
if (empty($checkvotes))
{
$entry = new Vote;
$entry->user_id = $user;
$entry->post_id = $post->id;
$entry->vote ="1";
$entry->save();
}
}
}
else
{
return "Not an AJAX request.";
}
}
You are using post in your jquery, but you are waiting for a GET route.
Use...
Route::post('knowledgebase/upvote/{id}', 'PostController#upvote');
Additionally, the way you are handling your route may not work correctly with the id. It would be expecting the id in the URL so what you can do is append your id to the url when setting up the ajax.
url: "http://domain.com/knowledgebase/upvote/"+id,
Or not use it at all, take the {id} portion out of your route, and grab it using Input::get('id');

how to get the value from codeigniter to ajax?

i have an ajax which I don't know if it is correct. I want to get the value from the controller and pass it to ajax.
ajax:
$.ajax({
type: "GET",
url: swoosh(id, path+'swoosh_employee/swoosh_delete_child', 'childdv'),
success: function(response) {
if (response != "Error")
{
$('#success-delete').modal('show');
}
else
{
alert("Error");
}
}
});
event.preventDefault();
and in the controller:
public function swoosh_delete_child()
{
$P1 = $this->session->userdata('id');
parse_str($_SERVER['QUERY_STRING'],$_GET);
$id = $_GET['h'];
$response = $this->emp->delete_children($id);
}
model
public function delete_chilren($id){
.......//codes here.. etc. etc.
if success //
return "success";
else
return "Error";
}
i just want to pass/get the value of $reponse and pass it to the ajax and check if the value is error or not..
Just echo in the controller:
$response = $this->emp->delete_children($id);
And alert the response:
alert(response); //output: success / Error
in your controller:
you should have something like this
public function swoosh_delete_child(){
$P1 = $this->session->userdata('id');
parse_str($_SERVER['QUERY_STRING'],$_GET);
$id = $_GET['h'];
$response['status'] = $this->emp->delete_children($id);
echo json_encode($response);
}
then in your ajax, to access the response
$.ajax({
type: 'POST',
url: url: swoosh(id, path+'swoosh_employee/swoosh_delete_child', 'childdv'),,
dataType: 'json',
success: function(response){
if (response.status)
{
$('#success-delete').modal('show');
}
else
{
alert("Error");
}
}
});

Resources