Consume REST Service with Javascript/HTML - javascript

Below is code I use to get data from a SharePoint List with Javascript. What would I need to do to get it work on a site like JS Bin or JS Fiddle with an open/free REST service? (Like iextrading.com?)
<script type="text/javascript">
function getCompanies () {
var call = $.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Bills')/items?$select=AccountNumber&$orderby=AccountNumber&$filter=(PackageID eq '" + pid + "')",
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
});
call.success(function (data,textStatus, jqXHR){
$("#ResultsDiv").empty();
for (var i = 0; i < data.d.results.length; i++)
{
var item = data.d.results[i];
$("#ResultsDiv").append(item.AccountNumber + "<br/>");
}
});
call.fail(function (jqXHR,textStatus,errorThrown){
alert("Error retrieving Account Numbers: " + jqXHR.responseText);
});
}
</script>
<button onclick="getCompanies(); return false;" type="button">Get Item</button>
<hr width="50px" />
<div id="ResultsDiv"></div>
I looked at several examples on SO, but I couldn't get them to work on JS Bin or JS Fiddle.

I guess I worded my question poorly, because my original code was close to the answer.
function getMovies () {
var call = $.ajax({
url: "https://www.omdbapi.com/?i=tt3896198&apikey=[yourKeyHere]",
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
});
call.success(function (data,textStatus, jqXHR){
$("#ResultsDiv").empty();
$("#ResultsDiv").append(data.Title);
});
call.fail(function (jqXHR,textStatus,errorThrown){
alert("Error retrieving data: " + jqXHR.responseText);
});
}

Related

How to access id of the modal globally using JavaScript Laravel Laravel

I'm have an html table with modal column (see image below for your reference)
Upon click the Order modal, I can access the its ID using onclick event in JavaScript
(var customer_id = $(this).val();)
I wanted to access and used it in my Add function using ajax but I'm having an error of "customer_id is not defined" when I tried to use it. Is there a way to fix it or do it properly.
This is my script
<script>
$(document).ready(function () {
// START OPEN CART MODAL FUNCTION
$(document).on('click', '.viewCart', function (e) {
e.preventDefault();
var customer_id = 0;
var customer_id = $(this).val();
console.log(customer_id);
$.ajax({
type: "GET",
url: "/get-cart/"+customer_id,
dataType: "json",
success: function (response) {
if (response.data != null) {
console.log(response);
$('.OrderTbody').html("");
$.each(response.data, function (key, item) {
$('.OrderTbody').append('<tr>\
<td>' + item.p_name + '</td>\
<td>' + item.c_qty + '</td>\
<td class="total">' + item.p_amt + '</td>\
<td><button type="button" value="' + item.c_id + '" class="btn btn-danger deleteListBtn btn-sm">Delete</button></td>\
\</tr>');
});
}
}
});
});
// END OPEN CART MODAL FUNCTION
// START ADD DATA FUNCTION
$(document).on('click', '.addToCart', function (e) {
e.preventDefault();
var data = {
'store': $('.sel_store').val(),
'product': $('.sel_product').val(),
'quantity': $('.sel_qty').val(),
// HOW TO INPUT Customer ID here, I tried this but im having an error of
// customer_id is not defined
'customer_id': customer_id,
}
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: "/cart-list",
data: data,
dataType: "json",
success: function (response) {
}
});
});
// END ADD DATA FUNCTION
});
</script>

How do I pass the parameter of whichever list object I click on?

$.ajax({
url: "/userList",
type: "GET",
success: function(data){
console.log(data);
if (!data) alert("ERROR")
else{
for (let j=0;j<data.length;j++) {
user = data[j];
console.log(data[j]);
$("#userList").append("<button> <a href='javaScript:getUserProfile(" + data[j] + ")'>" + data[j] + "</button>");
}
}
} ,
dataType: "json"
});
It keeps saying data[j] is undefined whenever i try to pass it in. I have done print statements and such but I can't find the root of the issue.
Can you try this?
$.ajax({
type: "GET",
url: "/userList",
dataType: 'json',
success: function(data){
if (!data)
alert("ERROR")
else{
for (j=0;j<data.length;j++) {
var user = data[j];
console.log(user);
$("#userList").append("<button> <a href='javaScript:getUserProfile(" + user + ")'>" + user + "</button>");
}
}
}
});
Also, make sure that the url is correct. Looks like is not correct....

How can i load data from ajax to Chosen jquery?

I have use chosen at http://harvesthq.github.io/chosen/ . Ok, i testing it load data from ajax . I founding anywhere, maybe no someone success with them.
<script src="theme/js/jQuery-2.1.3.min.js"></script>
<link href="theme/chosen_v1.4.2/chosen.css" rel="stylesheet" />
<script src="theme/chosen_v1.4.2/chosen.jquery.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function () {
$(".cb_bu_info").chosen({
width: "95%",
source: function (data) {
$.ajax({
type: "POST",
url: "../BUS/WebService.asmx/LIST_BU",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#cb_info").html('');
//$.each($.parseJSON(data.d), function (idx, obj) {
$.each(data, function (idx, obj) {
$("#cb_info").append('<option value="' + obj.BU_ID + '">' + obj.BU_NAME + '</option>');
});
//$("#cb_info").trigger("liszt:updated");
},
error: function (data) {
console.log(data.d);
}
});
}
});
$("#cb_info").trigger("liszt:updated");
});
</script>
<select id="cb_info" class="cb_bu_info"></select>
The data form ajax as
[{"BU_ID":"B01","BU_NAME":"Agro Feed","BU_DES":"Agro Feed","EDIT_DATE":"2015-05-05T00:00:00","EDIT_BY":"","FLAG":false},{"BU_ID":"B02","BU_NAME":"Agro Farm","BU_DES":"Agro Farm","EDIT_DATE":"2015-05-05T00:00:00","EDIT_BY":"","FLAG":false}]
Well , it's look ok , but when i run it , result not show in select option, see browser dev tool , I've not seen error. Anything is ok.What's the problem happen in here? Notes: only use Chosen Jquery
After checking out the Chosen docs, there seems to not be a "source" option. What you need to do is first run your Ajax call, then fill your select options. Once the select is all filled, then run Chosen on that select element.
I would use the following JS code:
var url = "../BUS/WebService.asmx/LIST_BU";
$.getJSON(url, function(json){
var $select_elem = $("#cb_info");
$select_elem.empty();
$.each(json, function (idx, obj) {
$select_elem.append('<option value="' + obj.BU_ID + '">' + obj.BU_NAME + '</option>');
});
$select_elem.chosen({ width: "95%" });
})
Ok, After some time with the help of suggestions from everybody, I have done
function load_cb_info() {
$.ajax({
type: "POST",
url: "../BUS/WebService.asmx/LIST_BU",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#cb_info").html('');
$.each($.parseJSON(data.d), function (idx, obj) {
//$.each(data, function (idx, obj) {
$("#cb_info").append('<option value="' + obj.BU_ID + '">' + obj.BU_NAME + '</option>');
});
$("#cb_info").trigger("liszt:updated");
$("#cb_info").chosen({ width: "95%" });
},
error: function (data) {
console.log(data.d);
}
});
}
And , I think this is an answer and everyone else can find it .Thank you.
I have changed your jsfiddle. Try this out http://jsfiddle.net/GaganJaura/by4d528c/2/
I have moved the chosen() to bottom.
$("#cb_info").empty();
$.each(data, function (idx, obj) {
$("#cb_info").append('<option value="' + obj.BU_ID + '">' + obj.BU_NAME + '</option>');
});
$("#cb_info").trigger("liszt:updated");
$("#cb_info").chosen();
You can try as follows it works for me
$.ajax({
type: "POST",
url: url,
data: formData,
processData: false,
contentType: false,
success:function(data){
if($.trim(data) != "no"){
$("#PROGRAM_ID").html(data);
$("#PROGRAM_ID").trigger("chosen:updated");
}
}
});
try this. it works for me. please pay attention to the bold text
Ext.Ajax.request({
url:'<?php echo base_url()."index.php/";?>ttemuan31a/cari_divisi',
method:'post',
params:{
divisi:vdivisi
},
success:function(data)
{
$("#divisi").chosen();
//document.getElementById('detail_divisi').innerHTML=response.responseText;
$('#divisi').empty();
$.each(JSON.parse(**data.responseText**), function(i, item) {
$('#divisi').append('<option value="'+item.id+'">'+item.namadivisi+'</option>');
$("#divisi").trigger("chosen:updated");
});
}
});
}

Json data from Guardian API

I have a guardian json data feed that I want to pull into my page online.
http://content.guardianapis.com/world/cuba?format=json&show-fields=trail-text%2Cheadline&order-by=newest&api-key=c3rr449rqqebmuxua9k5mdcz
I have used this javascript but nothing seems to be working to grab the right content from the json;
$(document).ready(function() {
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "http://content.guardianapis.com/world/cuba?format=json&show-fields=trail-text%2Cheadline&order-by=newest&api-key=c3rr449rqqebmuxua9k5mdcz",
success: function(data) {
for (var i = 0; i < 12; i++) {
$("#cuban-news").append("<div class='guardian'><a target='_blank' href='" + webTitle + "'>Link</a></div>");
}
console.log(data);
}
});
});
This is not throwing anything in terms of errors.
Am I better using a js service like backbone or underscore?
Any help would be amazing on this.
Use
data.response.results[i].webTitle
instead of
webTitle
error was
Uncaught ReferenceError: webTitle is not defined
$(document).ready(function() {
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "http://content.guardianapis.com/world/cuba?format=json&show-fields=trail-text%2Cheadline&order-by=newest&api-key=c3rr449rqqebmuxua9k5mdcz",
success: function(data) {
for (var i = 0; i < data.response.results.length; i++) {
$("#cuban-news").append("<div class='guardian'><a target='_blank' href='"
+ data.response.results[i].webTitle + "'>Link</a></div>");
}
console.log(data);
}
});
});​
JSFiddle

Error: $.ajax is not a function

Am getting a error like that, $ajax is not working
<script type="text/javascript">
$(document).ready(function () {
$("#btnsubmit").click(function () {
$.ajax({
type: "POST",
url: "loginform.aspx/getdataval",
data: "{'uname':'" + $("#TextBox1").val() + "','passwod':'" + $("#TextBox2").val() + "'}",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (msg) {
alert("welcome");
AjaxSucceeded(msg);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("what is the problem")
}
});
});
});
function AjaxSucceeded(result) {
alert(result.d);
var Emp = result.d;
$("#output").append('<p>' + Emp.Sname + ' ' + Emp.Sno + '</p>');
}
</script>
$ ajax not a function why? When I run this script I get error, it not running, what is the problem?
Thanks
You may have an issue with the single/doule quotes on the data string as the JSON standard says double quotes.
You can also simplify the contentType.
I tend to simplify my use of the .d in asp.net by including a converter and the ajax itself using ajaxSetup like so: (Note that using a converter like this works in jQuery 1.5 forward due to that syntax. Feel free to refactor out the ajaxSetup if you prefer but I find it helps me as I only have to do it once when I have multiple ajax calls.)
$(document).ready(function() {
$.ajaxSetup({
data: "{}",
dataType: "json",
type: "POST",
contentType: "application/json",
converters: {
"json jsond": function(msg) {
return msg.hasOwnProperty('d') ? msg.d : msg;
}
},
error: function(xhr, textStatus, errorThrown) {
var errorMessage = "Ajax error: " + this.url
+ " : " + textStatus + " : " + errorThrown
+ " : " + xhr.statusText + " : " + xhr.status;
alert(errorMessage);
if (xhr.status != "0" || errorThrown != "abort") {
alert(errorMessage);
}
}
});
$("#btnsubmit").click(function() {
var pString = '{"uname":"'
+ $("#TextBox1").val() + '","passwod":"'
+ $("#TextBox2").val() + '"}';
$.ajax({
url: "loginform.aspx/getdataval",
data: pString,
success: function(msg) {
alert("welcome");
AjaxSucceeded(msg);
}
});
});
});
// converter gives us the result instead of the .d here
function AjaxSucceeded(result) {
alert(result);
var Emp = result;
$("#output").append('<p>' + Emp.Sname + ' ' + Emp.Sno + '</p>');
}
EDIT: as of jQuery 1.9, you should bind the ajax setup as such:
$(document).ajaxSetup({..more code

Categories

Resources