AJax Submit onclick Font Awesome Icon - javascript

I am trying to display a simple rating option on a website, a thumbs up & down that when clicked will send the response to my external URL.
The site will be displayed on mobile devices as well as desktops (that's why i'm using touchstart and click).
I need to post the following values to my external URL;
date
time
feedback (good / bad)
I'm successfully receive the date and time, but not feedback type. Looking at the console I can see the following;
My code is as follows;
HTML
<form id="kioskFeedback">
<i class="fa fa-thumbs-o-up fa-4x"></i>
<i class="fa fa-thumbs-o-down fa-4x"></i>
</form>
AJAX
$(document).ready(function() {
var today = new Date();
var date = today.getDate() + '/' + (today.getMonth() + 1) + '/' + today.getFullYear();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
$("#kioskFeedback").on("touchstart, click", function(e) {
event.preventDefault();
var serializedData = $(this).serialize();
$.ajax({
url: "my external url here",
type: "post",
data: serializedData + '&Date=' + date + '&Time=' + time
});
.done(function(response, textStatus, jqXHR) {
console.log('success');
});
});
});

Expanding on #ADyson's comment, look at the docs for $.serialize() http://api.jquery.com/serialize/
To Make what you have work...
Change this var serializedData = $(this).serialize();
to this var serializedData = $(this).attr('value');
That should get you started. Once you read the documentation and understand that <a></a> elements are not form elements and the $.serialize() method will not return the expected results you may want to go back and update the rest of the click handler to use a different variable name like so,
$("#kioskFeedback a").on("touchstart, click", function(e) {
e.preventDefault();
var feedbackVal = $(this).attr('value');
$.ajax({
url: "my external url here",
type: "post",
data: {
// If the script is expecting "Feedback" swap in place of "value"
value: feedbackVal,
Date: date,
Time: time
}
});
.done(function(response, textStatus, jqXHR) {
console.log('success');
});
});
Also you should change event.preventDefault(); to e.preventDefault() seeing that your event information is being passed as e and not event.
Your target needs to get updated also, so adding an a to $("#kioskFeedback")
like this $("#kioskFeedback a") will shrink the scope to the link element. Allowing you to get the attribute value.
I am also attaching a working fiddle.
$("#kioskFeedback a").on("touchstart, click", function(e) {
e.preventDefault();
var feedbackVal = $(this).attr('value');
console.log(feedbackVal);
/* $.ajax({
url: "my external url here",
type: "post",
data: {
// If the script is expecting "Feedback" swap in place of "value"
value: feedbackVal,
Date: date,
Time: time
}
});
.done(function(response, textStatus, jqXHR) {
console.log('success');
}); */
});
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="kioskFeedback">
<i class="fa fa-thumbs-o-up fa-4x"></i>
<i class="fa fa-thumbs-o-down fa-4x"></i>
</form>

Related

Jquery complementary functions not working as desired

I have two complementary functions, one that publishes a post, and one that unpublishes a post when the user clicks the same button (the button is acting as a toggle). If the post is not published and the user goes to publish it everything works as it is supposed to, however if the user decides to unpublish it again the function to publish is erroneously called again. I am using class selectors to accomplish this. So publish does its business and then sets the class to unpublish so that when the user clicks the button unpublish gets called (which doesn't happen).
I have verified that publish gets the class unpublish after being called, and vise versa but the complementary function never gets called despite having its class changed in the final lines. Console.log shows that publish keeps getting called.
What am I doing wrong?
$('a.publish').on('click', function(e) {
console.log('publish item');
var id = $(this).attr('data-id');
var table = $(this).attr('rel');
var parent = $(this).closest('.btn-group');
var current = $(this).closest('a');
$.ajax({
type: 'POST',
url: '',
data: 'publish=' + id + '&table=' + table,
success: function(data) {
$('#published_' + id).hide().html(data).fadeIn();
count(table);
var buttons = parent.find(".btn-danger");
buttons.each(function() {
$(this).removeClass("btn-danger").addClass("btn-primary");
});
current.find('span').text('Unpublish');
current.removeClass("publish").addClass("unpublish");
}
});
e.preventDefault();
});
$('a.unpublish').on('click', function(e) {
console.log('unpublish item');
var id = $(this).attr('data-id');
var table = $(this).attr('rel');
var parent = $(this).closest('.btn-group');
var current = $(this).closest('a');
$.ajax({
type: 'POST',
url: '',
data: 'unpublish=' + id + '&table=' + table,
success: function(data) {
$('#published_' + id).hide().html(data).fadeIn();
count(table);
var buttons = parent.find(".btn-primary");
buttons.each(function() {
$(this).removeClass("btn-primary").addClass("btn-danger");
});
current.find('span').text('Publish');
current.removeClass("unpublish").addClass("publish");
}
});
e.preventDefault();
});
If this has to do with DOM or something, how can I subvert it?
HTML:
<a class="btn btn-sm btn-primary unpublish" href="javascript:void(0);" data-id="213114246" rel="projects">
<i class="glyphicon glyphicon-plus"></i>
<span class="actions">Unpublish</span>
</a>
$('.btn-container').on('click', '.btn', function(e) {
if ($(this).hasClass('publish')) {
console.log('publish item');
$(this).removeClass("publish").addClass("unpublish").text('unpublish');
} else {
console.log('unpublish item');
$(this).removeClass("unpublish").addClass("publish").text('publish');
}
e.preventDefault();
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="btn-container">
<a class="btn btn-sm btn-primary unpublish">unpublish</a>
</div>

Large amount of events loaded on the angularjs-bootstrap-calendar

I'm pulling in ALL my event data from my server and since I have a lot of events to pull, the angular-bootstrap-calendar takes a lot of time to load.
I was wondering if its possible to pull only a month's worth of data for the current view I'm in (month, week, day..I would hide the year view). As I change the view to the next month, I'd pull the data for that month only.
Right now, I pull ALL the data only once, when the calendar loads, but not sure how to pull the data when the view changes.
var urlapievents = $location.protocol() + "://" + $location.host() + "/api/events/" ;
$http.get(urlapievents).success(function(events) {
Good solution for me
Get year and month of view, send it to API, and only retrieve events for that year-month:
js
vm.viewChangeClicked = function() {
var viewDateYearMonth = moment(vm.viewDate).format('YYYY-MM');
var urlapieventsall = $location.protocol() + "://" + $location.host() + "/api/events/" + viewDateYearMonth ;
$http.get(urlapieventsall).success(function(events) {
vm.events = events.events;
});
};
html
<div class="col-md-6 text-center">
<div class="btn-group">
<label class="btn btn-primary" ng-model="vm.calendarView" uib-btn-radio="'month'" ng-click="vm.cellIsOpen = false; vm.viewChangeClicked()">Month</label>
<label class="btn btn-primary" ng-model="vm.calendarView" uib-btn-radio="'week'" ng-click="vm.cellIsOpen = false; vm.viewChangeClicked()">Week</label>
<label class="btn btn-primary" ng-model="vm.calendarView" uib-btn-radio="'day'" ng-click="vm.cellIsOpen = false; vm.viewChangeClicked()">Day</label>
</div>
</div>
I've also added logic to check if previous yyyy-mm is equal to current yyyy-mm to save some unnecessary calls to the API.
If you grab your events as a json feed, you can use additional options - startParam and endParam. They can be used like this:
$('#calendar').fullCalendar({
events: function(start, end, timezone, callback) {
if (request) {
request.abort();
};
$.mobile.loading('show');
request = $.ajax({
type: "POST",
url: "../Services/Calendar/CalendarService.asmx/GetEvents",
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{ dtStart: " + JSON.stringify(start) + ", dtEnd: " + JSON.stringify(end) + "}",
success: function(data) {
var events1 = [];
$(data.d).each(function() {
events1.push({
title: this.Title,
start: this.Start,
end: this.End,
id: this.Id
});
});
callback(events1);
$.mobile.loading('hide');
},
error: function(jqXHR, textStatus, errorThrown) {
if (jqXHR.statusText == 'abort') {
$.mobile.loading('hide');
return;
} else {
alert('There was an error');
$.mobile.loading('hide');
}
}
});
}
});
You can read more about those parameters here: https://fullcalendar.io/docs/event_data/events_json_feed/
The functionality you describe is a sort of date pagination, although this functionality isn't built in (shame, because it sounds really useful), you can implement your own with some small amount of work
First, the datepicker stores a JS Date object inside the ng-model, you can $watch it and get the current year/month/day out of it
$scope.modelDate = new Date()
...
$scope.$watch('modelDate', function(newDate, oldDate) {
newDate.getDay(); // 5
newDate.getMonth(); // 11
newDate.getYear(); // 116
})
Now you can query your database to get all the event for your selected month
Also, you can utilize the datepicker's mode (showing wether you are viewing the datepicker in the day/month/year mode, you set it up inside the options object).
datepickerMode C (Default: day) - Current mode of the datepicker (day|month|year). Can be used to initialize the datepicker in a specific mode.
Using this property you can query a month, year or years of events.

Why doesn't jquery submit work properly?

This code works fine in its current state where im using a click event on a button. But if i use a form tag around the input tags in my html code and use jquery's submit method it doesnt give any results. why is that happening? i have to use the form element because i want to be able to search with an enter key insted of clicking on a button
Html:
<body>
Title: <input type="text" id="title"><br/>
<input type="submit" value="Submit" id="btn">
<p id="results"></p>
<body>
jQuery:
$(document).ready(function(){
$("#btn").on("click", function(){
var textval = $('#title').val();
var playListURL = 'https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=' + textval + '&format=json&callback=?';
$.ajax({
type: "GET",
url: playListURL,
contentType: "application/json; charset=utf-8",
async: false,
dataType: "json",
success: function (data, textStatus, jqXHR) {
for (var i = 0; i < 10; i++)
{
var url = "https://en.wikipedia.org/wiki/" + data.query.search[i].title;
$("#results").append("<b> <a href='" + url + "' > " + data.query.search[i].title + "</a></b></br> ");
//console.log(url);
}
},
error: function (errorMessage) {
}
});
//alert($('#title').val());
});
});
Try to change this line
$("#btn").on("click", function(){
to this:
$("#btn").on("click", function(e){
e.preventDefault();
Then the form will not submit default way on click

jQuery how to run ajax with hover option and use .ajaxerror to addClass removeClass individual div

I have a page that displays a calendar into with a attribute "data-date" that as a date like: "11/29/2014" and I need to check server if there's a log file for that date and change css for that div on mouse hover.
So far i get this code:
$(document).ready(function() {
var lab = $( ".label.day" ).hover(
function() {
dd = $(this).attr("data-date").split("/");
ddo = $(this).attr("data-date");
dday = ("0" + (dd[1])).slice(-2);
dmonth = ("0" + (dd[0])).slice(-2);
dyear = dd[2];
url = "logs/log." + dyear + "-" + dmonth + "-" + dday;
$.ajax({
type: 'HEAD',
url: url,
error: function(xhr, status, error) {
console.log(status)
},
success: function(xhr, status, error) {
console.log(status)
}
});
$(document).ajaxError(function(event, jqxhr, settings, thrownError) {
console.log(thrownError)
if ( thrownError == "Not Found" ) {
$(".label.day").filter(ddo).addClass( "error" );
}
});
}, function() {
$(".label.day").filter(ddo).addClass( "noerror" );
}
);
});
<div data-date="1/16/2014" class="label day " original-title="Quinta" style="display: block;">16</div>
I can't change the class for the individual , without the .filter it changes all and .attr("data-date") doesn't work also.
There are several issues with your script:
You are not passing any data to the URL specified, via the data object in the $.ajax() function. Also, you need to specify to expected type of data (dataType) received (is it in JSON, plain text or otherwise?).
Use deferred objects and promises to check the status of the AJAX call
Use context, i.e. $(this), in your hover function so you can dictate which elements to modify without doing any filtering.
HEAD is an invalid value for the type object in the AJAX call. You should use POST or GET instead, depending on how the destination script is written to handle incoming data. Here's a good guide to deciding between the two.
Listen to mouseover instead of hover, as you are adding classes based on the status of the AJAX request, not the toggling between mouseover and mouseout events.
Use var when declaring functions to contain/restrict them within the function's scope, otherwise you risk polluting global variables :)
An improved code is as follow, but might not work unless you furnish more details on how you're checking the server for information.
$(document).ready(function() {
$('.label.day').on('mouseover', function() {
// Cache $(this)
var $t = $(this);
// Reset class
$t.removeClass('error noerror');
// Declare variables within function scope (not global)
var dd = $t.attr("data-date").split("/"),
ddo = $t.attr("data-date"),
dday = ("0" + (dd[1])).slice(-2),
dmonth = ("0" + (dd[0])).slice(-2),
dyear = dd[2],
url = "logs/log." + dyear + "-" + dmonth + "-" + dday;
// Perform AJAX call
var $check = $.ajax({
type: 'POST', //or "GET"
url: url;
});
// jQuery deferred object
$check.fail(function(jqXHR, textStatus) {
// If AJAX request failed and returned an error
console.log(textStatus);
$t.addClass('error');
}).done(function(data) {
// If AJAX request is successful
console.log(data);
$t.addClass('noerror');
});
});
});

jQuery .hide() and .show() not working

I have this code generate dynamically using php code:-
<div class="mailList" id="M_6">
<div class="mailListHeader" id="H_6">
<img style="float:right; display:none;" class="loaderIMG" id="LOADER_6" src="images/preloader.gif">
Sent by <strong>Admin</strong> on <strong>Oct 03 2013 02:53 PM</strong> to <strong>Received Response</strong> for Quarter <strong>3</strong> Year <strong>2013</strong>.<br>
Subject: <strong>Test Mail</strong><br>
</div>
<div class="mailListContent" id="C_6">
<div class="closeContent" id="CC_6">Close [x]</div>
<span id="SPAN_6"></span>
</div>
<div class="mailListFooter" id="F_6">
<span class="mailContentBtn" id="MCBTN_6" style="font-size:11px; color:#09C; cursor:pointer;">
View Content
</span>
<span class="mailListBtn" id="MLBTN_6" style="float:right; font-size:11px; color:#C06; cursor:pointer;">
Successfull-[0] Failed-[4]
</span>
</div>
</div>
Then, user can click View Content or Successfull-[0] Failed-[4] that will make a ajax request than display result in div mailListContent. Below is code for the jquery ajax request:-
$(".mailContentBtn, .mailListBtn").click(function(){
var currentId = $(this).attr('id');
currentId = currentId.split("_");
var actualId = currentId[1];
if($("#C_"+actualId).is(":visible")) {
$("#C_"+actualId).hide("slow","swing");
}
$("img#LOADER_"+actualId).show();
if(currentId[0]=="MCBTN") {
var dataString ="action=getMailContentByID&mailID="+actualId;
} else {
var dataString ="action=getMailListByID&mailID="+actualId;
}
$.ajax({
type: "POST",
url: "include/getMail.php",
data: dataString,
cache: false,
async: false,
success: function(html) {
$("#SPAN_"+actualId).empty();
$("#SPAN_"+actualId).append(html);
$("#C_"+actualId).show("slow","swing");
$("img#LOADER_"+actualId).hide();
}
});
});
The request and the events works fine, the problem is every time user click at View Content or Successfull-[0] Failed-[4] the loading image is not display. As you can see, I give a unique ID for every loading image than only 1 loading image will display on clik. There is no error in inspect code in Google Chrome. How can I solve this?
Thank you.
In your call to $.ajax, change the "async" option to "true". Because in your case, the $.ajax is blocking the ui thread in displaying the loading image as it is executed synchronously.
You have missed:
$(document).ready(function () {
});
try this:
<script>
$(document).ready(function () {
$(".mailContentBtn, .mailListBtn").click(function () {
var currentId = $(this).attr('id');
currentId = currentId.split("_");
var actualId = currentId[1];
if ($("#C_" + actualId).is(":visible"))
$("#C_" + actualId).hide("slow", "swing");
$("img#LOADER_" + actualId).show();
if (currentId[0] == "MCBTN") {
var dataString = "action=getMailContentByID" +
"&mailID=" + actualId;
}
else {
var dataString = "action=getMailListByID" +
"&mailID=" + actualId;
}
$.ajax({
type: "POST",
url: "include/getMail.php",
data: dataString,
cache: false,
async: false,
success: function (html) {
$("#SPAN_" + actualId).empty();
$("#SPAN_" + actualId).append(html);
$("#C_" + actualId).show("slow", "swing");
$("img#LOADER_" + actualId).hide();
}
});
});
})
</script>

Categories

Resources