How to use Ajax to update RenderBody() - ajax

I am trying to work with ajax in order to update only a partial view and not the whole view. In the following example I want to refresh the page-content section.
this is my layout.html.
<body>
<div id="container" class="effect">
#Html.Partial("_head")
<div class="boxed">
<section id="content-container">
#if (ViewData["Errors"] != null)
{
<div class="panel" style="background-color:white;">
<div class="panel-heading">
<h3 class="panel-title">
Page title
</h3>
</div>
</div>
}
<div id="page-content" class="container">
#RenderBody()
</div>
</section>
</div>
</div>
</body>
Partial view _head contains the menu with href links for example:
<a id="a1" href="">Menu Item 1</a>
In layout I am trying to use the following:
<script>
$(document).ready(function () {
$("#a1").click(function () {
A1();
});
function A1( ) {
$.ajax({
url: '#Url.Action("PartialViewMethodFromController", "HomeController")',
success: function (response) {
$('#page-content').html(response);
}
});
}
});
</script>
And my HomeController
public ActionResult PartialViewMethodFromController()
{
var model = service.GetAll();
return PartialView("PartialViewMethodFromController", model);
}
It kinda works - the partialview is refreshing for a moment and the partialview is show correctly and then the whole page goes on and refreshes.
Am I missing something crucial here?

Related

Livewire show variable

I have a variable $login that will contain data.
public $account;
public $login;
public function getAccountOrder($id)
{
$this->account = Buys::findOrFail($id);
$this->login = $this->account->accounts;
}
public function render()
{
$buys = Buys::where('user_id', auth()->user()->id)->get();
return view('livewire.profile', compact('buys'));
}
Modal opening (modal in same view that all content)
In modal displays this variable, but it does not display the required data. But in livewire helper (google extension) i can see data that i need to display
<div wire:ignore.self class="remodal remodal--prize" data-remodal-id="modal-account-email" aria-labelledby="modalRandTitle" aria-describedby="modalRandDesc" tabindex="-1">
<button type="button" class="remodal__close" data-remodal-action="close">
<svg><use xlink:href="#svg-btn_modal_close"></use></svg>
</button>
<div class="modal__header" id="modalRandTitle">Your login</div>
<div class="modal__content" id="modalRandDesc">
<div class="modal__accounts">
<div class="modal__accounts-row">
<div class="input__box">
<div class="input__box-btn" data-btn-clipboard="{{ $login }}" onclick="copyToClipboard('{{ $login }}')">
<svg class="svg-btn_clipboard"><use xlink:href="#svg-btn_clipboard"></use></svg>
<svg class="svg-btn_check"><use xlink:href="#svg-btn_check"></use></svg>
</div>
<div class="input__box-field">
<div class="input__box-label">Login</div>
<div class="input__box-value">{{ $login }}</div>
</div>
</div>
</div>
</div>
</div>
</div>
How can i render this variable in livewire component?
It seems you want the changed value of $login gets reflected in the javascript on the page. if this is the case you need to dispatch an event from your getAccountOrder function and catch it on the page with js.
something like this:
public function getAccountOrder($id)
{
$this->account = Buys::findOrFail($id);
$this->login = $this->account->accounts;
$this->dispatchBrowserEvent('yourEventName', ['value'=> $this->login]);
}
then on the something like this should be added:
<script>
window.addEventListener('yourEventName', (e) => {
//do something with the value
console.log(e.detail.value);
});
</script>

Don't see a div into a vue component

I have a vue component with a div and a button and into another div I have two components
<script>
export default {
name: 'excursion-backend-component',
methods:{
doRedirection: function () {
window.location = APP_URL+"/excursiones/create";
}
},
mounted() {
console.log(APP_URL+"/excursiones/create");
console.log("aaaa");
}
}
</script>
<template>
<div class="container">
<h3>Adicionar excursión</h3>
<div style="text-align: right">
<a class="btn btn-primary" :href="doRedirection"><i class="fa fa-plus"></i> Adicionar</a>
</div>
<br>
<div>
<excursion-list-component></excursion-list-component>
<excursion-add-component></excursion-add-component>
</div>
</div>
</template>
But I don't see the button on the navigator.
What is wrong?
Here is how I see the page
:href="" expecting string with url to navigation, but you using method.
Use #click instead :href, if you want to use method.
<a #click="doRedirect">... </a>
Or, may be, move it to computed block
computed: {
excursionesUrl () {
return APP_URL+"/excursiones/create";
}
}

Data not going to controller using Ajax

I am new to AJAX and I am trying to send some data to the controller using the AJAX. on clicking the button "Start Event", nothing is happening..
This is my jsp page where I have written the AJAX code
<c:forEach items="${scheduledEvents}" var="event">
<div class="col-md-3" id="eventId">
<div class="card-counter primary">
<div id="head" class="card-counter head-color"></div>
<span class="count-head">${event.eventName}</span>
<br>
<span class="count-name">Date : ${event.date}</span>
<span class="count-name">Location : ${event.location}</span>
<span class="count-name">Hosted By : ${event.hostName}</span>
<span class="count-name">Description : ${event.description}</span>
<br>
<br>
<div class="count-join">
<button class=" btn" id="${event.linkId}" style="background-color: #cc3300;"><font style="color: white;">Start Event</font></button>
</div>
</div>
</div>
</c:forEach>
<script type="text/javascript">
$(function() {
$('.count-join').on('click',function(){
var eventData = $(this).attr("id")
.ajax({
url : 'startEvent?data=' +eventData,
type : 'GET',
contentType : 'application/json',
success : function(data){
$
.get(
'${pageContext.request.contextPath}/startEvent',
function(data,status) {
$("#eventId").html(data);
}
);
}
});
});
});
</script>
And this my controller mapping
#RequestMapping(value="/dashBoard/startEvent")
public ModelAndView startScheduledEvent(#RequestParam("data")String data)
{
System.out.println(data);
return new ModelAndView("DashBoard");
}
Where am I wrong? please give some detailed explanation as I do not know much about AJAX. Thanks in advance.
As per you controller #RequestMapping, you have missed the /dashBoard in ajax call.

AJAX (JSON) problems with NGRepeat

I've got problem with outputting my JSON from server (Node.js) to NGrepeat.
I have tried a lot and debugged with both Firebug and Firefox Web Inspector.
For some reason it will not show the data from the JSON, even then the JSON looks correct when I output it in the Firebug console (using Firefox 39.0).
JSON:
[{ nr:"1", svenska:"test2", spanska:"testo2"},{ nr:"2", svenska:"test3", spanska:"testo3"},{ nr:"3", svenska:"test4", spanska:"testo4"},{ nr:"4", svenska:"test5", spanska:"testo5"},{ nr:"5", svenska:"test6", spanska:"testo6"}]
Angular.js
/**
*
* The client Angular.JS main file for the project
*/
var glosorApp = angular.module('glosorApp',['directives']); /* */
angular.module('directives', [])
.directive('toggleClass', function () {
var directiveDefinitionObject = {
restrict: 'A',
template: '<div ng-click="localFunction()" ng-class="selected" ng-transclude></div>',
replace: false,
scope: {
model: '='
},
transclude: true,
link: function (scope, element, attrs) {
scope.localFunction = function () {
scope.model.value = scope.$id;
};
scope.$watch('model.value', function () {
if (scope.model.value === scope.$id) {
scope.selected = "active";
} else {
scope.selected = '';
}
});
}
};
return directiveDefinitionObject;
});
glosorApp.controller('listController', function ($scope, $http) {
$http.post(PROJEKT_SOKVAG+'/_myroute',
{type:AJAX.LISTA_GLOSOR_CLI_R}).success( function(data) {
console.log("Kommer hit lookdeep: "+lookdeep(data.data));
$scope.glosor = data.data;
// $scope.$apply();
console.log("Kommer hit lookdeep: $scope.glosor "+lookdeep($scope.glosor));
});
});
function ajaxanrop(callback, data_) {
$.ajax({
url: PROJEKT_SOKVAG+'_myroute',
type: 'POST',
dataType: 'json',
data: data_ , // the data that should be sent to server
success: function(data) { if ( callback ) callback(data); },
error: function() { if ( callback ) callback(null); },
complete: function() { /* console.log("Klart"); */ }
});
}
HTML (EJS template)
<!DOCTYPE html>
<html ng-app="glosorApp" ng-init="model = { value: 'dsf'}">
<head>
<title>Glosor</title>
<script type="text/javascript">
var PROJEKT_SOKVAG="<%=project_path %>", LoginUser="<%= user.username %>";
</script>
<script type="text/javascript" src="http://w42.se/webbroot/js/jquery-1.9.1.min.js"></script>
<script src="http://w42.se/<%=project_path %>/jquery-ui-1.js" type="text/javascript"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.js"></script>
<script type="text/javascript" src="http://w42.se<%=project_path %>/lookdeep.js"></script>
<script type="text/javascript" src="http://w42.se<%=project_path %>/constants.js"></script>
<script type="text/javascript" src="http://w42.se<%=project_path %>/clientAngular.js"></script>
</head>
<body>
<div id="vald_sida" style="display:none;" class="mentorer"></div>
<p>Användarnamn: <%= user.username %></p>
<p>Email: <%= user.email %></p>
<p>Log out</p>
<div id="wrapper" ng-controller="listController" >
<p>Lägg till Glosor</p>
<p>Testa Glosor</p>
<div class="clear"></div>
<div class="list">
<div class="filterarea">
<h4>Sökning</h4>
<div>
<span>Nr: <input ng-model="search.nr" ng-model-options="{debounce: 20000}"></span>
<span>Svenska: <input ng-model="search.svenska" ng-model-options="{debounce: 20000}"></span>
<span>Spanske: <input ng-model="search.spanska" ng-model-options="{debounce: 20000}"></span>
<span>Poäng: <input ng-model="search.poang" ng-model-options="{debounce: 20000}"></span>
</div>
</div>
<div class="pad clearfix">
<h4>Resultat</h4>
Välj: alla <input type="checkbox" ng-model="master"><br/>
<div ng-form="">
<div class="list">
<div class="thead">
<div>
<span class="sortable"><a href=""
ng-click="predicate = 'nr'; reverse=!reverse">#</a></span>
<span class="sortable td"><a href=""
ng-click="predicate = 'svenska'; reverse=!reverse">Svenska</a></span>
<span class="sortable td"><a href=""
ng-click="predicate = 'spanska'; reverse=!reverse">Spanska</a></span>
<span class="sortable td"><a href=""
ng-click="predicate = 'poang'; reverse=!reverse">Poäng</a></span>
</div>
</div>
<div class="tbody">
<div ng-repeat="glosa in filter_glosor = (glosor | orderBy:predicate:reverse | filter:search)">
<div class="tr" toggle-class="" model="model">
<span class="td">{{glosor.nr}}</span>
<span class="td">{{glosor.svenska}}</span>
<span class="td">{{glosor.spanska}}</span>
</body>
</html>
As for the ng-repeat issue, it looks like you're using a filter incorrectly. Try this:
<div ng-repeat="glosa in glosor | orderBy:predicate:reverse | filter:search">
NB If you're trying to GET data, you should use $http.get instead of the $http.post(PROJEKT_SOKVAG+'/_myroute', you have.
It will save confusion down the road when maintaining the app.
Well, I found the error that I made, and it was a ridiculously simple error. Quite embarrasing actually... ;-)
I put glosor.svenska instead of glosa.svenska in the repeated block (inside the NGRepeat).
That's the bad thing with having the array name and the element name too similar, you might mix them up.
This means that I put the array instead of the repeated single array element inside the repeated block.

bootstrap load collapse panel with ajax

I'm trying to load collapsable panels with ajax. I got it working, but my trigger fires on the a tag, so the ajax script is called when you open AND close the panel. It should not load it when you close the panel, this is overload..
My code:
<div class="panel-group" id="accordion">
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title"><a data-toggle="collapse" data-parent="#accordion" href="#collapse1">First panel</a></h4>
</div>
<div id="collapse1" class="panel-collapse collapse">
<div class="panel-body">
<div id="depUsers511"><!-- here users will be loaded through ajax --></div>
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title"><a data-toggle="collapse" data-parent="#accordion" href="#collapse2">Second panel</a></h4>
</div>
<div id="collapse2" class="panel-collapse collapse">
<div class="panel-body">
<div id="depUsers511"><!-- here users will be loaded through ajax --></div>
</div>
</div>
</div>
The javascript:
$('#accordion a').click(function () {
var collapse_element = event.target;
alert(collapse_element);
var href = this.hash;
var depId = href.replace("#collapse","");
var dataString = 'depId='+ depId + '&do=getDepUsers';
$.getJSON(dir_pre + 'ajax/users.php?' + dataString, function(data) {
$('#depUsers'+depId).html(data);
});
})
The ajax script returns the content of the div.
So, it works, but I'm looking for the correct way to fire the ajax load trigger... i think I need to use the "show.bs.collapse" event, but can't find out how to use this on a panel which contains more than one dynamic panel (with its own ID).
You can try this:
$('#accordion').on('show.bs.collapse', function(e){
var depId = $(e.target).attr('id').replace('collapse','');
...
});
I kind of solved it by adding a "open" class when loaded with data, and removing that same class if clicked when opened:
$('#accordion a').click(function () {
if($(this).hasClass("panelisopen")){
$(this).removeClass("panelisopen");
} else {
var href = this.hash;
var depId = href.replace("#collapse","");
$(this).addClass("panelisopen");
var dataString = 'depId='+ depId + '&dep=1&do=getDepUsers';
$.getJSON(dir_pre + 'ajax/users.php?' + dataString, function(data) {
$('#depUsers'+depId).html(data);
});
}
});
Not the best solution I guess, but it works.
I think instead of depending on element ID, and polluting it with numbers and do the string replacement and so, you can make use of data attributes:
<div class='collapse' data-dep-id="1" />
Then in JS:
var $elementId = $(e.target).data('dep-id')
And the same applies for Ajax URL and other attributes if needed.

Resources