First of all im sorry for my bad English. im from Sri Lanka and im bad in English. I'm trying to create a chat site. but i have a problem checking for m=new messages. i used jquery setInterval() and ajax to check messages.
function chat() {
var fid = $('#send').data('id');
$.ajax({ url: "php/control/chat.php", type: 'post', dataType: 'json', data: { fid: fid }, success: function (obj) {
if(obj){
browser.find('.chat-view .seen').hide();
browser.find('.user-chat .chat-view').append(function () {
var msgs = '';
for( var i = 0; i < obj.length; i++) {
msgs += '<div class="user u2 d-flex flex-row">' +
' <span class="msg">' +
' <span class="text">' + obj[i].msg + '</span>' +
' <span class="time">' + nowTime(obj[i].sent) + '</span>' +
' </span>' +
'</div>';
}
return msgs;
});
browser.find('.chat-view').animate({scrollTop:browser.find('.chat-view')[0].scrollHeight});
}
}
});
}
setInterval(function () {
if(browser.find('div.chat-view').hasClass('chat-view') && browser.css('display') == 'block') {
chat();
}
}, 500);
i set to reply 0 from php when there is no new messages to reduce data usage. This works fine. but when there was no messages it still use 370 bytes for 1 reply and its about 45KB for a minute.
I checked facebook in chrome inspect and found out they are using a method to send a request to the server and wait for a new message or notification. server reply for that request only if there is something new. i tried using php sleep() function but i think it might cause a DoS attack on server. i cant check on WAMP because it only allow one request at one time. Please help me if someone know how to wait for a request without causing the server to stuck.
Related
We have SharePoint online 2013 site which displays the reports for different departments. All departments have different groups and they have assigned permission that way so one group can not see other group files. I am using JAVA SCRIPT and AJAX to get the files from gallery. when I use JavaScript on my page I am unable to open the documents in client application, it opens in office online than users have to download. IS there anyway user can click on it and it will download the files. I went to library setting and changed the default to open in client application also changed in site collection and features but still SharePoint opens the file in online instead of client application. We are using office 2010 and SharePoint online 2013.
(function () {
// Create object that have the context information about the field that we want to change it's output render
var galleryContext = {};
galleryContext.Templates = {};
galleryContext.Templates.Header = "<div class='gallery'>";
galleryContext.Templates.Footer = "</div><div class='gallerydocs'></div>";
// This line of code tell TemplateManager that we want to change all HTML for item row render
galleryContext.Templates.Item = galleryTemplate;
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(galleryContext);
})();
// This function provides the rendering logic
function galleryTemplate(ctx) {
var icon = ctx.CurrentItem["GalleryIcon"];
var src = ctx.CurrentItem["FileRef"];
var name = ctx.CurrentItem["Title"];
var subtitle =ctx.CurrentItem["SubTitle"];
var bgcolor = ctx.CurrentItem["BackgroundColor"];
var fontcolor = ctx.CurrentItem["FontColor"];
//var description = ctx.CurrentItem["Description"];
// console.log(JSON.stringify(ctx.CurrentItem["GalleryIcon"]));
// Return whole item html
return "<div onclick='javascript:getGalleryDocs("+'"'+ src + '"' +", "+'"'+ bgcolor + '"' +", "+'"'+ subtitle + '"' +", "+'"'+ fontcolor + '"' +", "+'"'+ name + '"' +" )'><div class='galleryblock' style='background-color:" + bgcolor + ";color:"+ fontcolor+"' >"+name +"<br/><br/><p>"+subtitle +"</p></div></div>";
}
function getGalleryDocs(folder , bgcolor, subtitle ,fontcolor , name)
{
$.ajax({
url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/GetFolderByServerRelativeUrl('"+folder+"')/files?$orderby=Title",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
var html="<div class='gallerynav'><span><a href='javascript:goback();'>BILLING REPORTS</a><span> <i class='fa fa-caret-right' ></i><span>"+name+"</span></div><div class='galleryblock' style='float:none;background-color:" + bgcolor + ";color:"+ fontcolor+"' >"+name +"<br/><br/><p>"+subtitle +"</p></div><span></span>";
var results = data.d.results;
//console.log(JSON.stringify(results.length));
html+= "<ul class='gallerylinks'>";
if(results.length > 0)
{
for( i=0 ; i< results.length ; i++)
{
var item = results[i];
html+= "<li><a href='" + item.LinkingUrl + "' target='_blank'>"+item.Title+" <i class='fa fa-external-link'></i></a></li>";
}
}
else
{
html+=" THERE ARE NO DOCUMENTS IN THIS GALLERY"
}
html+="<ul>"
//console.log(JSON.stringify(data));
$(".gallery").hide(500);
$(".gallerydocs").html(html);
},
error: function (data) {
$(".gallerydocs").html("You dont have permissions to view this folder!")
}
});
}
function goback(){
$(".gallery").show(500);
$(".gallerydocs").html("");
}
I've not got an environment to hand to test this on but it will be something to do with your href link. It's needs to be built differently. The solution below hopefully will open in the clients application.
Try
<a href=""
onclick="editDocumentWithProgID2('http://server/site/doclib/folder/Document.docx',
'',
'SharePoint.OpenDocuments', '0',
'http://server/site', '0')">
This will open the file in edit mode
</a>
A full post can be found here
THis post offers a solution to directly download
Sorry I can't test
Good luck
Cheers
Truez
Trying to display the cover art with the results. Something in the img src tag is causing the app not to load. If I just point the img to data.tracks[i].album.name (obviously not a real url, but enough to test if it's working) it pastes it in just fine, but the moment I change it to paste the url in place, it makes the whole app stop working.
$('#findTracks').click(function (e) {
e.preventDefault(); // override/don't submit form
$('#recommendations').empty();
var artist = $('#artist').val();
var userid = "";
var playlistid = "";
$.ajax({
url: 'http://ws.spotify.com/search/1/track.json?q=' + artist,
type: 'GET',
dataType: 'json',
success: function(data) {
if (data.tracks.length > 0) {
var tracksLength = data.tracks.length, html = '';
for (var i=0; i<tracksLength; i++) {
var href = '';
if (data.tracks[i].album.availability.territories.indexOf(' GB ') !== -1) { // data.tracks[i].href
href = data.tracks[i].href;
href = 'makeReq(\''+data.tracks[i].name + ' by '+data.tracks[i].artists[0].name+'\')';
html += '<li>' +data.tracks[i].name + ' by '+data.tracks[i].artists[0].name+ ' <img src="' +data.tracks[i].album.images[0].url+ '" />';html += '</li>';
html += '</li>';
}
}
$('#third').css('display', 'block');
$('#recommendations').append(html);
} else {
$('#recommendations').append('<li>No matches returned.</li>');
$('#third').css('display', 'none');
}
},
error: function(err) {
alert("The Spotify API failed to return a response.");
}
});
});
This is my first time ever coding in javascript so please go easy on me! lol
EDIT:
This seems to be running well! However, many of the songs do nothing when I click on them
For example, type "Don't Stop" and only "The Black Eyed Peas - Don’t Stop The Party" works out of the first ten...anybody know why?
also, anybody known why "if (data.tracks[i].album.availability.territories.indexOf(' GB ') !== -1)" is in there? If I take it out this all stops working...I am not in G.B.
If you look in the console you are getting the error
Uncaught TypeError: Cannot read property '0' of undefined
looking at the data the query returns we notice that data.tracks[i].album returns
{
"released": "2006",
"href": "spotify:album:2knAf4wg8Gff8q1bXiXCTz",
"name": "The Dutchess",
"availability": {
"territories": "MX"
}
}
there is no property images so when you call
data.tracks[i].album.images[0]
you get the undefined error, causing the script to halt execution.
I'm unfamiliar with the spootify api but taking a quick glance at the api theres the endpoint for get-album. Heres what I was able to come up with to get the album art
$.get("http://ws.spotify.com/search/1/track.json?q=Fergie",function(data){
var albumId = data.tracks[97].album.href.split(":")[2];
$.get("https://api.spotify.com/v1/albums/" + albumId,function(albumResponse){
var firstImage = albumResponse.images[0];
$('body').append($('<img/>',{
src : firstImage.url,
width : firstImage.width,
height : firstImage.height
}));
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body></body>
You should research more into how to get the album art since I'm unsure if this is the optimal solution.
The search endpoint you mentioned is different from the one your using.
One your using
url: 'http://ws.spotify.com/search/1/track.json?q=' + artist,
One you linked to
url: 'https://api.spotify.com/v1/search?q=' + artist + '&type=track,artist&market=GB',
Heres your solution with the change in endpoint
$('#findTracks').click(function(e) {
e.preventDefault(); // override/don't submit form
$('#recommendations').empty();
var artist = $('#artist').val();
var userid = "";
var playlistid = "";
$.ajax({
//url: 'http://ws.spotify.com/search/1/track.json?q=' + artist,
url: 'https://api.spotify.com/v1/search?q=' + artist + '&type=track,artist&market=GB',
type: 'GET',
dataType: 'json',
success: function(data) {
if (data.tracks.items.length > 0) {
data.tracks = data.tracks.items
data.artists = data.artists.items
var tracksLength = data.tracks.length,
html = '';
for (var i = 0; i < tracksLength; i++) {
var href = '';
href = data.tracks[i].href;
href = 'makeReq(\'' + data.tracks[i].name + ' by ' + data.tracks[i].artists[0].name + '\')';
html += '<li>' + data.tracks[i].name + ' by ' + data.tracks[i].artists[0].name + ' <img src="' + data.tracks[i].album.images[0].url + '" />';
html += '</li>';
html += '</li>';
}
$('#third').css('display', 'block');
$('#recommendations').append(html);
} else {
$('#recommendations').append('<li>No matches returned.</li>');
$('#third').css('display', 'none');
}
},
error: function(err) {
alert("The Spotify API failed to return a response.");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Artist:
<input type="text" id="artist" />
<button id="findTracks">Find Tracks</button>
<div id="recommendations"></div>
Good evening.
I have this jquery code which allows me, once you press the Enter key, to post a comment.
Fattio that I run an append with the username and the content that the user wants to publish.
In addition to the username I would also like to "hang" the profile picture using their path. How do I post a photo?
Thanks for your help. Here's the code:
function commento_post(id_post)
{
$('.form-commento'+id_post).click(function ()
{
$('#ins_commento'+id_post).keydown(function (e)
{
var message = $("#commento"+id_post).val();
var username = $("#username").val();
var id_user = $("#id_user").val();
if(e.keyCode === 13)
{
$.ajax(
{
type: 'POST',
url: 'http://localhost/laravel/public/index.php/post/ins_commento',
data: { commento: message, id_post: id_post },
success: function(data)
{
$('#commento'+id_post).val('');
$('#commentscontainer'+id_post).append
(
/*$(".username-commento"+id_post).html
(*/
$('<a/>',
{
text : username, href : 'http://localhost/laravel/public/index.php/utente/'+id_user
}).css({'font-weight':'bold'})
//)
).append(' ').append(message).append($('<br/>'));
var el = $('#numero_commenti'+id_post);
var num = parseInt(el.text());
el.text(num + 1);
}
});
}
});
});
}
In your success function, you could simplify everything quite a bit in the following way while not using jQuery append so much, but just using a variable to store your code and then appending it in one go. This will allow you to append all sort of elements, it's easily parseable for the you and it reduces the amount of calls you have to make.
// Add whatever you want your final HTML to look like to this variable
var html = "<a href='http://localhost/laravel/public/index.php/utente/" + id_user + "' style='font-weight: bold;'>" + username + "</a>";
html += message;
// add an image
html += "<img src='path/to/image.jpg' />"
html += "<br />";
// append to code you constructed above in one go
$('#commentscontainer' + id_post).append(html);
Update
I amended an incorrect quote and changed + id_user + "to + id_user + "', which makes everything after it work.
I am attempting to access Google Books in order to an ISBN Code to get details of a book, I have a number of problem, which are:
A) I am trying to assemble a script request e.g. with the ISBN code concatenated into the URL. I have not managed to do this successfully - and I don't know why.
B) I then want to update a div in the DOM with this generated script dynamically, such that it will then execute.
C) I am finding it a bit of a puzzle as to the format of the returned data and the argument name of the function call contained in the Google response.
Has anyone else encountered the same problem and can offer guidance re A thru C above.
I enclose JavaScript code below.
$(document).ready(function() {
$('#viewbook-button').live('click', function() {
isbnCode = this.text;
alert("ISBN is : " + isbnCode + " " + this.text + " as well");
alert("Getting JSONP Google Books data");
isbnCode = "0451526538";
JSONPstr = '<' + 'script ' + 'src="' + 'https://www.googleapis.com/books/v1/volumes?q=ISBN' + isbnCode;
JSONPstr = JSONPstr + '&callback=handleJSONPResponse">' + '</script>';
alert("un-Escaped JSONP string" + JSONPstr);
escJSONPstr = escape( escJSONPstr );
alert("Escaped JSONP string");
//divstr = "";
//divstr = divstr + escape(<script src=");
//divstr = divstr + encodeURIComponent(https://www.googleapis.com/books/v1/volumes?q=ISBN);
//divstr = divstr + escape(isbnCode);
//divstr = divstr + encodeURIComponent(&callback=handleJSONPResponse);
//divstr = divstr + escape("></);
//divstr = divstr + escape(script);
//divstr = divstr + escape(>);
$('#jsonp-call').html(escJSONPstr);
// This will cause the handleJSONPResponse function to execute when the script is dynamically loadedinto div.
// The data wrapped in a function call will be returned from the Google Books server.
// This will cause the handleJSONPResponse function to execute below.
}); // end viewbook-button
}); // end document.ready
function handleJSONPResponse(response) {
var tmp = response;
alert(tmp);
};
</script>
</head>
<body>
<h2>Show Details of Books Ordered by a Customer</h2>
Get Customer Details
<br/><br/>
<div id="tablist">Tables will be Listed Here</div>
<br/><br/>
<div id="Google-call">The JSONP generated src= statement will go here and execute</div>
</body>
</html>
EDIT:
Problem solved - thanks everyone.
You're reinventing the wheel: jQuery has built-in JSONP support, so you don't need to faff about implementing it yourself. Use the $.ajax method:
$.ajax({
url: 'https://www.googleapis.com/books/v1/volumes?q=ISBN' + isbnCode,
dataType: 'jsonp',
success: function(response) {
console.log(response); // log the response object to the console
}
});
That should be all you need to do.
I'm posting ckeditor content via Ajax to php. But getting 4-5 sentence of posted material in my db table. I wonder, Is there any size limitation for ajax post? is there any way to post big text contents via ajax?
My js looks like that
function postViaAjax(autosaveMode) {
var name = $("#name").val();
var title = $("#title").val();
var menu = $("#menu").val();
var parentcheck = $(".parentcheck:checked").val();
var id = $("#id").val();
if (parentcheck == 0) {
var parent = parentcheck;
} else {
var parent = $("#parent").val();
}
var content = CKEDITOR.instances['content'].getData();
var dataString = 'name=' + name + '&title=' + title + '&menu=' + menu + '&parentcheck=' + parentcheck + '&id=' + id + '&parent=' + parent + '&content=' + content;
$.ajax({
type: "POST",
url: "processor/dbadd.php",
data: dataString,
dataType: "json",
success: function (result, status, xResponse) {
var message = result.msg;
var err = result.err;
var now = new Date();
if (message != null) {
if (autosaveMode) {
$('#submit_btn').attr({
'value': 'Yadda saxlanıldı ' + now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds()
});
} else {
$.notifyBar({
cls: "success",
html: message + ' ' + now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds()
});
}
}
if (err != null) {
$.notifyBar({
cls: "error",
html: err
});
}
}
});
};
The HTTP specification doesn't impose a specific size limit for posts. They will usually be limited by either the web server or the programming technology used to process the form submission.
What kind of server do you use?
There isn't any size limitation for POSTs in HTTP.
Maybe you have an & in your content variable. Then everything after that would be stripped after that.
Other than that what type do you use for your data column in the database? Is it, by any chance, something like varchar(1000)? Then anything bigger would also get stripped.
Check what you actually receive on the server end, so you know if you've got a problem with the code or the database.
You have a limitation on the Apache server. Look for LimitRequestBody directive.
This may be helpful:
http://gallery.menalto.com/node/14870
In theory the limits on AJAX requests are the same on all the other requests, so it depends on your web server/app setup. See also Max length of send() data param on XMLHttpRequest Post