I am working with Laravel and viewing some data in Bootstrap modal using Rander view.
I am opening the modal on click and getting render data in it.
Here is how I am randoing data in my controller:
$view = \View::make('list.modal-body', ['list'=>$list]);
$message = $view->render();
return response()->json([
ajax_request_return_data' => $message
]);
I am getting this $message which is an HTML response to my Ajax request.
and then I am rendering this on a modal body.
Here is my HTML data which I am randoring:
<div class="table-responsive">
<table>
<thead>
<tr>
</tr>
</thead>
<tbody>
#foreach($list as $single_detail)
<tr>
<td>{{ $single_detail->detail_name }}</td>
</tr>
#endforeach
</tbody>
</table>
</div>
and here Is the AJAX function which I am Using:
$.ajax({
type : 'POST',
url : URL-OF-AJAX',
data : { 'related_data' : ralate_data_detail },
success: function(data) {
$('.CLASS_OF_Modal_Body').append(data.ajax_request_return_data)
$('#modal_id').modal('toggle');
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
}
});
ISSUE
The issue is when I render data the old render data showing in the table with new data and it keeps adding on every time I open that modal
What possible solution I have tried?
I have tried to pass the empty data before adding a new one but still shows old data in the modal table.
I have also tried to remove the view cache but still old data came in a table with new data.
Pelase help me on this how can I Randor FRESH data in the table every time and remove the old render data.
Instead of using append use html method.
Replace
$('.CLASS_OF_Modal_Body').append(data.ajax_request_return_data)
to
$('.CLASS_OF_Modal_Body').html(data.ajax_request_return_data)
Ref:
https://api.jquery.com/html/
https://api.jquery.com/append/
Related
Am having a problem deleting multiple rows in Laravel and Vue Js. I am able to get the values of id as an array. When I click on delete button I get a status 200 but no record is deleted from the database. Here is my code:
In my table
<tr v-for="user in users.data" :key="user.id">
<td>{{user.id}}</td>
<td>{{user.userName}}</td>
<td><input type="checkbox" :value="user.id" v-model="checkedNames"></td>
<button class="btn btn-warning" #click=" deleteAllUser()">Delete
Selected</button>
</td>
</tr>
Vue Js
<script>
export default {
data(){
return{
checkedNames:[],
Function
deleteAllUser(){
this.form.post('api/deletehotspotusers/',{id:this.checkedNames}).then(()=>{
self.loadHotspotUsers();
}).catch(()=> {
Swal.fire("Failed!", "There was something wrong.", "warning");
});
}
}
In my controller
public function deleteAll(Request $request){
if($request->id){
foreach($request->id as $id){
HotspotUsers::destroy($id);
}
}
My route
Route::post('/deletehotspotusers', 'HotspotUsersController#deleteAll');
To delete a model record you need to call the delete method. You can try the below in the controller method
//import use statement at the top of the class
//use Illuminate\Support\Arr;
public function deleteAll(Request $request){
if($request->id){
HotspotUsers::whereIn('id', Arr::wrap($request->id))->delete();
}
}
In Vue, input type checkbox, v-model uses checked property and change event, so v-model will record either true or false based on the checked state. In order to populate the id with user.id, you need to make use of change event
<tr v-for="user in users.data" :key="user.id">
<td>{{user.id}}</td>
<td>{{user.userName}}</td>
<td>
<input type="checkbox" :value="user.id" #change="onChecked(user.id)">
</td>
<td>
<button class="btn btn-warning" #click=" deleteAllUser()">
Delete Selected
</button>
</td>
</tr>
And in the script section in methods
onChecked(id){
if(!this.names.includes(id)){
this.names.push(id)
} else {
this.names.splice(this.names.indexOf(id),1)
}
}
I am not into vue.js.
If your front-end works good, then here is the laravel code.
Make sure that $request->id is receiving the value you expected.
You can use like
Model::destroy([array of primary keys])
If your Model's primary key is id, then you can specify array of ids like [1,2,3,4].
But before make sure the input values by using logger($request->id).
Thank you
just a very new to Vue 2.0, i actually use if for Laravel 5.4, now you can see from below link that i created one component which name is "canvas-chart", what actually i want show is a filterable table, and then to get more Json data from next steps, but now it always show me "Unknown custom element: - did you register the component correctly? For recursive components, make sure to provide the "name" option." , can not understand that i follow the official documentation to use it why it's not work?
new Vue({
el:'#filterTest',
data:{
keywords:[{"id":"9","name":"missy","phone":"21324234532"},
{"id":"3","name":"Mahama","phone":"345604542"},
{"id":"2","name":"Bernard","phone":"241242542"}]
},
computed: {
filterM: function () {
var self = this
return self.filter(function (word) {
return user.name.indexOf(self.searchQuery) !== -1
})
}
}
});
Vue.component('canvas-chat',{
template:'#canvasChart',
props:['keywordsData']
})
<script type="text/x-template" id="canvasChart">
<table>
<thead>
<tr>
<th v-for="key.id in keywordsData">
<span class="arrow" ></span>
</th>
</tr>
</thead>
<tbody>
<tr v-for="key.name in keywordsData">
<td v-for="key.phone in keywordsData"> {{key.name}}</td>
</tr>
</tbody>
</table>
</script>
<div id="filterTest">
<canvas-chat keywordsData="keywords" ></canvas-chat>
</div>
You have a few issues:
You must register the canvas-chat component first before you use it in the main component (put Vue.component('canvas-chat', ... before new Vue(...)).
Your v-for loops are wrong. They should be like v-for="key in keywordsData", not v-for="key.id in keywordsData".
The v-fors on the tr and td elements don't make sense; you will have to process the keywordsData first (perhaps in a computed property) to get it into the correct format you want, then loop over that.
You must bind the keywordsData prop in the template like this: :keywords-data="keywords".
On index.html I have two pages JQM v.1.4.
In page-1 I´ve a form that get (nombreUsuario) and password and assign into respective vars.
In page-2 , I want to use the previous (nombreUsuario) for to get table that match with this nombeUsuario via AJAX on Datatable Editor 1.4.
My problem is that in page-1 the AJAX call is executed before that I enter nombreUsuario , therefore when pass to page-2 the table is empty , due the AJAX call was executed with variable empty , without nombreUsuario entry.
I´ve tried different code to get that AJAX call executed after entry nombreUsuario but I don’t get desired result . I´ve used async to false, but to do nothing .
Also, DataTable Editor AJAX document said :
Success: Must not be overridden as it is used internally in DataTables . Even so, I´ve used this option (taking jquery examples) and is true that don’t work (is yes, please tell me!) .
Now, will be more easy resolve it on JQM?. How can I to get nombreUsuario on page-1 and after pass to page-2 , then will execute AJAX call with this variable?
Any idea?. Thank you in advance!
index.html
<div data-role="page" id="page0">
<form id="formulario" >
<label> Usuario </label>
<input type="text" id="nombredeusuario" name="nombredeusuario">
<label> Password </label>
<input type="password" id="clave" name="clave" >
<input type="submit" value="Login" id="botonLogin">
</form>
...
<div data-role="page" id="page1">
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Establecimiento</th>
<th>Telefono</th>
<th>E-mail</th>
<th>Nº de Plazas</th>
<th>Precio medio</th>
<th>E-mail (responsable)</th>
<th>Prueba (1) / Contrato (2)</th>
</tr>
</thead>
....
JS:
(form)
$('#formulario').submit(function() {
// recolecta los valores que inserta el usuario
var datosUsuario = $("#nombredeusuario").val()
var datosPassword = $("#clave").val()
...
JS (datatable editor 1.4)
$('#example').DataTable( {
//check. start
initComplete: function(settings, json) {
alert( 'DataTables has finished its initialisation.' );
},
//check.end
dom: "Tfrtip",
ajax: {
async: false, // don't work
url:"http://tripntry.com/_country/spain/b.cartasconmenu.front.back.demo/alacarte/php/clientes.php",
type: "POST",
data: function ( d ) {
d.site = $("#nombredeusuario").val(); // dont work!
//d.site = datosUsuario; //// dont work!
//d.site = "34280001"; // works (of course)
},
....
PHP (server side)
include( "../../php/DataTables.php" );
// Alias Editor classes so they are easy to use
use
DataTables\Editor,
DataTables\Editor\Field,
DataTables\Editor\Format,
DataTables\Editor\Join,
DataTables\Editor\Validate;
$site=$_POST['site'];
// Build our Editor instance and process the data coming from _POST
Editor::inst( $db, 'clientes' )
->fields(
Field::inst( 'tipo' )->validator( 'Validate::numeric' ), //this field another use
Field::inst( 'site' )->validator( 'Validate::notEmpty' )
)
->where( 'site', $site)
->process( $_POST )
->json();
I'm trying to set an image source using data returned from a modal. This is inside an ng-repeat loop:
<div id="divNetworkGrid">
<div id="{{network.id}}" ng-repeat="network in networks">
<span>
<table>
<tr>
<td class="imgContainer">
<img ng-src="{{ ('assets/img/networkicons/'+ network.actual + '.png') ||
'assets/img/networkicons/default.png' }}"/>
</td>
</tr>
</table>
</span>
</div>
</div>
As is apparent, I want to populate default.png when the network.actual model property is returned as null. But my code is not picking up the default image, though the first image is coming up fine when available.
I'm sure this is some syntax issue, but cant figure out what's wrong.
I have just found out, that you can use both ng-src and src on an img tag and if ng-src fails (variable used does not exists etc.), it will automatically fallback to src attribute.
What I imagine is happening is the src is returning a 404 even if network.actual is null. For example, first value:
('assets/img/networkicons/'+network.actual+'.png')
is evaluating to a 404 src URL, something like ('assets/img/networkicons/null.png'). So in the OR selection, it's truth-y, but the resource is 404. In that case, you can set the fallback via onError with something like:
<img ng-src="{{('assets/img/networkicons/'+network.actual+'.png')}}" onerror="this.src='assets/img/networkicons/default.png'" />
CodePen to demo use cases - http://codepen.io/jpost-vlocity/pen/zqqerL
angular.module('fallback',[]).directive('fallbackSrc', function () {
return{
link: function postLink(scope, element, attrs) {
element.bind('error', function () {
angular.element(this).attr("src", attrs.fallbackSrc);
});
}
}
});
<img ng-src="{{url}}" fallback-src="default-image.jpg"/>
angular.module('fallback', []).directive('actualSrc', function () {
return{
link: function postLink(scope, element, attrs) {
attrs.$observe('actualSrc', function(newVal, oldVal){
if(newVal != undefined){
var img = new Image();
img.src = attrs.actualSrc;
angular.element(img).bind('load', function () {
element.attr("src", attrs.actualSrc);
});
}
});
}
}
});
<img actual-src="{{url}}" ng-src="default.jpg"/>
link
Interesting way to use ng-src. I haven't tested how that expression would be handled but I would suggest doing it a more stable way:
<img ng-src="{{ networkIcon }}" />
And in your controller:
$scope.networkIcon = network.actual ? 'assets/img/networkicons/' + network.actual + '.png' : 'assets/img/networkicons/default.png';
Edit: Just to clarify, I'm not suggesting the best way to do this is to bind the image source directly to the scope but rather to move the image fallback logic outside of the view. In my applications I often do it in the services that retrieve the data or on the server itself and send an image URL so the client only has to worry about a single property.
Edit to address repeater:
angular.forEach($scope.networks, function(network) {
network.icon = network.actual ? 'assets/img/networkicons/' + network.actual + '.png' : 'assets/img/networkicons/default.png';
});
<tr ng-repeat="network in networks">
<td><img ng-src="{{ network.icon }}" /></td>
</tr>
<div id="divNetworkGrid">
<div id="{{network.id}}" ng-repeat="network in networks">
<span>
<table>
<tr>
<td class="imgContainer">
<img ng-src="{{'assets/img/networkicons/'+(network.actual || 'default' )+'.png'}}"/>
</td>
</tr>
</table>
</span>
</div>
</div>
The inline or will work if the the queried variable is undefined. The above will fix your issue
You can supply the alternative image after OR operator like this:
{{ book.images.url || 'Images/default.gif' }}
i have a Ajax function that works in Firefox but not in IE 6
my ajax script :
<script type="text/javascript">
function actualiserDLIS(){
var url = 'administration/gestionUtilisateurs.do?method=actualisationDLIs';
var params = 'DR='+encodeURIComponent(document.getElementById('selectDR').value);
var myAjax = new Ajax.Request(
url,
{ method: 'post',
parameters: params,
onComplete: majDLIS
});
}
function majDLIS(retour){
if (retour.status == 200)
{
alert("Retour Status: "+retour.responseText);
document.getElementById('tableDLI').innerHTML = retour.responseText;
}else{
document.getElementById('tableDLI').innerHTML = "uncool";
}
}
</script>
in my <body>
[...]
<table class="tabForm" id="tableDLI">
<c:forEach var="DLI" items="${sessionScope['fiscalite.AdministrationGestionUtilisateurForm'].DLISUtilisateur}" varStatus="status" >
<tr>
<td class="label_tableau_type1 width200px" ><c:out value="${DLI.code}"/>
</td>
<td class="width150px" colspan="3"><html:checkbox property="DLI(${status.count-1})"/>
</td>
</tr>
</c:forEach>
</table>
[...]
in my alertI'm recovering well my data that I want to display in my tableDLI
Apparently you're using Prototype. First I must mention that targeting IE6 is wrong, worse, it's evil. It's well known that this browser is broken in all sorts of ways. You probably have javascript errors in the browser, what are they?
Here is a what can be a useful link.