Ajax Add button in for each loop Laravel 5.4 - javascript

I'm trying to create an "Add button" in foreeach loop. And submit it using ajax. But i have problems finding out what exactly im doing wrong, my JS knowledge is very poor.
So this is my code.
View:
#foreach ($lots as $lot)
#if (count($lot->comments) >= 1)
<span class="glyphicon glyphicon-ok"></span>
#else
<form id="favorites-button" data-id="{{ $lot->lot_id }}">
{{ csrf_field() }}
<input type="hidden" name="body" value="0_o" class="form-control">
<button type="submit" class="btn btn-xs btn-primary">Favorites</button>
</form>
#endif
#endforeach
This is my JS
#section('js')
<!-- Ajax add to favorites -->
<script type="text/javascript">
$("document").ready(function(){
$("#favorites-button").submit(function(e){
e.preventDefault();
var button = $(this);
var url = '/lots/' + button.data('id') + '/comment';
var body = $("input[name=body]").val();
var dataString = 'body='+body;
$.ajax({
type: "POST",
url : url,
data : dataString,
dataType : "json",
success : function(data){
}
},"json");
});
});
</script>
#endsection
This is my route:
Route::post('/lots/{lot}/comment', 'CommentsController#add');
And my controller:
public function add(Lot $lot)
{
Comment::create([
'body' => request('body'),
'lot_id' => $lot->lot_id,
'user_id' => auth()->user()->id,
'bid' => $lot->bid,
'lot_date' => $lot->lot_date,
'auction_name' => $lot->auction_name,
'pics_urls' => $lot->pics_urls,
'company' => $lot->company,
'model_name_en' => $lot->model_name_en,
'model_type_en' => $lot->model_type_en,
'scores_en' => $lot->scores_en,
'model_year_en' => $lot->model_year_en,
'color_en' => $lot->color_en,
'displacement' => $lot->displacement,
'transmission_en' => $lot->transmission_en,
'start_price_en' => $lot->start_price_en,
'inspection_en' => $lot->inspection_en,
'grade_en' => $lot->grade_en,
'equipment_en' => $lot->equipment_en,
'mileage_num' => $lot->mileage_num,
'result_en' => $lot->result_en,
'auct_ref' => $lot->auct_ref,
]);
return "ok";
}
So i think the problem is also in ID that im using in foreach loop. That means all forms in loop have same ID's. So i need to reconsider my whole approach. Any one have ideas how can i do this?

<script type="text/javascript">
$("document").ready(function(){
$("#favorites-button").submit(function(e){
e.preventDefault();
var button = $(this);
var url = '/lots/' + button.data('id') + '/comment';
var body = $("input[name=body]").val();
$.ajax({
type: "POST",
url: url,
data: {
body: body,
_token: '{{ csrf_token() }}'
},
dataType: "json",
success: function(data){
console.log('success');
}
},"json");
});
});
</script>
I think it helps.

So i was doing everything wrong in the beginning!
I changed the whole approach. Thanks to my friends help.
Now first of all i change form in to a Button witch calls an event:
this is the view:
#foreach ($lots as $lot)
#if (count($lot->comments) >= 1)
<span class="glyphicon glyphicon-ok"></span>
#else
<button data-id="{{ $lot->lot_id }}" class="btn btn-xs btn-primary favouriteButton">Favourite</button>
#endif
#endforeach
Than i change JS:
<!-- Ajax add to favorites -->
<script type="text/javascript">
// call button via class
$('.favouriteButton').click(function (e) {
var button = $(this);
e.preventDefault();
// change the route
$.get('/lots/' + $(this).data('id') + '/favourite')
.done(function (response) {
// instead of button insert check icon
button.parent().append('<span class="glyphicon glyphicon-ok"></span>');
// remove button
button.remove();
})
.fail(function (respnse) {
});
});
</script>
Than i change my route:
Route::get('/lots/{lot}/favourite','CommentsController#favouriteButton');
And created new function:
public function favouriteButton(Lot $lot){
Comment::create([
'body' => 'Auto add', // this is the body for new comment
'lot_id' => $lot->lot_id,
'user_id' => auth()->user()->id,
'bid' => $lot->bid,
'lot_date' => $lot->lot_date,
'auction_name' => $lot->auction_name,
'pics_urls' => $lot->pics_urls,
'company' => $lot->company,
'model_name_en' => $lot->model_name_en,
'model_type_en' => $lot->model_type_en,
'scores_en' => $lot->scores_en,
'model_year_en' => $lot->model_year_en,
'color_en' => $lot->color_en,
'displacement' => $lot->displacement,
'transmission_en' => $lot->transmission_en,
'start_price_en' => $lot->start_price_en,
'inspection_en' => $lot->inspection_en,
'grade_en' => $lot->grade_en,
'equipment_en' => $lot->equipment_en,
'mileage_num' => $lot->mileage_num,
'result_en' => $lot->result_en,
'auct_ref' => $lot->auct_ref,
]);
return "ok";
}
I hope my experience will help some body.

Related

Laravel sending data by ajax

I am trying to send data from my form to back-end by ajax but it doesn't send all my data.
preview of sent data
array:6 [
"title" => "xxxxxxxxxxxx"
"slug" => "xxxxxx"
"description" => """xxxxxxxxxxxxxxxxx"""
"publish" => "1"
"user_id" => "1"
"thumbnail" => null
]
Issues
my description is in triple double qoute """ xxxx """ (not sure if it's ok)
Image (thumbnail) didn't send
Categories didn't send
code
form
{{ Form::model($post, array('route' => array('quickedit', $post->id), 'method' => 'POST', 'files' => true)) }}
<div class="modal-body text-left">
{{-- show success message --}}
<div class="msg"></div>
<input type="hidden" name="user_id" id="user_id" value="{{Auth::user()->id}}">
<div class="row">
<div class="col-md-12 mt-3">
{{ Form::label('title', 'Title') }}
{{ Form::text('title', null, array('class' => 'form-control')) }}
</div>
<div class="col-md-12 mt-3">
{{ Form::label('slug', 'Slug') }}
{{ Form::text('slug', null, array('class' => 'form-control')) }}
</div>
<div class="col-md-12 mt-3">
{{ Form::label('description', 'Description') }}
{{ Form::textarea('description', null, array('class' => 'form-control editor')) }}
</div>
<div class="col-md-6 mt-3">
<div class="row">
#if(!empty($post->thumbnail))
<div class="col-md-3">
<img class="img-thumbnail" src="{{url('/images')}}/{{$post->thumbnail}}" alt="{{$post->title}}">
</div>
<div class="col-md-9">
{{ Form::label('thumbnail', 'Thumbnail') }}
{{ Form::file('thumbnail', array('class' => 'form-control')) }}
</div>
#else
<div class="col-md-12">
{{ Form::label('thumbnail', 'Thumbnail') }}
{{ Form::file('thumbnail', array('class' => 'form-control')) }}
</div>
#endif
</div>
</div>
<div class="col-md-6 mt-3">
{{ Form::label('publish', 'Publish') }}
<select name="publish" id="publish" class="custom-select">
<option value="">Select</option>
<option value="1" {{ $post->publish == '1' ? 'selected' : '' }}>Publish</option>
<option value="0" {{ $post->publish == '0' ? 'selected' : '' }}>Draft</option>
</select>
</div>
<div class="col-md-6 mt-3">
{{ Form::label('categories', 'Categories') }}
<select name="categories[]" id="categories" class="custom-select selectbox" multiple>
#foreach($categories as $category)
<option value="{{$category->id}}">{{$category->title}}</option>
#if(count($category->children) > 0)
#foreach($category->children as $children)
<option class="pl-2" value="{{$children->id}}">{{$children->title}}</option>
#if(count($children->children) > 0)
#foreach($children->children as $child)
<option class="pl-4" value="{{$child->id}}">{{$child->title}}</option>
#if(count($child->children) > 0)
#foreach($child->children as $childf)
<option class="pl-5" value="{{$childf->id}}">{{$childf->title}}</option>
#endforeach
#endif
#endforeach
#endif
#endforeach
#endif
#endforeach
</select>
</div>
</div>
</div>
<div class="modal-footer">
<div class="msg"></div>
</div>
{{Form::close()}}
<button class="btn btn-primary updatepost" data-id="{{$post->id}}" type="submit">Update</button>
JavaScript
<script>
$(document).ready(function() {
$('.updatepost').click(function (event) {
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
});
event.preventDefault();
var title = $('input[name="title"]').val();
var slug = $('input[name="slug"]').val();
var description = $('.editor').val();
var publish = $('#publish option:selected').val();
var user_id = $('input[name="user_id"]').val();
var thumbnail = $('input[name="thumbnail"]').val();
var categories= $('#categories option:selected').val();
// $(this).attr("disabled", "disabled");
var prdfoId = $(this).data('id');
$.ajax({
url: '{{url("/admin/quickedit")}}/'+encodeURI(prdfoId),
type: "POST",
dataType: "json",
data: {
title: title,
slug:slug,
description: description,
publish: publish,
user_id: user_id,
thumbnail: thumbnail,
categories: categories
},
success:function(data) {
$('.msg').empty().append("Updated Successfully");
}
});
});
});
</script>
route
Route::post('quickedit/{id}','BlogController#quickedit')->name('quickedit');
controller
public function quickedit(Request $request, $id)
{
dd($request->all());
$this->validate($request, array(
'title' => 'required',
'slug' => 'required',
'description' => 'required',
'user_id' => 'required|numeric',
'thumbnail' => 'nullable|image',
'publish' => 'required|numeric',
));
$post = Post::find($id);
$post = Post::where('id',$id)->first();
$post->title = $request->input('title');
$post->slug = $request->input('slug');
$post->description = $request->input('description');
$post->user_id = $request->input('user_id');
$post->publish = $request->input('publish');
if ($request->hasFile('thumbnail')) {
$thumbnail = $request->file('thumbnail');
$filename = 'Post' . '-' . time() . '.' . $thumbnail->getClientOriginalExtension();
$location = public_path('images/' . $filename);
Image::make($thumbnail)->resize(850, 565)->save($location);
$post->thumbnail = $filename;
$oldFilename = $post->thumbnail;
$post->thumbnail = $filename;
Storage::delete($oldFilename);
}
$post->save();
$post->tags()->sync($request->tags);
$post->categories()->sync($request->categories);
}
Any idea?
Update
Based on answer and comments the last code I ended up is:
$(document).ready(function() {
$('.updatepost').click(function (event) {
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
});
event.preventDefault();
var title = $('input[name="title"]').val();
var slug = $('input[name="slug"]').val();
var description = $('.editor').val();
var publish = $('#publish option:selected').val();
var user_id = $('input[name="user_id"]').val();
var thumbnail = $('input[type=file]')[0].files[0];
var categories= [];
$("#categories option:selected").each(function(){
categories.push($(this).val());
});
categories = JSON.stringify(categories);
//new
var formData = new FormData();
formData.append('thumbnail', thumbnail);
formData.append('title', title);
formData.append('slug', slug);
formData.append('description', description);
formData.append('publish', publish);
formData.append('user_id', user_id);
formData.append('categories', categories);
//new
var prdfoId = $(this).data('id');
$.ajax({
url: '{{url("/admin/quickedit")}}/'+encodeURI(prdfoId),
type: "POST",
dataType: "json",
data: formData,
contentType: false,
processData: false,
success:function(data) {
$('.msg').empty().append("Updated Successfully");
}
});
});
});
The result of this code is:
array:7 [
"thumbnail" => "undefined"
"title" => "xxxxxxx"
"slug" => "xxxxxxxxx"
"description" => """
xxxxx
"""
"publish" => "1"
"user_id" => "1"
"categories" => "[]"
]
issues
image is undefined
categories are not passed
description is in triple double qoutes """ xxxxx """
any idea?
Your quickedit method calling dd(), what dump data, then just die. Also, quickedit returns void. In must to be an object or array if you going to use AJAX+JSON.
If you send image file you need has to base64 if you need handle in json, Or need use FormData like this:
var formData = new FormData();
formData.append('image', $('input[type=file]')[0].files[0]);
$.ajax({
url: 'Your url here',
data: formData,
type: 'POST',
contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
processData: false, // NEEDED, DON'T OMIT THIS
// ... Other options like success and etc
});
I think, a has a simplest way make two call firs send just json data, and then secound call is send the image.
var title = $('input[name="title"]').val();
var slug = $('input[name="slug"]').val();
var description = $('.editor').val();
var publish = $('#publish option:selected').val();
var user_id = $('input[name="user_id"]').val();
var thumbnail = $('input[name="thumbnail"]').prop('files');
var categories= $('#categories option:selected').val();
var formData = new FormData();
//Add a the file to fomr data
formData.append('image', thumbnail[0]);
//And need add data like this
formdData.append('title',title );

PHP not running with ajax POST

I have a form in a modal:
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
Add user
</button>
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form action="" method="post" id="saveperson">
<label for="newcat">Project Name</label>
<input type="text" name="newcat" value="">
<label for="description">Description</label>
<input type="text" name="description" value="">
<input type="submit" name="user" value="Submit">
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
On submit I run the js:
$(document).ready(function() {
$('#saveperson').submit(function(event) { //Trigger on form submit
var postForm = { //Fetch form data
'name' : $('input[name=newcat]').val(),
'desc' : $('input[name=description]').val() //Store name fields value
};
$.ajax({ //Process the form using $.ajax()
type : 'POST', //Method type
url : 'process.php',
data : postForm, //Forms name
dataType : 'json',
success : function(data) {
$('.modal-body').html("Done!");
}
else {
$('.modal-body').html("Error!");
}
}
});
event.preventDefault();
});
});
And then this should run in process.php
<?php
header ( "Content-Type: application/json");
$cat_ID = get_cat_ID( sanitize_title_for_query($_POST['newcat']) );
// Check if category exists
if($cat_ID == 0) {
$cat_name = sanitize_text_field($_POST['newcat']);
$cat_desc = sanitize_text_field($_POST['description']);
$cat_slug = sanitize_title_with_dashes($cat_name);
$my_cat = array(
'cat_name' => $cat_name,
'category_description' => $cat_desc,
'category_nicename' => $cat_slug,
'category_parent' => 0
);
if( wp_insert_category( $my_cat ) ) {
// Category added successfully
die ( json_encode ( array ( "success" => 1)));
} else {
// Error while creating new category
die ( json_encode ( array ( "success" => 0)));
}
} else {
// That category already exists
die ( json_encode ( array ( "success" => 0)));
}
?>
But after the submit, nothing happens and the data isn't saved in the db, meaning isn't working. If I use this php tho in a standard php without ajax, it works and saves the data in the db
<?php
header ( "Content-Type: application/json");
if( isset( $_POST['user'] ) ) {
if( !empty( $_REQUEST['newcat'] ) ) {
$cat_ID = get_cat_ID( sanitize_title_for_query($_POST['newcat']) );
// Check if category exists
if($cat_ID == 0) {
$cat_name = sanitize_text_field($_POST['newcat']);
$cat_desc = sanitize_text_field($_POST['description']);
$cat_slug = sanitize_title_with_dashes($cat_name);
$my_cat = array(
'cat_name' => $cat_name,
'category_description' => $cat_desc,
'category_nicename' => $cat_slug,
'category_parent' => 0
);
wp_insert_category( $my_cat );
}
}
}
?>
There is an error in the browser console:
$(document).ready(function() {
$('#saveperson').submit(function(event) { //Trigger on form submit
var postForm = { //Fetch form data
'name' : $('input[name=newcat]').val(),
'desc' : $('input[name=description]').val() //Store name fields value
};
$.ajax({ //Process the form using $.ajax()
type : 'POST', //Method type
url : 'process.php',
data : postForm, //Forms name
dataType : 'json',
success : function(data) {
$('.modal-body').html("Done!");
}
else {
$('.modal-body').html("Error!");
}
}
});
event.preventDefault();
});
});
Notice the
else {
$('.modal-body').html("Error!");
}
Error:
Uncaught SyntaxError: Unexpected token else
Remove the else block, it should work
It should be:
$(document).ready(function() {
$('#saveperson').submit(function(event) { //Trigger on form submit
var postForm = { //Fetch form data
'name' : $('input[name=newcat]').val(),
'desc' : $('input[name=description]').val() //Store name fields value
};
$.ajax({ //Process the form using $.ajax()
type : 'POST', //Method type
url : 'process.php',
data : postForm, //Forms name
dataType : 'json',
success : function(data) {
$('.modal-body').html("Done!");
}
});
event.preventDefault();
});
});
Here is the fiddle
Did u try this?
$( "#saveperson" ).submit(function( event ) {
let form = $( this );
let formData = new FormData(form[0]);
$.ajax({ //Process the form using $.ajax()
type : 'POST', //Method type
url : 'process.php',
data : formData,
success : function(data) {
$('.modal-body').html("Done!");
}
});
event.preventDefault();
});
The issue was I was running wordpress standard functions from an external php file and it doesn't work. In order to achieve what i was doing, I had to use
function.php and wordpress ajax
add_action( 'wp_footer', 'ajax_Person' );
function ajax_Person() { ?>
<script type="text/javascript">
jQuery("#createCat").on("click", function(e){
e.preventDefault();
person();
});
function person(){
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: { action: 'data_person', catName: jQuery('#newCat').val(), catDesc: jQuery('#descRiption').val() },
success: function(data) {
}
});
}
</script>
<?php }
add_action('wp_ajax_data_person' , 'data_person');
add_action('wp_ajax_nopriv_data_person','data_person');
function data_person(){
$catname = $_POST['catName'];
$catdesc = $_POST["catDesc"];
$cat_ID = get_cat_ID( sanitize_title_for_query($catname) );
// Check if category exists
if($cat_ID == 0) {
$cat_name = $catname;
$cat_desc = $catdesc;
$cat_slug = sanitize_title_with_dashes($cat_name);
$my_cat = array(
'cat_name' => $cat_name,
'category_description' => $cat_desc,
'category_nicename' => $cat_slug,
'category_parent' => 0
);
if( wp_insert_category( $my_cat ) ) {
echo 'Category added successfully';
} else {
echo 'Error while creating new category';
}
} else {
echo 'That category already exists';
}
}

Change like status with jQuery on a flask app

I am working on a flask web app and I am trying to implement the like comment feature with jQuery so that the page does not have to reload when the like button is clicked. Below are my codes. Any help will be much appreciated.
route:
#main.route('/like-comment/<int:id>', methods=["GEt", "POST"])
def like_comment(id):
comment = Comment.query.filter_by(id=id).first()
if comment is None:
flash('This comment is invalid or has been deleted by the user')
return redirect(url_for('.home'))
current_user.like_comment(comment)
return jsonify({'result' : 'success', 'like_comment' : current_user.like_comment(comment)})
JavaScript:
$(document).ready(function() {
$('.like').on('click', function () {
var comment_id = $(this).attr('comment_id');
req = $.ajax({
url : '/like-comment',
type : 'POST',
data : {
like_comment : current_user.like_comment(comment),
id : comment_id
}
});
req.done(function (data) {
$('#like'+comment.id).text(data.like_comment);
});
});
});
HTML:
{% if not current_user.is_liking_comment(comment) %}
<button class="like btn btn-pill btn-warning btn-xs" comment_id="{{ comment.id }}">
<span class="icon icon-thumbs-up" id="like{{ comment.id }}"></span> Like
</button>
{% else %}
I don't use flask, but I see you're using an attribute "comment_id", is that a Flask thing? Otherwise, you should use "data-"...
In your HTML...
<button class="like btn btn-pill btn-warning btn-xs" data-comment_id="{{ comment.id }}">
And then in jQuery...
var comment_id = $(this).data('comment_id');
But I think the problem is that your returning JSON and you haven't indicated that to your $.ajax call...
$(document).ready(function() {
$('.like').on('click', function(event) {
event.preventDefault();
var comment_id = $(this).attr('comment_id');
$.ajax({
url : '/like-comment',
type : 'POST',
data : {
like_comment : current_user.like_comment(comment),
id : comment_id
},
dataType='json'
})
.done(function (data) {
$('#like'+comment.id).text(data.like_comment);
});
});
});
Or if you don't want to use Promises...
$(document).ready(function() {
$('.like').on('click', function(event) {
event.preventDefault();
var comment_id = $(this).attr('comment_id');
$.ajax({
url : '/like-comment',
type : 'POST',
data : {
like_comment : current_user.like_comment(comment),
id : comment_id
},
dataType='json',
success: function(data) {
$('#like'+comment.id).text(data.like_comment);
}
});
});
});
Let me know if it helps...
Try adding an action to your data object to call the function on the server. See below:
data: {
action: like_comment, //or the name of your function on the server
like_comment: current_user.like_comment(comment),
id: comment_id,
},

Like/Dislike with jQuery AJAX returns 500 (Internal Server Error) but works when I reload the page

I have a Like Status button that sends data using AJAX to the controller.
When I click the button, the button changes from "like" to "dislike" and all the classes and form action get changed as well.
The problem is, if I like the status, I see the changes reflected, but if I decided to dislike it without reloading the page, I get this error
GET http://localhost/socialnet/public/likestatusCount/undefined 500 (Internal Server Error)
If I reload the page and click dislike, my vote gets removed from the database and the button changes back to "like"
It works if I reload the page.
If I remove the get() request to retrieves the likes count, nothing happens and console.log() returns an empty row, I don't see any data being returned.
I opened laravel.log and I saw this error
local.ERROR: exception 'ErrorException' with message 'Trying to get property of non-object' in C:\xampp\htdocs\socialnet\app\Http\Controllers\FeedController.php:140
which is this line in getlikesCounter() method
return Response::json(['count' => StatusLikes::where('status_id', $status->id)->count()]);
I am using Laravel 5.2
The form in the view
#if(\App\StatusLikes::where(['status_id' => $status->id, 'user_id' => Auth::user()->id])->first())
{!! Form::open(['action' => 'FeedController#dislikeStatus', 'id' => 'dislike_form', 'class' => 'dislikeform']) !!}
<button type="submit" class="btn btn-danger btn-xs dislike" data-user="{{ Auth::user()->id }}" data-status="{{ $status->id }}" id="dislike-status">
<i class="fa fa-thumbs-down"></i> <span class="dislike-button-text">Dislike</span> <span class="dislike-button-counter">({{ $likes_count }})</span>
</button>
{!! Form::close() !!}
#else
{!! Form::open(['action' => 'FeedController#likeStatus', 'id' => 'like_form', 'class' => 'likeform']) !!}
<button type="submit" class="btn btn-info btn-xs like" data-user="{{ Auth::user()->id }}" data-status="{{ $status->id }}" id="like-status">
<i class="fa fa-thumbs-up"></i> <span class="like-button-text">Like</span> <span class="like-button-counter">({{ $likes_count }})</span>
</button>
{!! Form::close() !!}
#endif
The methods in the controller for like, dislike, and get likes count
public function likeStatus() {
if (Input::has('like_status')) {
$status = Input::get('like_status');
$selectedStatus = Status::find($status);
$selectedStatus->likes()->create([
'user_id' => Auth::user()->id,
'status_id' => $status
]);
$response = [
'status' => 'success',
'msg' => 'You have liked this status',
];
return Response::json($response);
//return redirect(route('feed'));
}
}
public function dislikeStatus() {
if (Input::has('dislike_status')) {
$status = Input::get('dislike_status');
$selectedStatus = Status::find($status);
$selectedStatus->likes()->where('user_id', Auth::user()->id)->delete([
'status_id' => $status
]);
$response = array(
'status' => 'success',
'msg' => 'You have disliked this status',
);
return Response::json($response);
//return redirect(route('feed'));
}
}
public function getlikesCounter($id) {
$status = Status::find($id);
return Response::json(['count' => StatusLikes::where('status_id', $status->id)->count()]);
}
The javascript form likeform and dislikeform
$('.likeform').submit(function(e) {
e.preventDefault();
var submitBtn = $(this).find('.like');
var form = $(this).find('.likeform')
var likeText = $(this).find('span.like-button-text');
var likeCounter = $(this).find('span.like-button-counter');
var status_id = submitBtn.data('status');
var user_id = submitBtn.data('user');
var token = $('input[name=_token]').val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': token
}
});
$.ajax({
url: 'http://localhost/socialnet/public/likeStatus',
method: 'POST',
cache: false,
data: { like_status: status_id, user_id: user_id, _token: token },
success: function(data) {
submitBtn.removeClass('btn-info').addClass('btn-danger');
submitBtn.find($(".fa")).removeClass('fa-thumbs-up').addClass('fa-thumbs-down');
submitBtn.closest("form").removeClass('likeform').addClass('dislikeform').attr('id', 'dislike_form').attr('action', 'http://localhost/socialnet/public/dislikeStatus');
submitBtn.closest("form").find("input[name=like_status]").attr('name', 'dislike_status');
submitBtn.removeClass('like').addClass('dislike');
submitBtn.find($(".like-button-text")).removeClass('like-button-text').addClass('dislike-button-text');
submitBtn.find($(".like-button-counter")).removeClass('like-button-counter').addClass('dislike-button-counter');
likeText.text('Dislike');
$.get("http://localhost/socialnet/public/likestatusCount/" + status_id, function(data) {
likeCounter.text('(' + data.count + ')');
});
console.log(data);
},
error: function() {
console.log('error');
}
});
});
$('.dislikeform').submit(function(e) {
e.preventDefault();
var submitBtn = $(this).find('.dislike');
var form = $(this).find('.dislikeform')
var likeText = $(this).find('span.dislike-button-text');
var likeCounter = $(this).find('span.dislike-button-counter');
var status_id = submitBtn.data('status');
var user_id = submitBtn.data('user');
var token = $('input[name=_token]').val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': token
}
});
$.ajax({
url: 'http://localhost/socialnet/public/dislikeStatus',
method: 'POST',
cache: false,
data: { dislike_status: status_id, user_id: user_id, _token: token },
success: function(data) {
submitBtn.removeClass('btn-danger').addClass('btn-info');
submitBtn.find($(".fa")).removeClass('fa-thumbs-down').addClass('fa-thumbs-up');
submitBtn.closest("form").removeClass('dislikeform').addClass('likeform').attr('id', 'like_form').attr('action', 'http://localhost/socialnet/public/likeStatus');
submitBtn.closest("form").find("input[name=dislike_status]").attr('name', 'like_status');
submitBtn.removeClass('dislike').addClass('like');
submitBtn.find($(".dislike-button-text")).removeClass('dislike-button-text').addClass('like-button-text');
submitBtn.find($(".dislike-button-counter")).removeClass('dislike-button-counter').addClass('like-button-counter');
likeText.text('Like');
$.get("http://localhost/socialnet/public/likestatusCount/" + status_id, function(data) {
likeCounter.text('(' + data.count + ')');
});
console.log(data);
},
error: function() {
console.log('error');
}
});
});
GET http://localhost/socialnet/public/likestatusCount/undefined 500 (Internal Server Error)
Means :
status_id is undefined
Because, you have :
$.get("http://localhost/socialnet/public/likestatusCount/" + status_id//..
Indeed , you have status_id got from :
var status_id = submitBtn.data('status');
And you have submitBtn is got from :
var submitBtn = $(this).find('.dislike');
However, you change the CSS class of submitBtn when there is an action (like/dislike)
Thus ,
.dislike is bad selector here, you need a selector that match the button either it is like or dislike
Assign value to submitBtn & update status_id just before calling your ajax.
$.get("http://localhost/socialnet/public/likestatusCount/" + status_id//..

Returning form view in Symfony2 using Ajax/Jquery

Currently posting data from a drop-down menu. I am trying to basically the form that is returning and then insert it into the page.
Select Drop-Down
<form method="POST" style="display: inline;">
<select name="event_added" class="selectpicker">
{% for subscription in form.peerEventSubscriptions %}
<option value='{{typeDefEvent[loop.index0]}}'>{{ form_label(subscription.eventTypeHumanized) }}</option>
{% endfor %}
</select>
<input type="submit" class="btn btn-default" id = "addEventButton" data-rel="tooltip" title="AddEvent" value="Add Event" style="line-height: 1.5" />
</form>
Ajax/Jquery
var addEvent = $("#addEventButton");
addEvent.click(function(){
$.ajax({
method: "POST",
url: "{{ path('_add_new_sub_event') }}",
contentType: 'application/json; charset=utf-8',
data: { postVars: "EVENT_CLASS_JITTER EVENT_JITTER" }
})
.done(function( msg ) {
console.log( "Data Saved: " + msg );
window.stop();
});
});
Controller
return this data, the form is valid.
return array(
'form' => $form->createView(),
);
Getting a 500 internal server error. I just want to basically take this form and then render it to the current page, no refreshes.
I invite you to use FOSJsRoutingBundle,
Look at my example of my jQuery Ajax call:
$('#addNewVariant').on('click', function(event){
var hidden_input = $('#hidden_input').val();
hidden_input++;
$.ajax({
type: "get",
dataType: 'json',
url: Routing.generate('admin_products_addNewVariant', {'number' : hidden_input }),
beforeSend: function(){
$('.loadingGif').show();
$('#loadingModal').modal('show');
},
success: function( returnedData ) {
$('#hidden_input').attr( 'value', hidden_input );
$('#ajaxVariantAdded').append('<li class="dd-item" data-id="'+returnedData.id+'"><div class="dd-handle"><a data-id="'+returnedData.id+'"><i class="fa fa-hand-o-right"></i> {{"tab.variant"|trans}} '+returnedData.name+'</a><a data-id="'+returnedData.id+'" data-toggle="modal" class="pull-right" href="#modal'+returnedData.id+'"><i class="glyphicon glyphicon-minus-sign"></i></a></div></li>');
$( '.ajax' ).append( returnedData.form );
$('.variant').hide();
$('.variantItem'+returnedData.id).show();
$('.loadingGif').hide();
$('#loadingModal').modal('hide');
},
error: function( returnedData){
$('.loadingGif').hide();
$('#loadingModal').modal('hide');
}
});
});
This is my route:
admin_products_addNewVariant:
pattern: /addVariation/{number}
defaults: { _controller: "ProductsBundle:BackEnd/Products:addNewVariant" }
options:
expose: true
Finally this is my function:
public function addNewVariantAction($number){
$entity = new Variant();
$form = $this->createForm(new VariantType($number), $entity)->createView();
$response = new JsonResponse(array(
'form' => $this->renderView('ProductsBundle:Administration:Products/NewFormVariant/new.html.twig',array(
'form' => $form,
'number' => $number,
)
),
'name' => $number+1,
'id' => $number,
));
return $response;
}
I hope that my answer give a help.

Categories