ajax code to check new records at database - ajax

I am using laravel, and I want to check if there are new records inserted into the database, I want an Ajax code the returns with the result, I don't know ajax so please help me
this is my controller
public function newrecord($target_id){
$record = Message::where('target_id', $target_id)->get();
return $record->count();
}**strong text**
and this is my ajax code
$(document).ready(function(){
var ajaxCall=function()
{
$.ajax({
url:"{{ url('/record/'.$auth->id) }}" ,
type: "GET",
datatype:"html",
data:{},
success:function(data) {
$('.msgnum').html(data)
console.log('new record);
},
error: function(data) {
console.log('error');
}
});
}
setInterval(ajaxCall,5000);
});
all I get is just a loop or " new record " in the console log
Do I need to return anything to tell that there is a new file, any help?

Try this, of course modify the code to how you want it to work but wrap the whole thing in setInterval, you don't even need the document.ready()
<script type="text/javascript">
setInterval(function() {
$.ajax({
url:"{{ url('/record/'.$auth->id) }}",
type: "GET",
datatype:"html",
data:{},
processData:false,
success: function(data){
$('.msgnum').html(data)
console.log('new record');
error: function(data) {
console.log('error');
}
},
error: function(){}
});
}, 5000);
</script>

Related

Laravel/Ajax delete function not refreshing my table after success

when I add my function fetchcategory(); in my delete ajax, my table is not refreshing:
$(document).on('click', '.delete_category_btn', function (e) {
e.preventDefault();
var cat_id = $('#delete_cat_id').val();
alert('Category Deleted!');
// location.reload();
$('#deleteCategoryModal').modal('hide');
fetchcategory();
//token taken from laravel documentation
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "DELETE",
url: "/clinical/bbr-category-configuration-delete/"+cat_id,
dataType: "dataType",
});
});
for a reference, my screenshot shows the alert, showing that the delete function follows through:
another reference is that my add function here reloads the page after a new table is added:
$.ajax({
type: "POST",
url: "/clinical/bbr-category-configuration",
data: category_data,
dataType: "json",
success: function (response){
console.log(response);
if(response.status == 400) {
$('#category_formCheck').html("");
$('#category_formCheck').addClass('alert alert-danger');
$.each(response.errors, function (key, err_values) {
$('#category_formCheck').append('<li>'+err_values+'</li>');
});
}
else
{
$('#category_notif').html("");
$('#category_notif').addClass('alert alert-success');
$('#category_notif').text(response.message);
$('#createCategory').modal('hide');
fetchcategory();
}
}
});
another problem of mine is that I tried to add the alert and refresh function inside:
$.ajax({
type: "DELETE",
but they do not show up, so I placed them inside on(click
why is my delete ajax not refreshing my table?
UPDATE:
I am aware of location.reload(); but adding this defeats the purpose.
the data does get deleted, I have to manually refresh the whole page to see the changes though.
You can do it in ajax success. I believe fetchcategory() method is populating data to table
<script>
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).on('click', '.delete_category_btn', function (e) {
e.preventDefault();
var cat_id = $('#delete_cat_id').val();
// location.reload();
$('#deleteCategoryModal').modal('hide');
$.ajax({
type: "DELETE",
url: "/clinical/bbr-category-configuration-delete/"+cat_id,
dataType: "dataType",
success: function(data) {
alert('Category Deleted!');
fetchcategory();
},
error: function() {
alert('Error occured');
}
});
});
</script>

Ajax post calling wrong url

Good day.
I want to know why is my project calling the wrong url? The code is:
SCRIPT
$.ajax({
type: "POST",
url: "/Application/Franchise",
data: JSON.stringify(sendInfo),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
$('#myModal3').modal('hide'); //hide the modal
},
error: function () {
alert("Error while inserting data");
}
});
CONTROLLER
public class ApplicationController : Controller
{
public ActionResult Franchise()
{
return View();
}
}
I even tried changing the url by 'Url.Action("Franchise", "Application")' but still the system kept on bringing me to http://localhost:49267/Home/Franchise.
I can't understand what is wrong here. Is there a bug in jquery ajax url post?
Thanks in advance.
UPDATE
<button class="btn btn-success" type="button" id="btnCapture">Submit</button>
#section Scripts{
<script src="~/Scripts/webcam.min.js"></script>
<script src="~/Scripts/webcam.js"></script>
<script language="JavaScript">
Webcam.set({
width: 320,
height: 240,
image_format: 'jpeg',
jpeg_quality: 90
});
Webcam.attach( '#my_camera' );
</script>
<script language="JavaScript">
function take_snapshot() {
Webcam.snap( function(data_uri) {
document.getElementById('results').innerHTML =
'<img id="base64image" src="' + data_uri + '"/>';
} );
}
</script>
<script>
$(document).on("click", ".open-camera", function () {
var myBookId = $(this).data('id');
$(".modal-body #franid").val(myBookId);
})
</script>
<script>
$(function(){
$('#btnCapture').on('click', function(){
var file = document.getElementById("base64image").src;
var franid = $("#franid").val();
var sendInfo = {
Imagee: file,
FranIDD: franid
};
$.ajax({
type: "POST",
url: "/Application/Franchise",
data: JSON.stringify(sendInfo),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
$('#myModal3').modal('hide'); //hide the modal
},
error: function () {
alert("Error while inserting data");
}
});
});
});
</script>
}
This is all my code.
Ok. So I found my problem. It was in my controller.
In my controller I tried adding return RedirectToAction("Franchise", "Home"); after the save command. As soon as I commented this, everything worked.
Thanks for the help again guys.
Please use the browser to access directly, not from within the IDE directly access, from the localhost:49267 should be from the IDE access, and you will write URL as http://www.google.com try.

Ajax request type POST returning GET

I'm currently trying to make an ajax POST request to send a testimonial simple form to a Django view. The problem is this request is returning a GET instead of a POST.
This is my ajax:
<script>
$(document).ready(function(){
$("form.testimonial-form").submit(function(e){
e.preventDefault();
var dataString = $(this).serialize();
$.ajax({
type: "POST",
url: "/testimonials",
data: dataString,
success: function(_data) {
if (_data[0]){
$('.modal-text').css({display: "none"});
}
else{
$('.unsuccess').css({display: "block"});
}
}
});
});
});
</script>
Any idea what could I be doing wrong?
replace type by method
method: 'post',
also you may need send headers:
headers: {
'X-CSRFToken': getCSRFToken()
},
where getCSRFToken is:
function getCSRFToken() {
return $('input[name="csrfmiddlewaretoken"]').val();
}
I am not really sure why this is happening, but i would write the function in a bit different way. since ajax();'s default type is "GET", i suspect somewhere it is being set to default.
first set the type="button" of submit button (whose id is e.g. "submit_button_id"), so it doesnot submits if you click on it. or put the button outside of <form>
then try this code
<script>
$(function(){ // same as "$(document).ready(function()"..
$("#submit_button_id").on('click',function(){
var dataString = $('form.testimonial-form').serialize();
$.ajax({
type: "POST",
url: "/testimonials",
data: dataString,
success: function(_data) {
if (_data[0]){
$('.modal-text').css({display: "none"});
}
else{
$('.unsuccess').css({display: "block"});
}
}
});
});
});
</script>

Is it possible to make multiple calls using Jsonp with deferred objects?

I'm trying to make two or more requests all at once if that's even possible? I'm concerned about speed since after the first request is made I want to display that info onto a web page and then do the same for each additional url.
I've been reading about deferred objects and trying some examples, and so far I've tried to do this,
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script >
$(document).ready(function($) {
// - 1st link in chain - var url = 'https://www.sciencebase.gov/
catalog/items?parentId=504108e5e4b07a90c5ec62d4&max=60&offset=0&format=jsonp';
// - 2nd link in chain - var url = 'https://www.sciencebase.gov/
catalog/itemLink/504216b6e4b04b508bfd333b?format=jsonp&max=10';
// - 3rd (and last) link in chain - var url = 'https://www.sciencebase.gov/
catalog/item/4f4e4b19e4b07f02db6a7f04?format=jsonp';
// parentId url
function parentId() {
//var url = 'https://www.sciencebase.gov/catalog/items?parentId=
504108e5e4b07a90c5ec62d4&max=3&offset=0&format=jsonp';
return $.ajax({
type: 'GET',
url: 'https://www.sciencebase.gov/catalog/items?parentId=
504108e5e4b07a90c5ec62d4&max=3&offset=0&format=jsonp',
jsonpCallback: 'getSBJSON',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {},
error: function(e) {
console.log(e.message);
}
});
}
// itemLink url
function itemLink() {
//var url = 'https://www.sciencebase.gov/catalog/itemLink
/504216b6e4b04b508bfd333b?format=jsonp&max=10';
return $.ajax({
type: 'GET',
url: 'https://www.sciencebase.gov/catalog/itemLink
/504216b6e4b04b508bfd333b?format=jsonp&max=10',
jsonpCallback: 'getSBJSON',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {},
error: function(e) {
console.log(e.message);
}
});
}
// Multiple Ajax Requests
$.when( parentId(), itemLink()).done(function(parentId_data, itemLink_data) {
console.log("parentId_data.items[0].title");
});
});
But it doesn't seem like the functions are functioning. I was expecting to be able to put some stuff after the .when() method inside the function to tell my program what to do, but I'm not getting anything displayed??
Thanks for the help!
Part of the problem is that in the done handler for $.when, the arguments that are passed to the callback are the array of arguments for each request, not simply the data that you want to use. You can get around this by using .pipe as in the example below.
Also, don't specify jsonpCallback unless you have a very good reason, most of the time you want to let jQuery manage that internally for you.
Here's a working example tested on JSFiddle
jQuery(function($) {
function parentId() {
return $.ajax({
url: 'https://www.sciencebase.gov/catalog/items?parentId=504108e5e4b07a90c5ec62d4&max=3&offset=0&format=jsonp',
dataType: 'jsonp',
error: function(e) {
console.log(e.message);
}
// We'll use pipe here so that rather than the value being passed to our $.when handler
// is simply our data rather than an array in the form of [ data, statusText, jqXHR ]
}).pipe(function( data, statusText, jqXHR ) {
return data;
});
}
function itemLink() {
return $.ajax({
url: 'https://www.sciencebase.gov/catalog/itemLink/504216b6e4b04b508bfd333b?format=jsonp&max=10',
dataType: 'jsonp',
error: function(e) {
console.log(e.message);
}
}).pipe(function(data) {
return data;
});
}
// Multiple Ajax Requests
$.when( parentId(), itemLink()).done(function(parentId_data, itemLink_data) {
console.log( parentId_data, itemLink_data );
});
});

Showing Django comments after submission with ajax

I implemented Django ajax comment submission in my app using Nick Carroll's method here. I'd like the user that posted the comment, date of submission and comment to appear on the page using ajax after the server has received and saved it. What's a good way to do this?
Use jquery's post method to post the comment to server and on successful response,display the comment on the page from the success call back function.
Alright this is kind of a hackerish way to go about this, but I think I've figured out a decent solution:
<script type="text/javascript" charset="utf-8">
function bindPostCommentHandler() {
$('#comment_form form input.submit-preview').remove();
$('#comment_form form').submit(function() {
var comment_text = $('#id_comment').val();
$.ajax({
type: "POST",
data: $('#comment_form form').serialize(),
url: "{% comment_form_target %}",
cache: false,
dataType: "html",
success: function(html, textStatus) {
$('#comment_form form').fadeTo(500, 0, function(){
$(this).remove();
});
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1;
var yyyy = today.getFullYear();
if(dd<10){dd='0'+dd} if(mm<10){mm='0'+mm} var today = mm+'/'+dd+'/'+yyyy;
var comment = "<div class='comment'><h4>User " + "\"{{ user.username }}\"" + " Rating <small>" + today + "</small></h4>" + comment_text + "</div><hr />";
$(comment).hide().prependTo("#comments_loc").fadeIn(1000);
bindPostCommentHandler();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$('#comment_form form').replaceWith('Your comment was unable to be posted at this time. We apologize for the inconvenience.');
}
});
return false;
});
}
$(document).ready(function() {
bindPostCommentHandler();
});
</script>
I'm relatively new to javascript so I put this together with what little I know. Feel free to leave some comments if you think this could be cleaned up.
<script type="text/javascript" charset="utf-8">
function bindPostCommentHandler() {
$('#comment_form form input.submit-preview').remove();
$('#comment_form form').submit(function() {
$.ajax({
type: "POST",
data: $('#comment_form form').serialize(),
url: "{% comment_form_target %}",
cache: false,
dataType: "html",
success: function(html, textStatus) {
$('#comment_form form').replaceWith(html);
$('.comt_message').show();
bindPostCommentHandler();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$('#comment_form form').replaceWith('Your comment was unable to be posted at this time. We apologise for the inconvenience.');
}
});
return false;
});
}
$(document).ready(function() {
bindPostCommentHandler();
});
</script>

Resources