How to alert the data-id attribute value in laravel? - javascript

Ajax1:
<script type="text/javascript">
$(document).ready(function () {
$('.CategoryName').click(function() {
var categoryName = $(this).attr("data-id");
var url="{{url('getSubCategoryName/').'/'}}" + categoryName;
$.ajax({
url : url,
type: 'GET',
dataType:'json',
success:function(data){
$.each(data, function( index, value ) {
var output = '';
output = ' ' + value.subCategoryName + '';
**$(".subcategory").append('<ul><li data-
id="'+value.subCategoryName+'" class="getDeviceCategoryName">'+value.subCategoryName+'</li></ul>')**
});
}
});
});
});
</script>
The code which is marked in bold has the value for data-id attribute..And I need to pass that value when class named getDeviceCategoryName is clicked.
AJAX2:
<script type="text/javascript">
$(document).ready(function () {
$('.getDeviceCategoryName').click(function() {
var subCategoryName = $(this).attr("data-id");
alert(subCategoryName);
});
});
</script>
This is one I tried for that..But its not working.It doesnot alerts or shows any error.

You should consider jquery event delegation:
Change your jquery selector line like this:
<script type="text/javascript">
$(document).ready(function () {
$(document).on('click','.getDeviceCategoryName',function() {
var subCategoryName = $(this).attr("data-id");
alert(subCategoryName);
});
});
</script>

Here you go with a solution
$(document).ready(function () {
$(document).on('click', 'li.getDeviceCategoryName', function() {
console.log($(this).data("id"));
});
});
Since the elements are generated dynamically, so you need to delegate events.
For receiving the data-attribute you can do $(this).data("attribute-name"); in your scenario it will be $(this).data('id');
Hope this will help you.

Personally I think code is more efficient if the click event is applied to the element right after it's created.
$(function () {
$('.CategoryName').click(function () {
var categoryName = $(this).attr('data-id');
var url = '{{url(\'getSubCategoryName/\').\'/\'}}' + categoryName;
$.ajax({
url: url,
type: 'GET',
dataType: 'json',
success: function (data) {
$.each(data, function (index, value) {
var output = '';
output = ' ' + value.subCategoryName + '';
$('.subcategory').append($('<ul/>').append('<li data-id="' + value.subCategoryName + '" class="getDeviceCategoryName">' + value.subCategoryName + '</li>')
.find('li')
.click(function () {
var subCategoryName = $(this).attr('data-id');
alert(subCategoryName);
});
);
});
}
});
});
});

$(document).ready(function () {
$(document).on('click', '.getDeviceCategoryName', function(){
var subCategoryName = $(this).attr("data-id");
alert(subCategoryName);
});
});

Related

How to stop blur() event function to trigger twice?

I am trying to fetch the records from the database using blur function. There are two input fields where this function triggers. I have used different names, variables, javascript, controller using laravel to fetch the records. I am able to fetch the records through ajax and successfully opens the modal. When the modal pop ups when the blur function triggers, it also triggers the function for the second field.
I just want to trigger the modal according to the field, where the blur triggers and not to trigger twice.
//input field: originS
<script type="text/javascript">
$(document).ready(function(){
var origin = "";
var _token = "";
var ovalue = "";
$('#originS').blur(function(){
ovalue = "";
origin = $(this).val();
_token = $('input[name="_token"]').val();
$.ajax({
type: 'POST',
url: '{{ route('pagescontroller.fetchOrigin') }}',
data:{origin:origin, _token:_token},
success: function(response){
if(response){
$("#originSelect").modal('show');
console.log(response);
$(".result").html(response);
$(document).on('change', '#selectSuburb', function () {
ovalue = $(this).val();
if ($(this).is(':checked')) {
$('#originS').val(ovalue);
$("#originSelect").modal('hide');
$this.die('blur');
}
});
$('#originSelect').on('hidden.bs.modal', function (e) {
if (ovalue == "") {
$("#originS").val('');
$(".result").html(response);
}
});
}
},
});
});
});
</script>
//input field: destS
</script>
<script type="text/javascript">
$(document).ready(function(){
var dest = "";
var _token = "";
var dvalue = "";
$('#destS').blur(function(){
dvalue = "";
dest = $(this).val();
_token = $('input[name="_token"]').val();
$.ajax({
type: 'POST',
url: '{{ route('pagescontroller.fetchdest') }}',
data:{dest:dest, _token:_token},
success: function(response){
if(response){
$("#destSelect").modal('show');
console.log(response);
$(".dresult").html(response);
$(document).on('change', '#selectSuburbdest', function () {
dvalue = $(this).val();
if ($(this).is(':checked')) {
$('#destS').val(dvalue);
$("#destSelect").modal('hide');
$this.die('blur');
}
});
$('#destSelect').on('hidden.bs.modal', function (e) {
if (dvalue == "") {
$("#destS").val('');
$(".dresult").html(response);
}
});
}
},
});
});
});
</script>

Alert on DIV refresh with new website

I want to get an alert once the DIV is refreshed with the new Information/Website
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
function changeURL(){
var URL2add = "http://google.com";
var user="1";
$.ajax({
url: 'myApi.php?user=' + user + '&url='+ URL2add,
success: function(html) {
var newHTML = "<object id='webloader' data='" + html + "'></object>";
$("#exweb").fadeOut(5, function () {
$("#exweb").html(newHTML).fadeIn(50);
// alert("done");
});
}
});
}
</script>
the way i have it now the alert pops up Before the Div is refreshed
You can use the complete action of fadeOut() function similar to what you are doing for fadeIn(). In your above code, you can simply do it like this-
$.ajax({
url: 'myApi.php?user=' + user + '&url='+ URL2add,
success: function(html) {
var newHTML = "<object id='webloader' data='" + html + "'></object>";
$("#exweb").fadeOut(500, function () {
$("#exweb").html(newHTML).fadeIn(5000, function() {
alert("done");
});
});
}
});
Another example with working fiddle here - https://jsfiddle.net/gug08249/

Jquery onchange Ajax

i made a function that sends data (ajax) to the database and depending on the response from the server i need to alert a message but it seems like whenvever i change the select option i get the alert message for each change(if i change the select four times when i click i get the alert four times ) , but if i remove my ajax function and replace it simply by an alert i get it once not repeating itself here is my JS
$('.select_ids').change(function () {
var id = $(this).val();
var form = $('#form_widget_ids_' + id);
var container = form.parent('.ewb_forms');
var box = container.parent('.edit_widget_box');
container.children('.selected').fadeOut(300, function () {
$(this).removeClass('selected');
form.fadeIn(300, function () {
$(this).addClass('selected');
});
});
Widget.updateSSOUrl(box);
$.ajax({
type: "POST",
url: window.location + "",
data: {'id': id}
}).done(function (msg) {
$(".red").on('click', function (evt) {
if ('done' == msg) {
evt.preventDefault();
alert('NOP');
}
})
});
});
the event that you are binding i think is wrong. For newly append items is better in your case to use
$(document).on('click', ".red", function (evt) {
})
And it must be moved outside the ajax success because now you are triggering it every time
----- Edited ---
If you want just to alert the output of the ajax you dont need the onClick event
$('.select_ids').change(function () {
var id = $(this).val();
var form = $('#form_widget_ids_' + id);
var container = form.parent('.ewb_forms');
var box = container.parent('.edit_widget_box');
container.children('.selected').fadeOut(300, function () {
$(this).removeClass('selected');
form.fadeIn(300, function () {
$(this).addClass('selected');
});
});
Widget.updateSSOUrl(box);
$.ajax({
type: "POST",
url: window.location + "",
data: {'id': id}
}).done(function (msg) {
if (msg === 'done') {
evt.preventDefault();
alert('NOP');
}
});
});
If you want to show the latest result on a button click you can store the msg on a global variable and on click of a div show that like
var globalMsg = "";
$('.select_ids').change(function () {
var id = $(this).val();
var form = $('#form_widget_ids_' + id);
var container = form.parent('.ewb_forms');
var box = container.parent('.edit_widget_box');
container.children('.selected').fadeOut(300, function () {
$(this).removeClass('selected');
form.fadeIn(300, function () {
$(this).addClass('selected');
});
});
Widget.updateSSOUrl(box);
$.ajax({
type: "POST",
url: window.location + "",
data: {'id': id}
}).done(function (msg) {
globalMsg = msg
});
});
$(".div").click(function() { alert(globalMSG); });

AJAX - Javascript is breaking whenever the AJAX script is called

I hired a developer to help with some work, he was mostly PHP focused and attempted this javascript. The following AJAX script breaks the page whenever it reloads the HTML into the DOM. It called a function via Codenigniter to reload the view within the page. Once this happens, all of the javascript no longer works.
I can't seem to find a solution that helps solve this issue. Please help.
Note: Ideally I would of rather the code only loaded the data and not refresh the HTML, but for now this will need to do as I am up against a timeline.
The code:
$(document).ready(function () {
// Ajax Form Submit
$('body').on('click', '.submitForm', function () {
var formid = $(this).parents('form').attr('id');
var validationResult = $('#' + formid).validationEngine('validate');
if (!validationResult) {
return false;
}
var url = $('#' + formid).attr('action');
var formdata = $('#' + formid).serialize();
if ($('#' + formid).find('.submitForm').hasClass('loading')) {
$(this).hide();
$('#' + formid).find('.loader').show();
}
$.ajax({
type: "POST",
cache: false,
url: url,
data: formdata,
dataType: 'json',
success: function (data) {
if ($('#' + formid).find('.submitForm').hasClass('loading')) {
$('#' + formid).find('.submitForm').css('display', 'inline');
$('#' + formid).find('.loader').hide();
}
if (data.type == 'add') {
if (data.html) {
var newhtml = "<tr>" + data.html + "</tr>";
$('.tab-pane.active table').append(newhtml);
}
$('#' + formid).find('.message').html(data.msg).show();
$('#' + formid).trigger('reset');
setInterval(function () {
$('#' + formid).find('.message').hide();
}, 5000);
} else {
if (data.error) {
$('#' + formid + ' .message').show().html(data.error);
} else {
$('#' + formid + ' .message').show().html(data.msg);
if (data.reload_loc) {
window.setTimeout(function () {
window.location.href = data.reload_loc;
}, 4 * 1000);
}
}
}
}
});
});
// Generic Save Form Data
$('body').on('click', '#saveFormdata', function () {
var formid = $(this).parents('form').attr('id');
var validationResult = $('#' + formid).validationEngine('validate');
if (!validationResult) {
return false;
}
$('#' + formid).submit();
});
});
You just do something like this:
function bindEvent()
{
$('body').on('click', '.submitForm', function () { //Your code });
$('body').on('click', '#saveFormdata', function () { //Your code});
}
function unblindEvent()
{
$('body').off('click', '.submitForm'); //Something like this, please read Jquery.off
$('body').off('click', '#saveFormdata');
}
Before you replace these element, call unblindEvent(). And after you replace these elements call bindEvent().

Event.preventDefault() and check boxes in form?

I have a form being sent over ajax with event.preventdefault on it so it doesn't send automatically but this then stops the check boxes from functioning...
How do I get around this...
JSfiddle
$('[name="id"]').each(function (index, el) {
var getval = $(this).val();
console.log(getval);
$('#form_pub_priv_' + getval).on('click', function (event) {
event.preventDefault();
var arr_unchecked_values = $('input[type=checkbox]:not(:checked)').map(function () {
return this.value;
}).get();
var formvalues = $('#form_pub_priv_' + getval + ' [name="id"]').serialize();
var dataJoin = '&mod=' + arr_unchecked_values + '&' + formvalues;
console.log(dataJoin);
$.ajax({
url: 'unpublish-Lyst.html',
type: 'POST',
data: dataJoin
})
.done(function (data) {
console.log(data);
})
.fail(function () {
console.log("error");
})
.always(function () {
console.log("complete");
});
});
});
You're stopping the click event indirectly in your checkboxes, that's why your checkboxes don't work.
$('#form_pub_priv_' + getval).on('click', function (event) {
event.preventDefault(); //Remove this!
var arr_unchecked_values = ...
To prevent the form from being submited, you should do it in tye submit form event.
$('#form_pub_priv_' + getval).submit(function(event){
...
event.preventDefault(); //Here it's ok
});
Cheers

Categories

Resources