Below is an AJAX function I'm trying to use to show a loader gif during the request and hide when successful. Basically I started out with the function inside of the response.success which used to work by itself. It creates short urls and sets it to the value of an input field. And I was shown the rest that wraps that function, but i'm getting a 404 error in the console for failure to load resource. I'm sure this is a straightforward answer, I'm too new to tell but I think I'm close. Any help is much appreciated, thanks.
function getShare(url)
{
$('#loader').show(); // show loading...
$.ajax({
dataType: "jsonp",
jsonpCallback:'apiCallback', // this will be send to api as ?callback=apiCallback because this api do not want to work with default $ callback function name
url: 'http://b1t.co/Site/api/External/MakeUrlWithGet',
data: {'url':url},
success: function(response){
$('#loader').hide(); // hide loading...
//respponse = {success: true, url: "http://sdfsdfs", shortUrl: "http://b1t.co/qz"}
if(response.success){
{
var s = document.createElement('script');
var browserUrl = document.location.href;
//alert(browserUrl);
if (browserUrl.indexOf("?") != -1){
browserUrl = browserUrl.split("?");
browserUrl = browserUrl[0];
}
//alert(browserUrl);
var gifUrl = $('#gif_input').value;
var vidUrl = $('#vid_input').value;
//alert(gifUrl + "|" + vidUrl);
url = encodeURIComponent(browserUrl + "?gifVid=" + gifUrl + "|" + vidUrl);
//alert(encodeURIComponent("&"));
s.id = 'dynScript';
s.type='text/javascript';
s.src = "http://b1t.co/Site/api/External/MakeUrlWithGet?callback=resultsCallBack&url=" + url;
document.getElementsByTagName('head')[0].appendChild(s);
}
function resultsCallBack(data)
{
var obj = jQuery.parseJSON(JSON.stringify(data));
$("#input-url").val(obj.shortUrl);
}
}
},
error:function(){
$('#loader').hide();
}
});
}
Related
PHP/HTML:
<ul id="load-more-div"></ul>
<a id="load-more" data-ppp="<?php echo get_option('posts_per_page'); ?>">load more</a>
JavaScripts:
(function($) {
// Grab the load more button, since I only want to run the code if the button is on the page
var loadMoreButton = $("#load-more");
if (loadMoreButton) {
// Get the posts_per_page number set in Reading Options
var ppp = loadMoreButton.data("ppp");
// Initialize function
var loadPosts = function(page) {
var theData, loadMoreContainer, errorStatus, errorMessage;
// The AJAX request
$.ajax({
url: "/wp-json/wp/v2/posts",
dataType: "json",
data: {
// Match the query that was already run on the page
per_page: ppp,
page: page,
type: "post",
orderby: "date"
},
success: function(data) {
// Remove the button if the response returns no items
if (data.length < 1) {
loadMoreButton.remove();
}
// Create a place to store exactly what I need
// Alternatively, the response can be filtered to only return the needed data, which is probably more efficient as the following loop wont be needed
theData = [];
// Get only what I need, and store it
for (i = 0; i < data.length; i++) {
theData[i] = {};
theData[i].id = data[i].id;
theData[i].link = data[i].link;
theData[i].title = data[i].title.rendered;
theData[i].content = data[i].content.rendered;
}
// Grab the container where my data will be inserted
loadMoreContainer = $("#load-more-div");
// For each object in my newly formed array, build a new element to store that data, and insert it into the DOM
$.each(theData, function(i) {
loadMoreContainer.append(
'<li><a href="' +
theData[i].link +
'">' +
theData[i].title +
"</a></li>"
);
});
},
error: function(jqXHR, textStatus, errorThrown) {
errorStatus = jqXHR.status + " " + jqXHR.statusText + "\n";
errorMessage = jqXHR.responseJSON.message;
// Show me what the error was
console.log(errorStatus + errorMessage);
}
});
};
// Since our AJAX query is the same as the original query on the page (page 1), start with page 2
var getPage = 2;
// Actually implement the functionality when the button is clicked
loadMoreButton.on("click", function() {
loadPosts(getPage);
// Increment the page, so on the next click we get the next page of results
getPage++;
});
}
})(jQuery);
This is the trouble part, it doesn't remove the link.
// Remove the button if the response returns no items
if (data.length < 1) {
loadMoreButton.remove();
}
Console errors when click the load more link after reaching the end of posts:
400 Bad Request The page number requested is larger than the number of pages available.
I found two ways to solve it:
###Using data attribute
Get the max number of pages in the template, assign it to a data attribute, and access it in the scripts. Then check current page against total page numbers, and set disabled states to the load more button when it reaches the last page.
PHP/HTML:
<ul id="ajax-content"></ul>
<button type="button" id="ajax-button" data-endpoint="<?php echo get_rest_url(null, 'wp/v2/posts'); ?>" data-ppp="<?php echo get_option('posts_per_page'); ?>" data-pages="<?php echo $wp_query->max_num_pages; ?>">Show more</button>
JavaScripts:
(function($) {
var loadMoreButton = $('#ajax-button');
var loadMoreContainer = $('#ajax-content');
if (loadMoreButton) {
var endpoint = loadMoreButton.data('endpoint');
var ppp = loadMoreButton.data('ppp');
var pages = loadMoreButton.data('pages');
var loadPosts = function(page) {
var theData, errorStatus, errorMessage;
$.ajax({
url: endpoint,
dataType: 'json',
data: {
per_page: ppp,
page: page,
type: 'post',
orderby: 'date'
},
beforeSend: function() {
loadMoreButton.attr('disabled', true);
},
success: function(data) {
theData = [];
for (i = 0; i < data.length; i++) {
theData[i] = {};
theData[i].id = data[i].id;
theData[i].link = data[i].link;
theData[i].title = data[i].title.rendered;
theData[i].content = data[i].content.rendered;
}
$.each(theData, function(i) {
loadMoreContainer.append('<li>' + theData[i].title + '</li>');
});
loadMoreButton.attr('disabled', false);
if (getPage == pages) {
loadMoreButton.attr('disabled', true);
}
getPage++;
},
error: function(jqXHR) {
errorStatus = jqXHR.status + ' ' + jqXHR.statusText + '\n';
errorMessage = jqXHR.responseJSON.message;
console.log(errorStatus + errorMessage);
}
});
};
var getPage = 2;
loadMoreButton.on('click', function() {
loadPosts(getPage);
});
}
})(jQuery);
###Using jQuery complete event
Get the total pages x-wp-totalpages from the HTTP response headers. Then change the button states when reaches last page.
PHP/HTML:
<ul id="ajax-content"></ul>
<button type="button" id="ajax-button" data-endpoint="<?php echo get_rest_url(null, 'wp/v2/posts'); ?>" data-ppp="<?php echo get_option('posts_per_page'); ?>">Show more</button>
JavaScripts:
(function($) {
var loadMoreButton = $('#ajax-button');
var loadMoreContainer = $('#ajax-content');
if (loadMoreButton) {
var endpoint = loadMoreButton.data('endpoint');
var ppp = loadMoreButton.data('ppp');
var pager = 0;
var loadPosts = function(page) {
var theData, errorStatus, errorMessage;
$.ajax({
url: endpoint,
dataType: 'json',
data: {
per_page: ppp,
page: page,
type: 'post',
orderby: 'date'
},
beforeSend: function() {
loadMoreButton.attr('disabled', true);
},
success: function(data) {
theData = [];
for (i = 0; i < data.length; i++) {
theData[i] = {};
theData[i].id = data[i].id;
theData[i].link = data[i].link;
theData[i].title = data[i].title.rendered;
theData[i].content = data[i].content.rendered;
}
$.each(theData, function(i) {
loadMoreContainer.append('<li>' + theData[i].title + '</li>');
});
loadMoreButton.attr('disabled', false);
},
error: function(jqXHR) {
errorStatus = jqXHR.status + ' ' + jqXHR.statusText + '\n';
errorMessage = jqXHR.responseJSON.message;
console.log(errorStatus + errorMessage);
},
complete: function(jqXHR) {
if (pager == 0) {
pager = jqXHR.getResponseHeader('x-wp-totalpages');
}
pager--;
if (pager == 1) {
loadMoreButton.attr('disabled', true);
}
}
});
};
var getPage = 2;
loadMoreButton.on('click', function() {
loadPosts(getPage);
getPage++;
});
}
})(jQuery);
The problem appears to be an invalid query to that endpoint so the success: function() is never being run in this circumstance.
Add to All API Errors
You could add the same functionality for all errors like this...
error: function(jqXHR, textStatus, errorThrown) {
loadMoreButton.remove();
....
}
Though that may not be the desired way of handling of all errors.
Test for Existing Error Message
Another option could be to remove the button if you receive an error with that exact message...
error: function(jqXHR, textStatus, errorThrown) {
if (jqXHR.statusText === 'The page number requested is larger than the number of pages available.') {
loadMoreButton.remove();
}
....
}
but this would be susceptible to breaking with any changes to that error message.
Return Custom Error Code from API
The recommended way to handle it would be to return specific error code (along with HTTP status code 400) to specify the exact situation in a more reliable format...
error: function(jqXHR, textStatus, errorThrown) {
if (jqXHR.statusCode === '215') {
loadMoreButton.remove();
}
....
}
Here's an example on how to configure error handling in an API: Best Practices for API Error Handling
Return 200 HTTP Status Code
The last option would be to change the way your API endpoint handles this type of "error"/situation, by returning a 200 level HTTP status code instead, which would invoke the success: instead of the error: callback instead.
I'd like to load items from an XML file and display them on a webpage via AJAX and limit the output via a date range. However I am struggling to pass the parameters to the anonymous function. All tries to hand over the parameter 'displayDateLimit' have ended in syntax errors. Any idea how to do this?
In addition to that: If do not pass the the parameter I get an incremented counter for inpTest instead. Why does this happen?
// loads XML to Div-Element.
function loadItemsToBox(id)
{
var boxElement = document.getElementById('someid');
if (!boxElement){ return;}
xmlUrl = 'someurl'];
displayDateLimit = new Date().getTime();
displayDateLimit -= 3600*1000;
$.ajax({
type: "GET",
url: xmlUrl,
dataType: "xml",
success: function (xml) {
var content = "";
$(xml).find("item").each(function (inpTest) { // or "item" or whatever suits your feed
var el = $(this);
content += "<p>";
content += el.find("title").text() + "<br>";
content += "<br>DateLimit: " + inpTest;
content += "</p>";
})(displayDateLimit);
boxElement.innerHTML = content;
},
error : function(xhr, textStatus, errorThrown )
{
// some errorhandling
}
});
}
How to get current user name using JavaScript in Script Editor web part?
Here is the code that worked for me:
<script src="/SiteAssets/jquery.SPServices-2013.02a.js" type="text/javascript"></script>
<script src="/SiteAssets/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
var userid= _spPageContextInfo.userId;
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";
var requestHeaders = { "accept" : "application/json;odata=verbose" };
$.ajax({
url : requestUri,
contentType : "application/json;odata=verbose",
headers : requestHeaders,
success : onSuccess,
error : onError
});
function onSuccess(data, request){
var loginName = data.d.Title;
alert(loginName);
}
function onError(error) {
alert("error");
}
</script>
I found a much easier way, it doesn't even use SP.UserProfiles.js. I don't know if it applies to each one's particular case, but definitely worth sharing.
//assume we have a client context called context.
var web = context.get_web();
var user = web.get_currentUser(); //must load this to access info.
context.load(user);
context.executeQueryAsync(function(){
alert("User is: " + user.get_title()); //there is also id, email, so this is pretty useful.
}, function(){alert(":(");});
Anyways, thanks to your answers, I got to mingle a bit with UserProfiles, even though it is not really necessary for my case.
If you are in a SharePoint Page just use:
_spPageContextInfo.userId;
How about this:
$.getJSON(_spPageContextInfo.webServerRelativeUrl + "/_api/web/currentuser")
.done(function(data){
console.log(data.Title);
})
.fail(function() { console.log("Failed")});
You can use the SharePoint JSOM to get your current user's account information. This code (when added as the snippet in the Script Editor web part) will just pop up the user's display and account name in the browser - you'll want to add whatever else in gotAccount to get the name in the format you want.
<script type="text/javascript" src="/_layouts/15/SP.js"></script>
<script type="text/javascript" src="/_layouts/15/SP.UserProfiles.js"></script>
<script type="text/javascript">
var personProperties;
SP.SOD.executeOrDelayUntilScriptLoaded(getCurrentUser, 'SP.UserProfiles.js');
function getCurrentUser() {
var clientContext = new SP.ClientContext.get_current();
personProperties = new SP.UserProfiles.PeopleManager(clientContext).getMyProperties();
clientContext.load(personProperties);
clientContext.executeQueryAsync(gotAccount, requestFailed);
}
function gotAccount(sender, args) {
alert("Display Name: "+ personProperties.get_displayName() +
", Account Name: " + personProperties.get_accountName());
}
function requestFailed(sender, args) {
alert('Cannot get user account information: ' + args.get_message());
}
</script>
See the SP.UserProfiles.PersonProperties documentation in MSDN for more info.
To get current user info:
jQuery.ajax({
url: _spPageContextInfo.webServerRelativeUrl + "/_api/web/currentuser",
type: "GET",
headers: { "Accept": "application/json;odata=verbose" }
}).done(function( data ){
console.log( data );
console.log( data.d.Title );
}).fail(function(){
console.log( failed );
});
U can use javascript to achive that like this:
function loadConstants() {
this.clientContext = new SP.ClientContext.get_current();
this.clientContext = new SP.ClientContext.get_current();
this.oWeb = clientContext.get_web();
currentUser = this.oWeb.get_currentUser();
this.clientContext.load(currentUser);
completefunc:this.clientContext.executeQueryAsync(Function.createDelegate(this,this.onQuerySucceeded), Function.createDelegate(this,this.onQueryFailed));
}
//U must set a timeout to recivie the exactly user u want:
function onQuerySucceeded(sender, args) {
window.setTimeout("ttt();",1000);
}
function onQueryFailed(sender, args) {
console.log(args.get_message());
}
//By using a proper timeout, u can get current user :
function ttt(){
var clientContext = new SP.ClientContext.get_current();
var groupCollection = clientContext.get_web().get_siteGroups();
visitorsGroup = groupCollection.getByName('OLAP Portal Members');
t=this.currentUser .get_loginName().toLowerCase();
console.log ('this.currentUser .get_loginName() : '+ t);
}
I had to do it using XML, put the following in a Content Editor Web Part by adding a Content Editor Web Part, Edit the Web Part, then click the Edit Source button and paste in this:
<input type="button" onclick="GetUserInfo()" value="Show Domain, Username and Email"/>
<script type="text/javascript">
function GetUserInfo() {
$.ajax({
type: "GET",
url: "https://<ENTER YOUR DOMAIN HERE>/_api/web/currentuser",
dataType: "xml",
error: function (e) {
alert("An error occurred while processing XML file" + e.toString());
console.log("XML reading Failed: ", e);
},
success: function (response) {
var content = $(response).find("content");
var spsEmail = content.find("d\\:Email").text();
var rawLoginName = content.find("d\\:LoginName").text();
var spsDomainUser = rawLoginName.slice(rawLoginName.indexOf('|') + 1);
var indexOfSlash = spsDomainUser.indexOf('\\') + 1;
var spsDomain = spsDomainUser.slice(0, indexOfSlash - 1);
var spsUser = spsDomainUser.slice(indexOfSlash);
alert("Domain: " + spsDomain + " User: " + spsUser + " Email: " + spsEmail);
}
});
}
</script>
Check the following link to see if your data is XML or JSON:
https://<Your_Sharepoint_Domain>/_api/web/currentuser
In the accepted answer Kate uses this method:
var userid= _spPageContextInfo.userId;
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")
you can use below function if you know the id of the user:
function getUser(id){
var returnValue;
jQuery.ajax({
url: "http://YourSite/_api/Web/GetUserById(" + id + ")",
type: "GET",
headers: { "Accept": "application/json;odata=verbose" },
success: function(data) {
var dataResults = data.d;
alert(dataResults.Title);
}
});
}
or you can try
var listURL = _spPageContextInfo.webAbsoluteUrl + "/_api/web/currentuser";
try this code..
function GetCurrentUsers() {
var context = new SP.ClientContext.get_current();
this.website = context.get_web();
var currentUser = website.get_currentUser();
context.load(currentUser);
context.executeQueryAsync(Function.createDelegate(this, onQuerySucceeded), Function.createDelegate(this, onQueryFailed));
function onQuerySucceeded() {
var currentUsers = currentUser.get_title();
document.getElementById("txtIssued").innerHTML = currentUsers;
}
function onQueryFailed(sender, args) {
alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
}
}
You can use sp page context info:
_spPageContextOnfo.userLoginName
After searching here on SO and google, didn't find an answer to my problem.
The animation doesn't seem to trigger, tried a simple alert, didn't work either.
The function works as it is supposed (almost) as it does what i need to, excluding the success part.
Why isn't the success event being called?
$(function() {
$(".seguinte").click(function() {
var fnome = $('.fnome').val();
var fmorada = $('.fmorada').val();
var flocalidade = $('.flocalidade').val();
var fcodigopostal = $('.fcodigopostal').val();
var ftelemovel = $('.ftelemovel').val();
var femail = $('.femail').val();
var fnif = $('.fnif').val();
var fempresa = $('.fempresa').val();
var dataString = 'fnome='+ fnome + '&fmorada=' + fmorada + '&flocalidade=' + flocalidade + '&fcodigopostal=' + fcodigopostal + '&ftelemovel=' + ftelemovel + '&femail=' + femail + '&fnif=' + fnif + '&fempresa=' + fempresa;
$.ajax({
type: "GET",
url: "/ajaxload/editclient.php",
data: dataString,
success: function() {
$('.primeirosector').animate({ "left": "+=768px" }, "fast" );
}
});
return false;
});
});
you are trying to pass query string in data it should be json data.
Does your method edit client has all the parameters you are passing?
A simple way to test this is doing the following:
change this line to be like this
url: "/ajaxload/editclient.php" + "?" + dataString;
and remove this line
data: dataString
The correct way of doing it should be, create a javascript object and send it in the data like so:
var sendData ={
fnome: $('.fnome').val(),
fmorada: $('.fmorada').val(),
flocalidade: $('.flocalidade').val(),
fcodigopostal: $('.fcodigopostal').val(),
ftelemovel: $('.ftelemovel').val(),
femail: $('.femail').val(),
fnif: $('.fnif').val(),
fempresa: $('.fempresa').val()
}
$.ajax({
url: "/ajaxload/editclient.php",
dataType: 'json',
data: sendData,
success: function() {
$('.primeirosector').animate({ "left": "+=768px" }, "fast" );
}
});
Another thing shouldn't this be a post request?
Hope it helps
I have a javascript function which executes on the change of a dropdown:
<script type="text/javascript">
$(function()
{
// Executes when the status dropdown changes value
$('select[name="status_dropdown"]').change(function(event)
{
var $this = $(event.target);
var orderId = $this.closest('tr').children('td:eq(0)').text(); // index 0 refers to the "order_id column" in the table
var result = null;
var scriptUrl = "ajax_php/update_status.php?order_id=" + orderId + "&status_id=" + this.value;
$.ajax(
{
url: scriptUrl,
type: 'get',
dataType: 'html',
async: false,
success: function(data)
{
result = data;
alert(result);
}
});
});
})
</script>
I am trying to get the alert call to show the return value of the following php code (which is true):
<?php
.
.
.
return true;
?>
The alert doesn't pop up. Anyone know why ???
I tried your code with another URL and it's working well.
There are three cases:
scriptUrl is not calculated properly and doesn't point to your PHP script
your server is down
you are accessing an URL not served under the same domain as the one of your script (same-origin policy)
You can see detail of your error if you add an error handler to ajax parameters :
error : function(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
Return only returns a value within the php script - to output it to ajax you need to actually output the result to the page, in this case something like echo "true"; or print("true");
Try this
$(document).ready(function(){
$('select[name="status_dropdown"]').change(function(event)
{
var $this = $(event.target);
var orderId = $this.closest('tr').children('td:eq(0)').text(); // index 0 refers to the "order_id column" in the table
var result = null;
var scriptUrl = "ajax_php/update_status.php?order_id=" + orderId + "&status_id=" + this.value;
$.ajax(
{
url: scriptUrl,
type: 'get',
dataType: 'html',
async: false,
success: function(data)
{
result = data;
alert(result);
}
});
});
});