laravel 4 upvote via ajax post - ajax

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');

Related

Why my controller not getting data from ajax

I'm new to this, I'm trying to get the data from an ajax query
This Is My Ajax
$('#insertfile').on('click',function() {
console.log('a');
var file = document.getElementById('files').files[0];
var name = document.getElementById('names').value;
if( $('#room-status-no').prop('checked') ) {
console.log("status: 1");
var status = 1;
} else {
var status = 0;
console.log("status: 0");
}
var id = document.getElementById('id').value;
let form = new FormData();
console.log(file);
form.append('file', file);
form.append('name', name);
form.append('status', status);
form.append('id', id);
form.append('_method', 'PATCH');
form.append('action', 'update_file');
console.log(id, name, status);
$.ajax({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
url: "{{ route('this is my route.update', 'update_file') }}",
type: "PATCH",
cache: false,
processData: false,
contentType : false,
dataType: 'json',
data: form,
beforeSend: function() {
$('body').append('<div id="spinnerLoading"><div class="sk-spinner sk-spinner-double-bounce"><div class="sk-double-bounce1"></div><div class="sk-double-bounce2"></div></div></div>');
},
This is my Controller
public function update(Request $request) {
$action = $request->action;
dd($request->all());
if($action == 'update_text'){
return $this->updatetextControl($request);
} else if($action == 'update_file') {
return $this->updateFileControl($request);
}
I'm trying to pass the form data to my laravel controller using dd($request->all());
I was unable to get any data in my controller, I'm not sure if my URL route is the problem or I cant have multiple update functions others thing in one controller, does anyone know a solution? it will be much appreciated, thanks

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');
}

ajax is not sending data to controller

ajax is not sending data to controller
var url = "<?php echo base_url(); ?>";
function allowip() {
var url = "<?php echo base_url(); ?>"
var id = $('#path').attr('value');
$.ajax({
type: "POST",
url: url+"client/home/get_ip",
//dataType: 'text',
data: {'id': id},
//cache: false,
success: function(abc) {
alert(abc);
},
error:function(data) {
alert('no working');
}
});
}
alert is showing with data but not sending data to controller
controller is empty
public function get_ip($id)
{
$day = $this->input->post('id');
echo $day;
}
As your get_ip function have argument $id so it must need to pass on it, url keyword might be conflicting so use different variable name and get the value from #path with val() function.
It might help:
function allowip() {
var id = $('#path').val();
var request_url = "<?php echo base_url(); ?>"+"client/home/get_ip/"+id;
$.ajax({
type: "POST",
url: request_url,
data: {'id': id},
success: function(abc) {
alert(abc);
},
error:function(data) {
alert('no working');
}
});
}
public function get_ip($id)
{
echo $id;
}
or you can do is to post $id in data as you're already doing it but only have to change some lines:
function allowip() {
var id = $('#path').val();
var request_url = "<?php echo base_url(); ?>"+"client/home/get_ip/";
$.ajax({
type: "POST",
url: request_url,
data: {'id': id},
success: function(abc) {
alert(abc);
},
error:function(data) {
alert('no working');
}
});
}
public function get_ip()
{
$day = $this->input->post('id');
echo $day;
}
You are sending a parameter to a function so you can change your code like this
function allowip() {
var id = $('#path').attr('value');
var url = "<?php echo base_url(); ?>"+"client/home/get_ip/"+id
$.ajax({
type: "GET",
url: url,
dataType: "html",
success: function(abc) {
alert(abc);
},
error:function(data) {
alert('no working');
}
});
}
and your action will be
public function get_ip($id)
{
echo $id;
}
I think it is probably the way you are getting the value. It's hard to tell without seeing the view code, but I will assume that $('#path') is an <input...> element of some sort. If that is correct then try getting the value like this
var id = $('#path').val();
Forget about using an argument with the get_ip() function. You are posting to the controller not creating a URL with argument values. Try this.
public function get_ip()
{
$day = $this->input->post('id');
echo !empty($day) ? $day : "No Input"; //or, an empty string instead?
}

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 render view AJAX html is empty

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.

Resources