How to access id of the modal globally using JavaScript Laravel Laravel - javascript

I'm have an html table with modal column (see image below for your reference)
Upon click the Order modal, I can access the its ID using onclick event in JavaScript
(var customer_id = $(this).val();)
I wanted to access and used it in my Add function using ajax but I'm having an error of "customer_id is not defined" when I tried to use it. Is there a way to fix it or do it properly.
This is my script
<script>
$(document).ready(function () {
// START OPEN CART MODAL FUNCTION
$(document).on('click', '.viewCart', function (e) {
e.preventDefault();
var customer_id = 0;
var customer_id = $(this).val();
console.log(customer_id);
$.ajax({
type: "GET",
url: "/get-cart/"+customer_id,
dataType: "json",
success: function (response) {
if (response.data != null) {
console.log(response);
$('.OrderTbody').html("");
$.each(response.data, function (key, item) {
$('.OrderTbody').append('<tr>\
<td>' + item.p_name + '</td>\
<td>' + item.c_qty + '</td>\
<td class="total">' + item.p_amt + '</td>\
<td><button type="button" value="' + item.c_id + '" class="btn btn-danger deleteListBtn btn-sm">Delete</button></td>\
\</tr>');
});
}
}
});
});
// END OPEN CART MODAL FUNCTION
// START ADD DATA FUNCTION
$(document).on('click', '.addToCart', function (e) {
e.preventDefault();
var data = {
'store': $('.sel_store').val(),
'product': $('.sel_product').val(),
'quantity': $('.sel_qty').val(),
// HOW TO INPUT Customer ID here, I tried this but im having an error of
// customer_id is not defined
'customer_id': customer_id,
}
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: "/cart-list",
data: data,
dataType: "json",
success: function (response) {
}
});
});
// END ADD DATA FUNCTION
});
</script>

Related

Consume REST Service with Javascript/HTML

Below is code I use to get data from a SharePoint List with Javascript. What would I need to do to get it work on a site like JS Bin or JS Fiddle with an open/free REST service? (Like iextrading.com?)
<script type="text/javascript">
function getCompanies () {
var call = $.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Bills')/items?$select=AccountNumber&$orderby=AccountNumber&$filter=(PackageID eq '" + pid + "')",
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
});
call.success(function (data,textStatus, jqXHR){
$("#ResultsDiv").empty();
for (var i = 0; i < data.d.results.length; i++)
{
var item = data.d.results[i];
$("#ResultsDiv").append(item.AccountNumber + "<br/>");
}
});
call.fail(function (jqXHR,textStatus,errorThrown){
alert("Error retrieving Account Numbers: " + jqXHR.responseText);
});
}
</script>
<button onclick="getCompanies(); return false;" type="button">Get Item</button>
<hr width="50px" />
<div id="ResultsDiv"></div>
I looked at several examples on SO, but I couldn't get them to work on JS Bin or JS Fiddle.
I guess I worded my question poorly, because my original code was close to the answer.
function getMovies () {
var call = $.ajax({
url: "https://www.omdbapi.com/?i=tt3896198&apikey=[yourKeyHere]",
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
});
call.success(function (data,textStatus, jqXHR){
$("#ResultsDiv").empty();
$("#ResultsDiv").append(data.Title);
});
call.fail(function (jqXHR,textStatus,errorThrown){
alert("Error retrieving data: " + jqXHR.responseText);
});
}

Phonegap/Cordova - on("click") not firing

I'm creating a phonegap app.
This code is going to get by a json, the content on de database. Then I want to insert in the database the vote with the device.uuid. The problem is that the on("click") or on("touchstart") is not firing, not even in the alert(). Please help!!
$(document).ready(function() {
var url = "http://filmpix.esy.es/json.php";
$.getJSON(url, function(result) {
console.log(result);
$.each(result, function(i, field) {
var id = field.id;
$('.music-box').append("<button class='btn btn-default insert' value='" + id + "'>Votar</button>");
});
});
$(".insert").on("touchstart", function() {
alert("asdasd");
var music_id = $(this).val();
var dataString = "music_id=" + music_id;
$.ajax({
type: "POST",
url: "http://filmpix.esy.es/insert.php",
data: dataString,
crossDomain: true,
cache: false,
beforeSend: function() {
$("#insert").val('A votar...');
confirm("Tens a certeza que queres votar nesta musica?");
},
success: function(data) {
if (data == "success") {
alert("inserted");
$("#insert").val('Votado');
} else if (data == "error") {
alert("Não foi possível votar");
}
}
});
return false;
});
});
The return false statement should come after the function's "}" on your touch event.

Handling of click events in jQuery(For Like and Unlike button)

I am trying to create a Like-Unlike system using AJAX and jQuery. The "like" event seems to work properly, but when I want to "unlike" the event is not responding. Any suggestions to solve this problem is appreciated.
$(document).ready(function() {
$(".like").click(function() { //this part is working
var item_id = $(this).attr("id");
var dataString = 'item_id=' + item_id;
$('a#' + item_id).removeClass('like');
$('a#' + item_id).html('<img src="images/loader.gif" class="loading" />');
$.ajax({
type: "POST",
url: "ajax.php",
data: dataString,
cache: false,
success: function(data) {
if (data == 0) {
alert('you have liked this quote before');
} else {
$('a#' + item_id).addClass('liked');
$('a#' + item_id).html(data);
}
}
});
});
$(".liked").click(function() { //this part is not working
var item_id = $(this).attr("id");
console.log(item_id);
var dataString = 'item_id=' + item_id;
$('a#' + item_id).removeClass('liked');
$('a#' + item_id).html('<img src="images/loader.gif" class="loading" />');
$.ajax({
type: "POST",
url: "ajax.php",
data: dataString,
cache: false,
success: function(data) {
if (data == 0) {
alert('you have liked this quote before');
} else {
$('a#' + item_id).addClass('like');
$('a#' + item_id).html(data);
}
}
});
});
});
$(".like") and $(".liked") are retrieved when the document is ready but don't get updated when you add/remove classes from an element.
If you assign a more generic class the vote elements like 'like-toggle' you would be able to do the following:
$(document).ready(function() {
$('.like-toggle').click(function(event) {
if ($(event.target).hasClass('like') {
// Call your unlike code, replace like with liked.
} else {
// Call your like code, replace liked with like.
}
});
});
This will work because the like-toggle class never gets removed from the elements and thus the elements which are present when the document is ready will keep functioning.

Running jquery function after one function is executed

I am adding some comments with AJAX and get return formatted HTML and adding it to HTML with DOM manipulation,
jQuery.ajax({
url: baseURL + "index.php/user/news/add_comment",
data: $("#comment_fm").serialize(),
type: "POST",
success: function(data) {
var objData = jQuery.parseJSON(data);
if (objData.cival == 1) //Success..
{
$("#comment").val('');
$("#comment_box").replaceWith(objData.comment);
$("#commentcounts").replaceWith(objData.commentcounts);
}
} // Success End
}); //AJAX End
With above code i can see my comments are added,
Now in same return formatted HTML, there is delete button which have JS function associated,
Below is delete JS,
function deletecomment(commentid) {
jQuery.ajax({
url: baseURL + "index.php/user/news/deletecomment",
data: {
comment_id: commentid
},
type: "POST",
success: function(data) {
var objData = jQuery.parseJSON(data);
if (objData.cival == 1) {
$("#commentcounts").replaceWith(objData.commentcounts);
$("#commentbox" + commentid).remove();
}
}
});
}
Below is my delete button which fire to function deletecomment()
<i class="fa fa-trash text-info"></i>
But my problem is that i can not delete this comment just after adding function is run,
If i refresh page, then delete function works a needed,
So question is, how to make multiple function work without reloading page?
Thanks in advance,
I would suggest you to try as below:
<a class="deleteComment" data-id="<?php echo $comment['comment_id'];?>" href="#"><i class="fa fa-trash text-info"></i></a>
Your JS would be:
$(document).on('click','.deleteComment',function(){
jQuery.ajax({
url: baseURL + "index.php/user/news/deletecomment",
data: {
comment_id: $(this).data('id');
},
type: "POST",
success: function(data) {
var objData = jQuery.parseJSON(data);
if (objData.cival == 1) {
$("#commentcounts").replaceWith(objData.commentcounts);
$("#commentbox" + commentid).remove();
}
}
});
});

Json data in a next and previous button

I have to use a AJAX call to get Json data after clicking next and previous buttons. Json data should contain blog content displayed after clicking next or previous. Any suggestions how my function should look like? So far I have only:
function getPrev() {
$.ajax({
type: "GET",
url: "../Content/test.txt",
dataType: "json"
}).success(function (data) {
$.each(data, function (key, val) {
$('#blogcont').append(key+ val);
});
return false;
});
}
And my Json file is only a test file:
{"one":"test1", "two":"test2", "three":"test3" }
Sorry I am a beginner!!!!
Thanks
Your $.ajax() syntax is incorrect
function getPrev() {
$.ajax({
type: "GET",
url: "../Content/test.txt",
dataType: "json",
success: function(data) {
var content = "";
$.each(data, function(key, val) {
content += "<p>" + key + ":" + val + "</p>";
});
$('#blogcont').html(content);
}
});
return false;
}
or
function getPrev() {
$.ajax({
type: "GET",
url: "../Content/test.txt",
dataType: "json"
}).done(function(data) {
var content = "";
$.each(data, function(key, val) {
content += "<p>" + key + ":" + val + "</p>";
});
$('#blogcont').html(content);
});
return false;
}
Try this
function getPrev() {
$.ajax({
type: "GET",
url: "../Content/test.txt",
dataType: "json"
}).done(function(data) {
var content = "";
$.each(data, function(key, val) {
content += '<p>' + key + ':' + val + '</p>';
});
$('#blogcont').html(content)
.find('p')
.hide()
.first().show();
$('button.next').click(function() {
$('#blogcont').find('p:visible')
.hide()
.next('p').show();
});
});
return false;
}
How about storing the JSON data as a variable, which you can then access using an index on click?
var jsonData;
$.ajax({
type: "GET",
url: "../Content/test.txt",
dataType: "json",
success: function (data) {
jsonData= data;
}
});
var clickIndex = 0;
$('.prev').click(function() {
if(clickIndex > 0) {
clickIndex -= 1;
}
get(clickIndex);
});
$('.next').click(function() {
clickIndex++;
get(clickIndex);
});
Your get function would then accept the index and find the JSON property:
function get(i) {
var item = jsonData[i];
}
Note that you would need to add an if statement to check whether you have reached the index limit on click of .next. Also, this is fine for a test JSON file, but a better solution would be to be able to request just one relevant item from a web service returning the JSON.

Categories

Resources