How to get id when I click Object Card? - ajax

how to get id when I click the card, I get id in concole.log .
but I don't know get id when card was clicked.
here is the code :
$.ajax({
url : 'https://www.thesportsdb.com/api/v1/json/1/search_all_leagues.php?',
type: 'get',
dataType: 'json',
data : {
's' : 'Soccer'
},
success: function(result){
let league = result.countrys;
$.each(league, function(i, data){
$('#club-list').append(`
<div class="col-md-4 p-2">
<div class="card shadow" onCLick="console.log(`+data.idLeague+`)">
<img src="`+ data.strBadge +`" class="card-img-top p-2" alt="...">
<div class="card-body">
<p class="card-text">`+ data.strLeague +`</p>
</div>
</div>
</div>`);
});
$('.card').on('click', function(){
$.ajax({
url : 'https://www.thesportsdb.com/api/v1/json/1/lookup_all_teams.php?',
type: 'get',
dataType: 'json',
data: {
// 'id' : '4328'
'id' : /* HOW TO GET ID FROM CARD WHEN USER CLICK CARD ? */
},
success: function(result){
let team = result.teams;
$.each(team, function(i, data){
$('#club-detail').append(`
<div class="col-md-4 p-2">
<div class="card shadow">
<img src="`+ data.strTeamBadge +`" class="card-img-top p-2" alt="...">
<div class="card-body">
<p class="card-text">`+ data.strTeam +`</p>
</div>
</div>
</div>`);
});
// window.location.href = "league.php";
console.log(team);
}
});
});
}
});
https://www.thesportsdb.com/api/v1/json/1/lookup_all_teams.php?id=4328 /* HOW TO GET ID WHEN USER CLICK CARD ? */
enter image description here

use class instead of id. because multiple id with same key won't work

$.ajax({
url : 'https://www.thesportsdb.com/api/v1/json/1/search_all_leagues.php?',
type: 'get',
dataType: 'json',
data : {
's' : 'Soccer'
},
success: function(result){
let league = result.countrys;
$.each(league, function(i, data){
$('#club-list').append(`
<div class="col-md-4 p-2">
<div class="card shadow" data-id="${data.idLeague}">
<img src="`+ data.strBadge +`" class="card-img-top p-2" alt="...">
<div class="card-body">
<p class="card-text">`+ data.strLeague +`</p>
</div>
</div>
</div>`);
});
$(document).on('click','.card', function(e){
console.log(this.dataset.id);
});
}
});

Related

How to update data on a page using ajax script?

There is a script that needs to update the data on the page in a specific div. But instead of updating, the block with the div is simply hidden and in order for it to appear again, you need to reload the page. The data comes in data, but here is $ ("# userPost" + id) .html (data); something doesn't work.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('.infinite-scroll').on('click', '#editPostButton', function(e) {
e.preventDefault();
var id = $(this).data('id');
var user_id = $('#userForm').val();
var form = document.getElementById('EditPostForm'+id);
var formData = new FormData(form);
// var formData = $('#EditPostForm'+id).serialize();
$.ajax({
url: "id"+user_id+"/"+id+"/edit",
type: "POST",
data: formData,
success: function(data) {
console.log(data);
$("#userPost"+id).html(data);
$("#closeButton"+id).click();
},
error: function() {
console.log('error');
},
processData: false,
contentType: false,
});
});
And div
<div id="userPost{{$post->id}}">
#if($post->img)
<div>
<img src="{{$post->img}}" class="img-fluid">
</div>
#endif
<br>
#if($post->title)
<div class=" mr-1 mb-3 titleleft">
<h5 style="color: black"><b>{{$post->title}}</b></h5>
</div>
#endif
#if($post->message)
<div class="text-muted text-small margins" style="white-space: pre-wrap;">{{mb_strimwidth($post->message, 0, 600, " . . . Read more")}}</div>
#endif
#if($post->videoPost)
<div class="embed-responsive embed-responsive-16by9 mt-4 mb-2">
<iframe class="embed-responsive-item" src="{{$post->videoPost}}" allowfullscreen></iframe>
</div>
#endif
</div>
Try doing this way:
$("#userPost"+id).load(url);
or
$("#userPost"+id).html(data).load(url);

Ajax request for delete image doesnt work in laravel

I want to delete the image in the preview box, as well as delete it in the database using ajax. Deleting the image in the preview box was successful, but deleting it from the database didn't work.
here my ajax:
$(document).ready(function() {
document.getElementById('pro-image').addEventListener('change', readImage, false);
$(".preview-images-zone").sortable();
$(document).on('click', '.image-cancel', function() {
let no = $(this).data('no');
let idData = $(this).data('id');
$(".preview-image.preview-show-" + no).remove();
$.ajax({
type: 'POST',
url: '{{url("unit/API/simpan")}}',
data: {
'id': idData
},
success: function(data) {
alert('success');
}
});
});
});
My Html:
<!-- Percobaan Preview -->
<fieldset class="form-group">
<div class="offset-md-2 col-md-6">
Upload Gambar
<input type="file" id="pro-image" name="gambarku[]" style="display: none;" class="form-control" multiple>
</div>
</fieldset>
<div class="preview-images-zone offset-md-2 col-md-8">
<!-- Gambar Utama -->
<div class="preview-image preview-show-1">
<div class="image-cancel" data-no="1">x</div>
<div class="image-zone"><img id="pro-img-1" src="{{asset('storage/rumah/'.$rumahku->gambar_rumah)}}"></div>
</div>
<!-- Gambar Tambahan -->
<?php $counter = 2 ?>
#foreach($rumahku->gambar as $rows)
<div class="preview-image preview-show-{{$counter}}">
<div class="image-cancel" data-no="{{$counter}}" data-id="{{$rows->id_gambar}}">x</div>
<div class="image-zone"><img id="pro-img-{{$counter}}" src="{{asset('storage/rumah/'.$rows->gambar_unit)}}"></div>
</div>
<?php $counter++ ?>
#endforeach
</div>
<!-- /preview -->
my route
Route::post('unit/API/simpan/{id}', 'partner\UnitController#simpanGambar');
my controller
public function simpanGambar($id)
{
$gambar = Gambar::find($id);
$gambar->delete();
}
you can try this
Route::post('unit/API/simpan', 'partner\UnitController#simpanGambar');
and
public function simpanGambar(Request $request)
{
$gambar = Gambar::find($request->id);
$gambar->delete();
}
or in ajax
$.ajax({
type: 'POST',
url: '{{url("unit/API/simpan")}}' +'/'+ id, <---------- pass id here

Confirm delete dialog using ajax and bootstrap

I'd like to display a confirm delete dialog using Bootstrap v3 before deleting an entity.
My code works fine, but without confirm dialog. How can I do that?
{% for travel in pagination %}
<div class="col-sm-6 col-md-4" id="item-{{ travel.id }}">
//......
<a title="delete" href data-entity-id="{{ travel.id }}" class="button btn-mini red remove_item">Delete</a>
</div>
{% endfor %}
<script>
$(document).ready(function () {
$(".remove_item").click(function () {
var entityId = $(this).attr('data-entity-id');
var itemId = 'item-' + entityId;
$.ajax({
type: 'POST',
dataType: 'json',
url: Routing.generate('travel_delete', {'id': entityId}),
success: function () {
//hide the block of item after delete success
$('#' + itemId).fadeOut();
}
});
return false;
});
});
</script>
Edited
I tried this code. I'd like when clicking on delete link, pass the value of attr entity-id which is in the delete link, to the attr data-entity-id in delete button in the modal. How can I do that ?
error console:
Failed to load resource: the server responded with a status of 404 (Not Found)
<a title="delete" href data-toggle="modal" data-target="#myModal" entity-id="{{ travel.id }}" class="button btn-mini uppercase red">Sup ajax</a>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button data-entity-id="" type="button" class="btn btn-primary remove_item">Delete</button>
</div>
<script>
$(document).ready(function () {
$('#myModal').on('show.bs.modal', function () {
var entityId = $(this).attr('entity-id');
// set new value of attr data-entity-id but doesn't work
$('.remove_item').attr('data-entity-id', entityId);
});
$(".remove_item").click(function () {
var entityId = $(this).attr('data-entity-id');
var itemId = 'item-' + entityId;
$.ajax({
type: 'POST',
dataType: 'json',
url: Routing.generate('frontend_travel_delete_favorite', {'id': entityId}),
success: function () {
$('#' + itemId).fadeOut();
}
});
return false;
});
});
</script>
Try to do this:
<a id="delete-btn" title="delete" href data-toggle="modal" data-target="#myModal" data-entity-id="{{ travel.id }}" class="button btn-mini uppercase red">Sup ajax</a>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button data-entity-id="" type="button" class="btn btn-primary remove_item">Delete</button>
</div>
<script>
$(document).ready(function () {
$('#delete-btn').on('click', function () {
var entityId = $(this).attr('data-entity-id');
$('.remove_item').attr('data-entity-id', entityId);
});
$(".remove_item").click(function () {
var entityId = $(this).attr('data-entity-id');
var itemId = 'item-' + entityId;
$.ajax({
type: 'POST',
dataType: 'json',
url: Routing.generate('frontend_travel_delete_favorite', {'id': entityId}),
success: function () {
$('#' + itemId).fadeOut();
}
});
return false;
});
});
</script>

Adding records to a drop down menu without form refresh

I want to add records to a drop down menu without form refresh. I'm using codeigniter and bootstrap
Here is the Bootstrap Modal :
<div class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button aria-hidden="true" data-dismiss="modal" class="close" type="button">×</button>
<h4 id="myLargeModalLabel" class="modal-title">Add Record</h4>
</div>
<div class="modal-body">
<form class="sky-form" id="sky-inchidere" method="post" accept-charset="utf-8" action="">
<dl class="dl-horizontal">
<dt>Name<span class="color-red">*</span></dt>
<dd>
<section>
<label class="input">
<i class="icon-append fa fa-inbox"></i>
<input type="text" value="" name="name" required>
<b class="tooltip tooltip-bottom-right">Add New Record</b>
</label>
</section>
</dd>
</dl>
<hr>
<button type="submit" class="btn-u" style="float:right; margin-top:-5px;">Submit</button>
</form>
</div>
</div>
</div>
Ajax script :
$(document).ready(function(){
$("#sky-inchidere").submit(function(e){
e.preventDefault();
var tdata= $("#sky-inchidere").serializeArray();
$.ajax({
type: "POST",
url: 'http://localhost/new/oportunitati/add',
data: tdata,
success:function(tdata)
{
alert('SUCCESS!!');
},
error: function (XHR, status, response) {
alert('fail');
}
});
});
});
CI Controller ( i have added the modal code here for test )
public function add() {
$tdata = array( name=> $this->input->post(name),
);
$this->db->insert('table',$tdata);
}
When i use this code i get "fail" error message.
Thanks for your time.
how yo debug:
1. Print your 'tdata' and see what happen;
2. Something wrong here: $this->input->post('name');
Try to use:
$tdata = array(
'name' => $this->input->post('name')
);
I manage to find the problem and correct it. (typo on the table name)
Now I have come across a different problem. In the ajax success I cant refresh the chosen dropdown records i have tried :
success:function(tdata)
{
// close the modal
$('#myModal').modal('hide');
// update dropdown ??
$('.chosen-select').trigger('liszt:updated');
$('#field-beneficiar_p').trigger('chosen:updated');
$('#field-beneficiar_p').trigger('liszt:updated');
},
Any help in how i can refresh the records to see the last added item will be appreciated. I'm using chosen plugin.
from controller send data in json_encode
then in js function
$.ajax({
type: "POST",
url: "<?php echo base_url('login/get_time'); ?>",
data: {"consltant_name": consltant_name, "time": time},
success: function(data) {
var data = JSON.parse(data);
var options = '';
options = options + '<option value="">Please Select One</option>'
$.each(data, function(i, item) {
options = options + '<option value="' + item + '">' + item + '</option>'
});
selectbox.html(options);
}});

kendo crud listview change model value after insert

Here is my code.
$(document).ready(function() {
var kendoWindow_room = $("#window_room");
kendoWindow_room.hide();
$("#roombut").on(
'click',
function()
{
home_id = $("#home_id").val();
if (home_id) {
kendoWindow_room.data("kendoWindow").open();
$('.k-window').css({'marginLeft': -$('.k-window').width() / 2});
dataSource.read();
$("#room_listview_pager .k-link:first").hide();
$("#room_listview_pager .k-link:last").hide();
$("#room_listview_pager a.k-link").each(function(index) {
$(this).addClass("pager_new_icons");
$(this).addClass("mortgage");
});
}
}
);
home_datasource = new kendo.data.DataSource({
transport: {
read: {
url: "<?php echo BASE_URL . 'user/get_edit_home_name' ?>",
dataType: "json"
}
}
});
room_datasource = new kendo.data.DataSource({
transport: {
read: {
url: "<?php echo BASE_URL . 'common/get_dropdown_entries' ?>",
dataType: "json",
data: {thisisfor: "floortype"}
}
}
});
var crudServiceBaseUrl = "<?php echo BASE_URL . 'user/room_crud_listview_' ?>",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: function() {
return crudServiceBaseUrl + "read?home_id=" + $("#home_id").val()
},
dataType: "json",
contentType: "application/json"
},
update: {
url: crudServiceBaseUrl + "update",
dataType: "json",
type: "POST"
},
destroy: {
url: crudServiceBaseUrl + "destroy",
dataType: "json",
type: "POST"
},
create: {
url: crudServiceBaseUrl + "create",
dataType: "json",
type: "POST"
}
},
batch: true,
pageSize: 1,
schema: {
model: {
id: "id",
fields: {
rd_home_id: "rd_home_id",
homename: "homename",
nickname: "nickname",
type: "type",
wallcolor: "wallcolor",
trimcolor: "trimcolor",
floorcolor: "floorcolor",
floortype: "floortype",
windows: "windows"
}
}
}
});
$("#room_listview_pager").kendoPager({
dataSource: dataSource,
info: false,
numeric: false
});
var room_listview = $("#room_listview").kendoListView({
dataSource: dataSource,
template: kendo.template($("#room_listview_template").html()),
editTemplate: kendo.template($("#room_editview_template").html())
}).data("kendoListView");
// Add Row
$("#room_add_row").on("click", function(event) {
event.preventDefault();
room_listview.add();
});
// Delete Row
$("#room_delete_row").on("click", function(event) {
event.preventDefault();
room_listview.remove(room_listview.element.children().first());
if (dataSource.total() < 1) {
room_listview.add();
} else {
dataSource.read();
}
});
// edit row
$("#room_edit_row").on("click", function(event) {
event.preventDefault();
room_listview.edit(room_listview.element.children().first());
});
// save row
$("#room_save_row").on("click", function(event) {
event.preventDefault();
room_listview.save();
});
if (!kendoWindow_room.data("kendoWindow")) {
kendoWindow_room.kendoWindow({
width: "520px",
title: "Room Designer"
});
}
});
<div style="background-color: #FFFFFF; border: 0; max-width: 90px; float: left;" id="room_listview_pager"></div>
<span style="float: right; margin-top: 4px;">
<a id="room_add_row" class="k-add" href="#"><img src="<?php echo STATIC_DIR; ?>images/icon7.png" alt="" height="36" width="37"></a>
<a id="room_delete_row" class="k-delete" href="#"><img src="<?php echo STATIC_DIR; ?>images/icon8.png" alt="" height="36" width="37"></a>
<a id="room_edit_row" class="k-edit" href="#"><img src="<?php echo STATIC_DIR; ?>images/icon9.png" alt="" height="36" width="37"></a>
<a id="room_save_row" class="k-insert" href="#"><img src="<?php echo STATIC_DIR; ?>images/icon10.png" alt="" height="36" width="37"></a>
</span><div class="clear"></div>
This is the kendo template with id - "room_listview_template"
<div class="product-view k-widget">
<dl>
<dt>Home</dt>
<dd>#:homename#</dd>
<dt>Nickname</dt>
<dd>#:nickname#</dd>
<dt>Type</dt>
<dd>#:type#</dd>
<dt>Wall Color</dt>
<dd>#:wallcolor#</dd>
<dt>Trim Color</dt>
<dd>#:trimcolor#</dd>
<dt>Floor Color</dt>
<dd>#:floorcolor#</dd>
<dt>Floor Type</dt>
<dd>#:floortype#</dd>
<dt>Windows</dt>
<dd>#:windows#</dd>
</dl>
</div>
This is the kendo template with id - "room_editview_template"
<div class="product-view k-widget">
<dl>
<dt>Home</dt>
<dd>
<select id="home"
data-role="dropdownlist"
data-text-field="nickname"
data-value-field="id"
data-source="home_datasource"
data-bind="value:rd_home_id"
name="rd_home_id"
required="required"
validationMessage="required">
</select>
<span data-for="rd_home_id" class="k-invalid-msg"></span>
</dd>
<dt>Nickname</dt>
<dd>
<input type="text" class="k-textbox" data-bind="value:nickname" name="nickname" required="required" validationMessage="required" />
<span data-for="nickname" class="k-invalid-msg"></span>
</dd>
<dt>Type</dt>
<dd>
<input type="text" class="k-textbox" data-bind="value:type" name="type" required="required" min="1" validationMessage="required" />
<span data-for="type" class="k-invalid-msg"></span>
</dd>
<dt>Wall Color</dt>
<dd>
<input type="text" class="k-textbox" data-bind="value:wallcolor" name="wallcolor" required="required" validationMessage="required" />
<span data-for="wallcolor" class="k-invalid-msg"></span>
</dd>
<dt>Trim Color</dt>
<dd>
<input type="text" class="k-textbox" data-bind="value:trimcolor" name="trimcolor" required="required" validationMessage="required" />
<span data-for="trimcolor" class="k-invalid-msg"></span>
</dd>
<dt>Floor Color</dt>
<dd>
<input type="text" class="k-textbox" data-bind="value:floorcolor" name="floorcolor" required="required" validationMessage="required" />
<span data-for="floorcolor" class="k-invalid-msg"></span>
</dd>
<dt>Floor Type</dt>
<dd>
<select
data-role="dropdownlist"
data-text-field="name"
data-value-field="value"
data-source="room_datasource"
data-bind="value:floortype"
name="floortype"
required="required"
validationMessage="required">
</select>
<span data-for="floortype" class="k-invalid-msg"></span>
</dd>
<dt>Windows</dt>
<dd>
<input type="text" class="k-textbox" data-bind="value:windows" name="windows" required="required" validationMessage="required" />
<span data-for="windows" class="k-invalid-msg"></span>
</dd>
</dl>
</div>
I have a listview inside a kendowindow with options to create, read, update and delete.
It uses one template to list the records and another template to edit.
In the fields, I have a dropdown list, with the field name "rd_home_id" its data-text-field and data-value-field are different. It displays home name in as the option and each option has its integer value.
The insert, and update is working fine, I get the integer value in the server side.
While reading, obviously I would like to display the home name - so, I have the field name "homename" - and from the server, I pass this value and I am able to see it in the listing template - which works perfectly fine.
The only problem remaining is - after I insert a record, the "homename" is not showing up - its null - all the other values are showing up and is correct.
How could I show the value "homename" right after the insert?
I know I can call the call the read function of the datasource in the room_save_row's onclick right after calling the save function of the listview - which would fix the issue, but doing that would make the validation not work.
Is there any way to change the value of the fields which is rendered in the template?
Thank you
Just solved the problem
If the inserted record is sent as a response from the server ( from the create URL ) - it would get updated - and the value would be reflected in the listing template - before I was not sending anything from the server. that was the problem.

Resources