Output from controller to HTML form - javascript

Can someone please tell me how to output data from my controller to an HTML form. I want to change the label of an anchor from "Like" to "Liked" if the user has already clicked the link previously.
Here is the HTML.
<section class="row posts">
<div class="col-md-6 col-md-3-offset">
<header><h3>other posts</h3></header>
#foreach($posts as $post)
<article class="post">
<p>{{ $post->content }}</p>
<div class="info">Posted by {{ $post->user->username }} on {{ $post->created_at }}</div>
<div class="interaction">
Like
#if(auth()->user() === $post->user)
|
Edit |
Delete
#endif
</div>
</article>
#endforeach
</div>
<script>
var token = '{{ session()->token() }}';
var urlLike = '{{ route('like') }}';
</script>
</section>
The JavaScript to get the postid from the form:
...
$('.like').on('click', function (event) {
event.preventDefault();
postId = event.target.dataset.postid;
var isLike = event.target.previousElementSibling==null ? true:false;
$.ajax({
method: 'POST',
url: urlLike,
data: {isLike: isLike, postId: postId, _token: token}
})
.done(function () {
//change the page
})
})
...
The route:
Route::post('/like',[
'uses' => 'PostController#postLikePost',
'as' => 'like'
]);
Finally, can someone please tell me how to send the output from the controller to the HTML form?
public function postLikePost(Request $request)
{
$post_id = $request['postId'];
$is_like = $request['isLike'] === 'true' ? true : false;
$post = Post::find($post_id);
if (!$post) {
return null;
}
$user = Auth::user();
$like = $user->likes()->where('post_id', $post_id)->first();
if ($like) { // user already liked the post
$like->delete();
return null; // output to "Like" in the html form here
}
$like = new Like();
$like->post_id = $post->id;
$like->user_id = $user->id;
$like->save(); // output to "Liked" in the html from here
return null;
}
The label of the Like anchor should change from Like to Liked if the user has already like the post.

I'd set up both as POSTs and then in your success block query the result and set to either like or liked. Something like:
success: function (data) {
document.getElementById("something").innerHTML = "Liked";
}

You can do it something like this, change it as per your need though.
public function postLikePost(Request $request)
{
$post = Post::where('id', $request->get('post_id'))->first();
if(!$post){
return response()->json(['status' => 1, 'message' => 'post not found']);
}
if($post->liked == 1)//change it as per your model
{
return response()->json(['status' => 2, 'message' => 'already liked']);
}
$post->status = 1;
$post->save();
return response()->json(['status' => 3, 'message' => 'liked']);
}
and in your ajax success
success: function(response){
if(response.status == 1){
window.alert('Post Not Found')
}
else{
document.querySelector('#likeBtn').innerHTML = 'liked'
}
like button
Like

Related

Wordpress Category Filtering Stuck

Everytime I click a category it shows only "Filtering..." and not loading all the post.
Filtering Issue
HTML
<div class="filters"> <span class="filter active" data-set="all"><span>Show all</span></span> <?php $categories = get_categories(array( 'hide_empty' => true, 'exclude' => array(1, 143) )); foreach ($categories as $category) : ?> <span class="filter" data-set="<?= $category->slug ?>"><span><?= $category->name ?></span></span> <?php endforeach; ?> </div>
SCRIPT
`(($) => {
const filters = $("#filterBar .filters");
const articles = $("#all-posts .articles");
filters.children('.filter').click(function(e) {
e.preventDefault();
const button = $(this),
loader = $("#loader"),
data = {
'action': 'filterposts',
'category': $(this).data('set')
};
$.ajax({
url : latest_reads_params.ajaxurl,
data : data,
type : 'POST',
beforeSend : function ( xhr ) {
articles.html("<span class='message'>Filtering...</span>");
loader.remove();
filters.find('.active').removeClass('active');
button.addClass('active');
},
success : function( data ){
if( data ) {
data = JSON.parse(data);
articles.hide().html(data.posts).slideDown(400);
if (data.max_pages > 1) {
articles.after('<div id="loader">'+
'<span class="ibtn secondary large" id="loaderAction" data-category="'+data.category+'" data-maxpages="'+data.max_pages+'">Load more</span>'+
'</div>');
}
} else {
articles.html("<span class='message'>No post found for filter</span>");
}
}
});
});
})(jQuery);`
I wanted to display all category post

Wordpress how to use Ajax to show new data returned from successful insert_post()?

After a successful Ajax insert of an entry, I would like to see what the ID and url of that same entry is and display it in a modal window without refreshing the page
Any way to get this data from success: function (response) {}? This is the code I have to make a new entry with ajax which works perfect:
<script>
$("#enquiry_email_form").on("submit", function (event) {
event.preventDefault();
var form= $(this);
var ajaxurl = form.data("url");
var detail_info = {
post_title: form.find("#post_title").val(),
post_description: form.find("#post_description").val()
}
if(detail_info.post_title === "" || detail_info.post_description === "") {
alert("Fields cannot be blank");
return;
}
$.ajax({
url: ajaxurl,
type: 'POST',
data: {
post_details : detail_info,
action: 'save_post_details_form' // this is going to be used inside wordpress functions.php// *esto se utilizará dentro de las functions.php*
},
error: function(error) {
alert("Insert Failed" + error);
},
success: function(response) {
modal.style.display = "block"; * abre la ventana modal*
body.style.position = "static";
body.style.height = "100%";
body.style.overflow = "hidden";
}
});
})
</script>
<button id="btnModal">Abrir modal</button>
<div id="tvesModal" class="modalContainer">
<div class="modal-content">
<span class="close">×</span> <h2>Modal</h2> * Ventana modal mostrar le url y ID generado *
<p><?php ***echo $title_post, $url, $ID*** ?></p>
</div>
</div>
Archive funtions.php
function save_enquiry_form_action() {
$post_title = $_POST['post_details']['post_title'];
$post_description = $_POST['post_details']['post_description'];
$args = [
'post_title'=> $post_title,
'post_content'=>$post_description,
'post_status'=> 'publish',
'post_type'=> 'post',
'show_in_rest' => true,
'post_date'=> get_the_date()
];
$is_post_inserted = wp_insert_post($args);
if($is_post_inserted) {
return "success";
} else {
return "failed";
}
}
When you use wp_insert_postDocs function, it'll return the post id.
It returns the post ID on success. The value 0 or WP_Error on failure.
First you could initiate an empty array and call it, let's say, $response and populate it based on the returned value from wp_insert_post function.
Then, we could use the id to get the permalink as well, using get_permalinkDocs.
And at last, we could send that array back to the client-side by using wp_send_json_successDocs function.
So your code on the php side would be something like this:
function save_enquiry_form_action() {
$response = array(
'error' => '',
'success' => '',
'post_id' => '',
'post_url' => '',
);
$post_title = sanitize_text_field($_POST['post_details']['post_title']);
// Note we could have used 'sanitize_title()' function too!
$post_description = sanitize_textarea_field($_POST['post_details']['post_description']);
$args = array(
'post_title' => $post_title,
'post_content' => $post_description,
'post_status' => 'publish',
'post_type' => 'post',
'show_in_rest' => true,
'post_date' => get_the_date()
);
$post_id = wp_insert_post($args);
if($post_id){
$response['success'] = true;
$response['error'] = false;
$response['id'] = $post_id;
$response['post_url'] = get_permalink($post_id);
}else{
$response['success'] = false;
$response['error'] = true;
}
wp_send_json_success($response);
exit;
}
Note:
I've used sanitize_text_fieldDocs function to sanitize the $_POST['post_details']['post_title'] value and sanitize_textarea_fieldDocs function to sanitize the $_POST['post_details']['post_description'] value.
When you receive the response on the client-side, you could check for $response['success'] and $response['error'] values.
On the javascript side
As you can see on the following screenshot, data returns as data object. To access data you could use response.data.success, response.data.error, response.data.id and response.data.post_url.

Cannot submit form from controller after ajax call [symfony]

I have a view in which I need after a click to send a javascript variable to a controller which contains a form that I send to the database.
So after the click, I'm using ajax to call my controller and load the html on the same view like this:
$(".month").click(function(){
var click = $(this);
var month = click.val();
var year = $("#years").val();
var url = Routing.generate('av_platform_formulaire');
$.ajax(url,
{
type: 'GET',
data: {"month": month,
"year" : year},
dataType: "html",
success: function (data) {
$('#content').empty();
$('#content').append(data);
},
error : function(jqXHR, textStatus, errorThrown){}
});
});
So far there is no problem, my view containing the form is loading correctly and I receive the data I sent via the ajax request but when I fill my form and try to submit it, the page is refreshing and it's like nothing happens...
Here is my 2 controllers (the second is the problematic one):
public function saisieAction(Request $request){
$thisyear = date("Y");
return $this->render('AvPlatformBundle:Platform:saisie.html.twig',
array(
'year' => $thisyear
));
}
public function formulaireAction(Request $request){
$user = $this->getUser();
$em = $this->getDoctrine()->getManager();
//$repository = $em->getRepository('AvPlatformBundle:NoteDeFrais');
// Create the form
$form = $this->get('form.factory')->createBuilder(FormType::class)
->add('ndf', CollectionType::class, array(
'entry_type' => NoteDeFraisType::class,
'label' => false,
'allow_add' => true,
'allow_delete' => true,
))
->getForm();
if ($request->isXmlHttpRequest()){
$month = $request->get('month');
$year = $request->get('year');
$sub_date = $month . '/' . $year;
}
if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
// After debugging, the code inside the if is not executed
$notesDeFrais = $form['ndf']->getData();
foreach ($notesDeFrais as $ndf) {
$ndf->setUser($user);
$ndf->setMois($sub_date);
$em->persist($ndf);
}
$em->flush();
}
return $this->render('AvPlatformBundle:Platform:formulaire.html.twig',
array(
'form' => $form->createView()
));
}
My view containing the form:
<div id="ms_form">
{{ form_start(form) }}
<div id="bloc_saisie" class="fieldset">
<fieldset>
<div id="form_ndf" class="form_ndf" data-prototype="
{% filter escape %}
{{ include('AvPlatformBundle:Platform:prototype.html.twig', { 'form': form.ndf.vars.prototype }) }}
{% endfilter %}">
</div>
<div class="buttons">
<button type="button" class="fas fa-plus" id="add_ndf"></button>
<input type="submit" class="btn btn-primary btn-lg" id="next_button" >
</div>
</fieldset>
</div>
{{ form_row(form._token) }}
{{ form_end(form, {'render_rest': false}) }}
</div>

Laravel how to retrieve name with user_id using angular?

I'm only able to fetch data with title and body attribute, but when i get data for the name it shows up empty when i refresh the page but shows when i submit automatically.
For some reason angularjs is not retrieving the name successfully.
Note: I'm using laravel.
For example here:
Here is the server side:
PostController
public function getPosts() {
$posts = Post::with('user')->get();
$response = new Response(json_encode($posts));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
public function storePost(Request $request) {
$data = request()->validate([
'title' => 'required|max:120',
'body' => 'required|max:1000'
]);
$data['user_id'] = auth()->user()->id;
$data['name'] = auth()->user()->name;
$post = Post::create($data);
$response = new Response(json_encode($data));
$response->headers->set('Content-Type', 'application/json');
// return redirect('/home')->withMessage('A new post was created.');
return $response;
}
main.js
$scope.myposts = {};
$scope.addPost = function() {
$http.post('/auth/post', {
title: $scope.post.title,
body: $scope.post.body
}).then(function(data, status, headers, config) {
console.log(data);
$scope.myposts.push(data.data);
});
$scope.post.title = '';
$scope.post.body = '';
};
$scope.deletePost = function(post) {
var index = $scope.myposts.indexOf(post);
if (index != -1) {
$scope.myposts.splice(index, 1);
}
$http.delete('auth/post/' + post.id);
};
$scope.getPosts = function() {
$http.get('/auth/posts').then(function(data) {
$scope.myposts = data.data;
}).then(function(data, status, header, config) {});
};
HTML:
<div id="mypost" class="col-md-8 panel-default" ng-repeat="post in myposts">
<div id="eli-style-heading" class="panel-heading">
<% post.title %>
</div>
<div class="panel-body panel">
<figure>
<p>
<% post.body %>
</p>
by:
<p>
<% post.user.name %>
</p>
</figure>
<span><button ng-click="deletePost(post)">x</button></span>
</div>
</div>
When i first add content without refresh(asynchronously)
on page refresh
above
(different log for different post)
Your reload page is okay since
$posts = Post::with('user')->get();
returns
{
"title": "title",
"body": "body",
"user": {
"name": "name"
}
}
and in your angular you display it by
<% post.user.name %>
So the solution to display it when you added is to restructure your json object before pushing to array
$scope.addPost = function() {
$http.post('/auth/post', {
title: $scope.post.title,
body: $scope.post.body
}).then(function(data, status, headers, config) {
console.log(data);
data.data['user'] = {
name: data.data.name
}
$scope.myposts.push(data.data);
});
$scope.post.title = '';
$scope.post.body = '';
};

autocomplete and multiple function using ajax in laravel

I am new to laravel framework. I want to complete a important task in my app.
In that app they have modules like invoices,quotes,payment,customers. for particular customers they have multiple invoices with status of sent and partially paid.
Here is the receipt page, on type of customer name it will get autosuggestion from customer table. Onclick of cutomer name it will get invoice details from (invoice table) based on customer id,and need to show on table below that customer name textbox, onclick of table invoice it will open modal which means if the particular customer has unpaid invoice they need to record payment else proceed with normal receipt creation.
I try the code like this, But I am not getting proper output please anyone help me to get out of this issue.
<input type="text" name="customername" required="required" id="cust" placeholder="Customer Name" class="form-control col-md-7 col-xs-12 typeahead"/>
$( function() {
$( "#cust" ).autocomplete({
//source: "http://www.duminex.com/client/search",
source: "{{route('search.client')}}",
select: function( event, ui ) {
get_invoices(ui.item.id);
$('#id').val(ui.item.id);
$('#clientAddress').val(ui.item.address);
}
});
} );
function get_invoices(client_id)
{
$.ajax({
method: 'GET',
url: "{{route('client.details')}}"
}).done(function(data){
alert(data);
});
}
routes
Route::get('/client/search',[
'uses'=>'ClientsController#search',
'as'=>'search.client'
]);
Route::get('/client/search2', 'ClientsController#search2')->name('client.details');
Controller
public function search(Request $request)
{
$s= Input::get('term');
$clients = Client::select("id" ,"user_id", "companyname", "companyaddress" , "billingAddress")->where('companyname','like','%'.$s.'%')->where('user_id',Auth::user()->id)->get();
if(count($clients) == 0){
$searchResult[] = "No Item found";
}
else{
foreach ($clients as $key => $value) {
$searchResult[] = ['id' => $value->id, 'value' => $value->companyname , 'email' => $value->companyaddress , 'address' => $value->billingAddress];
}
}
return $searchResult;
}
public function search2(Request $request)
{
$clients = Invoice::select("invoiceNo")->where('status',['sent,Partially paid'])->where('client_id',$request->client_id)->get();
if(count($clients) == 0){
$searchResult[] = "No Item found";
}
else{
foreach ($clients as $key => $value) {
$searchResult[] = ['invoiceNo' => $value->invoiceNo];
}
}
return $searchResult;
}
Thanks in advance. Please anyone to help me get out of this issue.
You are not passing any data to the ajax so thats why you are not getting any result.
Try below code :
function get_invoices(client_id) {
$.ajax({
method: 'GET',
data : {
client_id: client_id
},
url: "{{route('client.details')}}"
}).done(function(data){
alert(data);
});
}

Categories