Laravel AJAX GET and show new data - json

I've been working on a project and thus far I've been able to POST to the database using AJAX, so when the user submits data the page wont refresh but the data is still uploaded to the database.
Now what I want to do, is show those results to the user without needing to refresh the page. I've spent a lot of time trying to figure it out but right now I'm very stuck. Could anyone point me in the right direction? I've read the documentation on the website, watched hours worth of videos but still have no luck.
The code I have so far.
Script
$.ajax({
type: 'GET', //THIS NEEDS TO BE GET
url: '{{$video->id}}/shownew',
success: function (data) {
console.log(data);
$("#data").append(data);
},
error: function() {
console.log(data);
}
});
Controller
public function shownew($video)
{
$getstamps = DB::table('timestamps')
->where('videoid', '=', $video)
->orderByRaw('LENGTH(timestamp_time)', 'ASC')
->orderBy('timestamp_time', 'asc')
->get();
return response()->json(array('success' => true, 'getstamps' => $getstamps));
}
Console
{success: true, getstamps: Array(3)}
getstamps: Array(3)
0: {
timestamp_id: 128,
videoid: "5",
timestamp_name: "Title",
timestamp_time: 1,
created_at: "2017-10-04 23:28:12",
…
}
1: {
timestamp_id: 129,
videoid: "5",
timestamp_name: "1",
timestamp_time: 1,
created_at: "2017-10-04 23:41:01",
…
}
2: {
timestamp_id: 130,
videoid: "5",
timestamp_name: "1",
timestamp_time: 1,
created_at: "2017-10-04 23:41:21",
…
}
length: 3
__proto__: Array(0)
success: true
__proto__: Object

here is the solution for you problem
$.ajax({
type: 'GET', //THIS NEEDS TO BE GET
url: '{{$video->id}}/shownew',
success: function (data) {
var obj = JSON.parse(data);
var your_html = "";
$.each(obj['getstamps'], function (key, val) {
your_html += "<p>My Value :" + val + ") </p>"
});
$("#data").append(you_html); //// For Append
$("#mydiv").html(your_html) //// For replace with previous one
},
error: function() {
console.log(data);
}
});

This fixed the issue.
$.ajax({
type: 'GET', //THIS NEEDS TO BE GET
url: '{{$video->id}}/shownew',
dataType: 'json',
success: function (data) {
console.log(data);
container.html('');
$.each(data, function(index, item) {
container.html(''); //clears container for new data
$.each(data, function(i, item) {
container.append('<div class="row"><div class="ten columns"><div class="editbuttoncont"><button class="btntimestampnameedit" data-seek="' + item.timestamp_time + '">' + new Date(item.timestamp_time * 1000).toUTCString().match(/(\d\d:\d\d:\d\d)/)[0] +' - '+ item.timestamp_name +'</button></div></div> <div class="one columns"><form action="'+ item.timestamp_id +'/deletetimestamp" method="POST">' + '{!! csrf_field() !!}' +'<input type="hidden" name="_method" value="DELETE"><button class="btntimestampdelete"><i aria-hidden="true" class="fa fa-trash buttonicon"></i></button></form></div></div>');
});
container.append('<br>');
});
},error:function(){
console.log(data);
}
});

Related

On select of date on FullCalendar, the click accuracy is miscalibrated

I have not found another question quite like this. There are some similar with solutions like "be sure and include 'prev' and 'next' buttons" and things about timezones etc. I do not believe there is any issue with the logic or time zone or code on the backend. When I click on existing events, they work fine. I can click, drag, drop, edit, retrieve popup modal, etc. But when I click on an empty space in a date, it is inaccurate. I can see it visually selecting the wrong box. This is the case for every day of the month. The click is accurate in the top left 25% of the box. The bottom and left 75% is off by one box in that direction.
Look at May 18.
red: works perfect
yellow: selects 19th
blue: selects 26th
green: selects 25th
It is like a strange calibration issue. But if I click on an event, even if it is at the bottom of that box, like Thomas on May 5, it works just fine. Below is my js file.
function GetEventsOnPageLoad() {
$('#calendar').fullCalendar({
header: {
left: 'prev, next today',
center: 'title',
right: 'month, agendaWeek, agendaDay'
},
buttonText: {
today: 'Today',
month: 'Month',
week: 'Week',
day: 'Day'
},
selectable: true,
select: function (start) {
selectedEvent = {
eventID: 0,
start: start,
allDay: true,
};
CreateFullCalEvent(start.toISOString());
$('#calendar').fullCalendar('unselect');
},
height: 'parent',
events: function (start, end, timezone, callback) {
$.ajax({
type: "GET",
contentType: "application/json",
url: "GetEventData",
dataType: "JSON",
success: function (data) {
var events = [];
$.each(data, function (i, data) {
events.push(
{
title: data.title,
start: moment(data.start),
end: moment(data.end),
allDay: true,
backgroundColor: data.color,
id: data.id,
textColor: data.textColor
}
);
});
callback(events);
}
})
},
nextDayThreshold: '00:00:00',
editable: true,
droppable: true,
nowIndicator: true,
eventClick: function (info) {
GetFullCalEventByID(info);
},
eventDrop: function (info) {
console.log(info);
UpdateFullCalEvent(info.id, info.start.toISOString(), info.end.toISOString());
},
eventResize: function (info) {
UpdateFullCalEvent(info.id, info.start.toISOString(), info.end.toISOString());
}
})
}
function CreateFullCalEvent(start) {
window.location.href = "CreateFullCalEvent?start=" + encodeURIComponent(start);
}
function GetFullCalEventByID(eventinfo) {
$.ajax({
type: "GET",
url: "GetFullCalEventByID/" + eventinfo.id,
dataType: "JSON",
contentType: "applicaton/json; charset=utf-8",
success: function (eventdetails) {
showModal('Event Details', eventdetails, true);
}
});
}
function UpdateFullCalEvent(id, start, end) {
var object = {};
object.id = id;
object.start = start;
object.end = end;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "UpdateFullCalEvent/",
dataType: "JSON",
data: JSON.stringify(object)
});
}
function showModal(title, body, isEventDetail) {
$("MyPopup .modal-title").html(title);
if (isEventDetail == null) {
$("#MyPopup .modal-body").html(body);
$("#MyPopup").modal("show");
}
else {
var title = 'Title: ' + body.title + '</br>';
var details = 'Details: ' + body.details + '</br>';
var date = 'Date: ' + moment(body.start).format("M/D/YYYY") + '</br>';
var empName = 'Employee: ' + body.employeeName + '</br>';
url = 'Location: ' + body.url + '</br>';
var modalPop = $("#MyPopup .modal-body");
modalPop.html(title + details + date + empName + url);
$("#MyPopup.modal").modal("show");
}
}
About line 16 to 21 is the issue. It happens even if I am not calling a function at all. If I just do a popup modal like below, I can still see it highlighting and selecting the wrong day:
selectable: true,
select: function () {
showModal('Create an Event', 'Create new Event feature coming soon. For now, use create button in list view', null);
The CSS was the issue. I had
body {
zoom: 110%;
}
Apparently fullCalendar does not respond well to zoom feature of CSS. It is not a problem if the user zooms in the browser though.

Table doesn't refresh with table.ajax.reload(), when used after a delete operation is performed on a row

I have a table which is printing data in this form,
var table;
// DATA TABLE!!!
function show_assigned_table()
{
$.ajax({
url: "action.php",
type: "POST",
data: {action:"view_assigned_course_table"},
dataType: 'json',
success: function(data)
{
console.log(data);
table = $('#assign_table').DataTable({
"bDestroy": true,
data: data,
columns: [
{'data': 'course_name'},
{'data': 'teacher_name'},
{'data': 'grade_name'},
{'render': function(data, type, row, meta){
return '<a id="replace_teacher' + meta.row + '" data-value = ' + row.taught_id +
' class="btn btn-outline-warning btn-sm" href="">Replace</a> <a id="remove_teacher' +
meta.row + '" data-value = ' +
row.taught_id + ' class="btn btn-outline-danger btn-sm" href="">Delete</a>';
}},
]
});
},
error: function(e)
{
alert("no");
}
});
}
Now, I have another function for the "Replace" and "Delete" buttons. A function for delete button is as follows,
$(document).on("click", "[id^=remove_teacher]", function(e){
var id = $(this).data('value');
e.preventDefault();
$.ajax({
url: "action.php",
type: "POST",
data:{action: "Remove_Assigned_Teacher", id: id},
success:function(response)
{
response = response.trim();
console.log(response);
if (response == 'ok')
{
alert("Teacher has been removed from the course successfully!");
$("#assign_table").DataTable().ajax.reload();
}
else
alert("Error occured");
}
});
});
This function works well, except one thing, it doesn't Refresh the table whenever a row is deleted... To refresh the table, I have to refresh the whole page. What I want is only this table to be refreshed whenever the delete event occurs.
I used ajax.reload() function for this but it didn't work, as it apparently didn't receive JSON data on refresh (now I tried to search it but I couldn't find any thing which I could properly understand. I did find a code to convert array to JSON but didn't get how to implement it in my code. I am still very new in this).
I also tried using destroy function and then created the table again, that worked but it destroyed all the properties of my table (like the border of table, search bar and etc. The look of the table changed)
Your issue is in this line:
$("#assign_table").DataTable().ajax.reload()
Your datatable has no ajax option, hence you get an error in the console:
jquery.dataTables.min.js:50 Uncaught TypeError: Cannot set property 'data' of null
Because you control the datatable client side, using jquery ajax, you need to use datatable row remove() in order to delete a row, i.e.:
$('#assign_table').DataTable().row( $(this).closest('tr')).node().remove()
If instead you wish to control everything server side you need to use the datatable ajax option and change a bit the logic of your sw. In this case I would suggest you to take a look to Removing rows with ajax Data
var data = [
{
"taught_id": "11",
"course_name": "English",
"grade_name": "2",
"section_name": "A",
"teacher_name": "Ali Khalil"
},
{
"taught_id": "6",
"course_name": "Science",
"grade_name": "2",
"section_name": "A",
"teacher_name": "Talha Ayub"
},
{
"taught_id": "8",
"course_name": "Science",
"grade_name": "7",
"section_name": "A",
"teacher_name": "Talha Ayub"
}
];
function show_assigned_table() {
/*
$.ajax({
url: "http://localhost:63342/StackOverflow/1.json",
type: "POST",
data: {action:"view_assigned_course_table"},
dataType: 'json',
success: function(data) {
*/
$('#assign_table').dataTable({
data: data,
columns: [
{'data': 'course_name'},
{'data': 'teacher_name'},
{'data': 'grade_name'},
{
'render': function (data, type, row, meta) {
return '<a id="replace_teacher' + meta.row + '" data-value = ' + row.taught_id +
' class="btn btn-outline-warning btn-sm" href="">Replace</a> <a id="remove_teacher' +
meta.row + '" data-value = ' +
row.taught_id + ' class="btn btn-outline-danger btn-sm" href="">Delete</a>';
}
}
]
});
/*
},
error: function(e) {
alert("no");
}
})
*/
}
$(document).on("click", "[id^=remove_teacher]", function (e) {
var response = {
"data": "ok"
};
e.preventDefault();
var crow = $('#assign_table').DataTable().row( $(this).closest('tr')).node();
var id = $(this).data('value');
console.log('taught_id --> ' + id);
//$.ajax({
//url: "http://localhost:63342/StackOverflow/2.json",
//type: "POST",
//data: {action: "Remove_Assigned_Teacher", id: id},
//success: function (response) {
response = response.data.trim();
console.log(response);
if (response == 'ok') {
//alert("Teacher has been removed from the course successfully!");
crow.remove();
}
else
alert("Error occured");
//}
//});
});
show_assigned_table();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/dataTables.bootstrap4.min.js"></script>
<table id="assign_table" class="display" style="width:100%">
<tbody>
</tbody>
</table>

Call JSON method in asp.net mvc without page refresh?

Here is my JSON method in controller
public JsonResult GetNotificationForAll()
{
Int64 userid = Convert.ToInt64(Session["UserID"]);
string searchcriteria = string.Format("N.notificationfor ={0}", 1);
PODService.Notification[] notification = service.GetNotificationBySearchCriteria(searchcriteria);
return Json(notification, JsonRequestBehavior.AllowGet);
}
Here is my script code for JSON method:
var URL6 = "/Home/GetNotificationForAll";
$.getJSON(URL6, "", function (data) {
var x = { "padding-left": "10px" };
$.each(data, function (index, value) {
$("<td>"
+ value["Notification_Name"]
+ "</td>")
.appendTo("#Allnotification").css(x);
});
});
Here is my view:
<div id="Allnotification" style="color:White;float:left;margin-left:10px"> </div>
I want to show data without page refresh.
i have found the solution.
function NotificationForALL() {
$("#Allnotification").empty();
$.ajax({
type: "GET",
url: "#Url.Action("GetNotificationForAll", "Home")",
dataType: "json",
cache: false,
success: function (data) {
$.each(data, function(index, element) {
var x = { "padding-left": "10px" };
$("<td>"
+ element["Notification_Name"]
+ "</td>") .appendTo("#Allnotification").css(x);
});
setTimeout(function(){NotificationForALL();}, 900000);
}
});
}
NotificationForALL();
Hope it will help to someone

jqPlot and JSON formatted Data

I'm returning a JSON string with an Ajax call in jQuery, I'd like to pump that data into a bar chart using jqPlot.
I got the JSON conversion code from another Stack-Overflow post, but can't understand why this isn't working. My code:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(DTO), //JSON.stringify(AnDParms), combined,
url: "GetAdmitsDischarges.asmx/GetAandD",
dataType: "json",
success: function (data) {
//do chart stuff here.
var line1 = [];
for (var prop_name in data.d) {
line1.push([prop_name, data[prop_name]])
}
var ticks = ['Admits', 'Discharges'];
var plot1 = $.jqplot('chartdiv', [line1], {
title: 'Admits & Discharges',
series: [{ renderer: $.jqplot.BarRenderer}],
axesDefaults: {
tickRenderer: $.jqplot.CanvasAxisTickRenderer
},
axes: {
xaxis: {
renderer: $.jqplot.CategoryAxisRenderer
}
}
});
//to prove the flow is working...
//alert("Data: " + data.d);
}, //end of success
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus + ' ' + errorThrown + ' ' + XMLHttpRequest);
} //end of error
}); //end of ajax call
In Firebug, the value of line1 is (going from 0 to 32):
[["0", undefined],["1", undefined],...["31", undefined],["32",
undefined]]
While the value of data is:
Object { d="{"Admits":"35","Discharges":"36"}" }
Thanks for any help you can offer...
The problem is your JSON structure:
{
"Admits": "35",
"Discharges": "36"
}
You are providing a JSON object, but jqplot needs array instead:
[
["Admits", 35],
["Discharges", 36]
]
I finally figured it out with the help of Dave Ward of Encosia.com...if you've not checked out his blog, head straight there right now...it's great for all your .Net/jQuery needs.
Here is my javascript:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(DTO),
url: "GetAdmitsDischarges.asmx/GetAandD",
dataType: "json",
success: function (data) {
var jqPlotData = $.map(data.d, function (value, key) {
if (key != "__type") {
return [value]; //was key, value
}
});
var ticks = ['Admits', 'Discharges'];
var plot1 = $.jqplot('chartdiv', [jqPlotData], {
title: 'Admits & Discharges',
seriesDefaults: {
renderer: $.jqplot.BarRenderer,
rendererOptions: { varyBarColor: true },
pointLabels: { show: true }
},
axes: {
xaxis: {
renderer: $.jqplot.CategoryAxisRenderer,
ticks: ticks
}
},
highlighter: { show: false }
});
Also, I removed the JSON serialization from my web service, and just returned the object. Hopefully this will help others.

jquery validation onSubmit ajax post JSON response

I have a very complicated post using jquery validation and an AJAX post that gets a JSON response back from the server and puts it in a jqGrid... But it seems as though my onsuccess is never being called at any point...
$(document).ready(function () {
$("#formSearchByMRN").validate({
rules: {
MRN: { required: true, minLength: 6 }
},
messages: {
MRN: 'Please Enter a Valid MRN'
},
submmitHandler: function (form) {
e.preventDefault();
animateLoad();
debugger;
var theURL = form.action;
var type = form.methd;
var data = $(this).serialize();
$.ajax({
url: theURL,
type: type,
data: data,
dataType: "json",
success: function (result) {
debugger;
var data = result;
if (data.split(':')[0] == "Empty record") {
$("#list").unblock();
$('#resultDiv').html('<b><p style="color: #ff00ff">' + data + '</p></b>');
setTimeout(function () {
$('#resultDiv').html("");
}, 10000);
}
else {
binddata(data);
}
}
});
return false;
}
});
});
It would seem I never get into the submmitHandler. Event though I manage to get to my server side function and it does return, it prompts my UI to save a file which contains the JSON results...
No good.
Am I going about validating my form before my AJAX post the wrong way? Does anybody have any advice about best practices in validating AJAX posts?
UPDATE... MARK R. This is what I attempted. It seems as though I never get in to the success function... My suspicion is that I am not really posting via ajax, but instead doing a full post. I don't understand why.
$('#submitMRN').click(function () {
$("#formSearchByMRN").validate({
rules: {
MRN: { required: true, minLength: 6 }
},
messages: {
MRN: 'Please Enter a Valid MRN'
}
});
if ($('#submitMRN').valid()) {
$("#list").block({ message: '<img src="../../Images/ajax-loader.gif" />' });
$.ajax({
url: $('#submitMRN').action,
type: $('#submitMRN').method,
data: $('#submitMRN').serialize(),
dataType: "json",
success: function (result) {
debugger;
var data = result;
if (data.split(':')[0] == "Empty record") {
$("#list").unblock();
$('#resultDiv').html('<b><p style="color: #ff00ff">' + data + '</p></b>');
setTimeout(function () {
$('#resultDiv').html("");
}, 10000);
}
else {
binddata(data);
}
}
});
}
});
$('#SubmitButton').click(function (){
//Check that the form is valid
$('#FormName').validate();
//If the Form is valid
if ($('#FormName').valid()) {
$.post(...........
}
else {
//let the user fix their probems
return false;
}
});//$('#SubmitButton').click(function (){