Reading WordPress REST API JSON data via Ajax showing blank screen - javascript

I'm trying to pull data in my hybrid app through wordpress rest api. But I'm getting a blank screen. No error msg is thrown. Just a blank screen is coming. I have checked for syntactical error in lint and there's no error in code. I'm using the following code:
var BASE_URI = "https://public-api.wordpress.com/rest/v1.1/sites/smushbits.com/";
var POST_OFFSET = 0;
function load_post() {
$.ajax({
url: BASE_URI + "posts",
type: "GET",
dataType: "json",
data: {
"number": 10 ,
"offset": POST_OFFSET
},
error: function() {
alert("An error occured.");
},
success: function(response) {
$.each(response, function(index, data) {
$('<li><h1>'+data.posts[index].title+'</h1><p>'+getDays(data.posts[index].date)+'</p></li>').appendTo('#latest-list');
$(document).on("click", "#"+data.posts[index].ID, function() {
get_single_post(data.posts[index].title, data.posts[index].date, data.posts[index].URL, data.posts[index].content);
});
});
$('#latest-list').listview('refresh');
}
});
POST_OFFSET+=10;
}
$(document).ready(function(){
load_post();
});
Demo: http://smushbits.com/smushbits/www

Related

How to autocomplete an input from and API url on wordpress?

I am trying to make a request on an API, from an input. I want to autocomplete airport,cities suggestions etc.
I need to do this on Wordpress and i keep getting an error. This is what i did:
$(function() {
$("#autocompletedep").autocomplete({
source: function(request, response) {
$.ajax({
url: "https://www.fly-go.ro/ajax_autocomplete_flight?temp=",
dataType: "json",
data: {
q: request.term
},
success: function(data) {
var user = new String()
user = data.Title;
for (i = 0; i < user.length; i++) {
$('#autocompletedep')
.append($('<option>', { value: user[i] })
.text(user[i]));
}
}
});
},
});
});
I am not sure if i am doing the right way.
The error is:
flight-search.js?ver=5.3:1 Uncaught TypeError: $ is not a function
at flight-search.js?ver=5.3:1
Any help would be very appreciated, thank you!

Access object properties - Ajax Call

I have simple AJAX call.
It looks like this:
myApp.onPageInit('about', function (page) {
search_term = $$("#search_term").val();
const key = "xxxx-xxxx";
const nick = "https://api.xxx.xxx/" + search_term + "?api_key=" + key;
$$.ajax({
url:nick,
type:'GET',
dataType: JSON,
beforeSend: function(){
//myApp.showPreloader('Please wait...');
},
success: function(data) {
//myApp.hidePreloader();
console.log(data);
console.log(data['summonerLevel']);
},
statusCode: {
404: function() {
// myApp.alert('Account does not exist.', 'ERROR');
}
},
error: function(data) {
myApp.alert('Account does not exist.', 'ERROR');
// ak je ovaj error, netko je dirao putanju - fajl
},
});
})
When I'm trying to get properties from data object, every time it says undefined.
Console log: {"id":"xxxx","accountId":"xxxx","puuid":"xxxx","name":"Data","profileIconId":3015,"revisionDate":1546082318000,"summonerLevel":37}
Second console log: undefined
I tried dot notation and bracket notation, but everytime same status(undefined).
Like this:
console.log(data['summonerLevel']);
console.log(data.summonerLevel);
Any suggestion for this problem?
use JSON.Parse() method and try taking the value with object.attributename
$.ajax({
url:nick,
type:'GET',
dataType: JSON,
beforeSend: function(){
},
success: function(data) {
var data=JSON.Parse(data);
console.log(data.summonerLevel);
console.log(data.accountId);
},
statusCode: {
404: function() {
}
},
error: function(data) {
},
});

JSON object is undefined in ajax call

In my Django project I'm trying to create a page that constantly displays the current state of a certain field in a database. I'm using ajax to do that but for reason the response object I'm returning keeps coming back as undefined.
Here is my view:
def call_ajax(request):
if request.is_ajax():
userp = UserProfile.objects.get(user=request.user)
accepted = userp.recent_call.accepted
hello = "hello"
ajax_vars = {
'accepted':accepted,
'hello':hello,
}
return JsonResponse(ajax_vars)
Here is the relevant javascript:
$(document).ready(function(response){
ajax_call(response);
});
function ajax_call(response){
$.ajax({
type: 'GET',
url: '/calls/call_ajax/',
dataType: 'json',
async: true,
data: {
accepted: response.accepted,
hello: response.hello,
},
success: function(response) {
console.log(response.hello)
$('#info').html('<p>'+response.hello+'</p>');
},
error: function() {
$('#info').html('<p>An error has occurred</p>');
}
});
setInterval(function() { ajax_call(response); },10000)
}
For some reason the console is logging that the response object is undefined. Any tips?

Dotnetnuke Call ajax from a module

I am now trying to build a dnn module using ajax calls. But there is a jquery error stating
SyntaxError: Unexpected token <
I have tried to work around with ajax "url: " and tried to create a new ascx at the root folder but still showing error 404.
My ajax call is as below
$.ajax({
url: "NewsManagement.ascx/Add",
contentType: "application/json; charset=utf-8",
dataType: "json",
method: "POST",
beforeSend: function () {
},
cache: false,
data: {
title : $('#txt_Title').val(),
news_content : $('#txt_Content').val(),
image : $('#file_Image').val(),
chapter_id : $('#sel_Chapter').val(),
is_draft : $('#chk_Draft').val(),
posted_date : $('#dp_PostDate').val(),
created_by : "",
lastupdate_by : ""
},
success: function (data) {
console.log(data);
if (data == "success") {
console.log(data);
}
else {
initMdlError("SERVER : " + data);
}
},
error: function (data, textStatus, error) {
// ERROR IS BEING CALLED FROM HERE
console.log("JQUERY JAVASCRIPT : " + error);
initMdlError(error);
},
complete: function () {
console.log('complete');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Is there any way to solve the issues?
The problem you're running into is that DNN isn't handling the requested URL properly that you are calling. If you want to call a service URL in DNN you're going to want to setup routes to handle the calls.
namespace Christoc.Com.Modules.SlidePresentation.services
{
public class SlidePresentationRouteMapper : IServiceRouteMapper
{
public void RegisterRoutes(IMapRoute mapRouteManager)
{
mapRouteManager.MapRoute("SlidePresentation", "{controller}.ashx/{action}",
new[] {"Christoc.Com.Modules.SlidePresentation.services"});
}
}
}
In the Controller you can define the methods available
[DnnAuthorize(AllowAnonymous = true)]
public ActionResult ListOfSlides()
{
try
{
var slides = Slide.GetSlides(ActiveModule.TabID, ActiveModule.ModuleID);
return Json(slides, JsonRequestBehavior.AllowGet);
}
catch (Exception exc)
{
DnnLog.Error(exc);
return Json(null, JsonRequestBehavior.AllowGet);
}
}
https://slidepresentation.codeplex.com/SourceControl/latest#DesktopModules/SlidePresentation/services/SlidePresentationController.cs
sample Javascript
//get slides on initialization
this.init = function(element) {
//var data = {}; //removed because we don't need this
//data.moduleId = moduleId; //removed because we don't need this when calling setModuleHeaders
//data.tabId = tabId; //removed because we don't need this
//serviceFramework.getAntiForgeryProperty(); //removed because we don't need this
$.ajax({
type: "POST",
cache: false,
url: baseServicePath + 'ListOfSlides',
//data: data,
//dataType:"json",
beforeSend: serviceFramework.setModuleHeaders
}).done(function(data) {
viewModel.slides = ko.utils.arrayMap(data, function(s) {
return new slide(s);
});
ko.applyBindings(viewModel);
$(element).jmpress();
}).fail(function () {
Console.Log('Sorry failed to load Slides');
});
};
Here's an example module that does this
https://slidepresentation.codeplex.com/
And a user group video I did years ago on this module.
https://www.youtube.com/watch?v=hBqn5TsLUxA

jQuery autocomplete using data pulled from SharePoint list using ajax REST

I need to add autocomplete to an input textbox. The data needs to be fetched from SharePoint using AJAX / REST.
This what I've done so far:
JS
var myData = [];
var requestHeaders = {
"accept": "application/json;odata=verbose"
}
$.ajax({
url: "https://my-URL/sites/RMA-GFPLC/_api/web/lists/GetByTitle('AD_DB')/items? $select=Title,Regional_x0020_Office,Commodity,Commodity_x0020_Year,StateLookUp/Title&$expand=StateLookUp",
type: 'GET',
dataType: 'json',
async: false,
headers: requestHeaders,
success: function (data) {
$.each(data.d.results, function (i, result) {
myData.push(result.Title);
});
myDataSource(myData);
},
error: function ajaxError(response) {
alert(response.status + ' ' + response.statusText);
}
});
function myDataSource(myData){
$('#myAutoCompleteSearch').autocomplete({
source: myData,
minLength: 3
});
}
So far my code is not working, and I'm getting "Uncaught TypeError: Cannot read property 'label' of null " error in my console. I;m wonder what am I doing wrong here? Thanks!
This error occurs when a source for Autocomplete function contains an element(s) with a null value.
Solution
Add the condition for checking if value is not null:
$.each(data.d.results, function (i, result) {
if(result.Title) {
myData.push(result.Title);
}
});
Jast insert your code in
$(document).ready(function () {
//your code here
}

Categories