returning another page's variables using AJAX - javascript

I am using AJAX to try and return list items. The list items are stored on another page as a var. The var is called WPQListData. This var is viewable in the page source.
var WPQ2ListData = { "Row" :
[{
"ID": "1",
"PermMask": "0x7fffffffffffffff",
"FSObjType": "0",
"Title": "test",
"FileLeafRef": "1_.000",
"Created_x0020_Date.ifnew": "",
"FileRef": "\u002fsites\u002fResilient\u002fLists\u002fNewsSliderList\u002f1_.000",
"File_x0020_Type": "",
"File_x0020_Type.mapapp": "",
"HTML_x0020_File_x0020_Type.File_x0020_Type.mapcon": "",
"HTML_x0020_File_x0020_Type.File_x0020_Type.mapico": "icgen.gif",
"ContentTypeId": "0x0100B87D22D691BA4B419255256292F918AA00B2962D0F358E9442AFF496C5DFF6AB1F",
"Body1": "test"
}
Id like to get this variable using AJAX. I'm currently trying the following:
$.ajax({
url: ctx.HttpRoot+"/Lists/NewsSliderList/AllItems.aspx",
type: "GET",
success: function (data) {
var dataDom = $(data);
var stripped_data = $(dataDom).find("WPQ2ListData");
},
error: function () {
// your error logic
alert("AJAX failed");
}
})
Is it possible to get Vars via AJAX, and if so then what am i doing wrong?
thanks

Related

How do I place a json value using jquery?

I am sending selected fields to an API(3rd party app) from wordpress.
This is how my data array looks like:
var data_array = {
"order": {
"customer": {
"name": "The User"
}
}
}
I want to substitute the value of the "name" key to a javascript variable that contains a jquery selector. For example:
var name = j('.billing_company_name').html(result.meta_data[1].value);
I am thinking that the new code for the data_array will be:
var data_array = {
"order": {
"customer": {
"name": name(variable name jquery selector)
}
}
}
Do you know the correct syntax so I can substitute the value of "name" key with the value of the jquery selector?
The final code will look like the code below:
j.ajax({
type: 'POST',
url: 'http://mywebsite/api/orderdetails',
cache: false,
data: {
"data_array": data_array
},
beforeSend: function() {
},
success: function(result) {
},
error: function(xhr, status, error) {
console.log(error);
},
complete: function() {
}
});
I need the value of the element to be place inside the value of data_array.order.customer.name
In this case you can use val() to select that property. If you want to do it as you instantiate the object, use this:
var data_array = {
"order": {
"customer": {
"name": name.val()
}
}
}
Or if you want to do it after declaring data_array (which is badly named, as it's an object not an array), then you can use this line:
data_array.order.customer.name = name.val();

How to display dummy data in a JSON object in the html page?

I am trying to display some dummy data, which is stored in JSON object. I am a newbie to this subject. So I don't understand clearly how to proceed with this.
However I wrote a javascript function and ajax call.
$(document).ready(function () {
var data = {
"id": 1,
"schedule": 1,
"channel": "AXN",
"fromDate": "2018-01-19",
"toDate": "2018-01-31",
"startTime": "11:00:00",
"endTime": "12:00:00",
"type": "TVC",
"mediaFile": 1
}
$.ajax({
type: "POST",
url: URI.customSchedule.getCustomScheduleUrl(),
data: data,
beforeSend: function () {
},
processData: false,
contentType: false,
cache: false,
timeout: 600000,
success: function (data) {
data.channel = $('#selectChannel').val();
data.fromDate = $('#fromDate').val();
date.toDate = $('#toDate').val();
date.startTime = $('#startTime').val();
date.endTime = $('#endTime');
},
error: function (e) {
}
});
});
This is how assigned the data in the JSON object to the html fields and this does not works.
data.channel = $('#selectChannel').val();
data.fromDate = $('#fromDate').val();
date.toDate = $('#toDate').val();
date.startTime = $('#startTime').val();
date.endTime = $('#endTime');
Can someone help me with this and explain the mistakes I did ? Please help me to display the values stored in the JSON object in html fields.
Edit:
While I debug the code, the debug point does not go inside the Ajax call. What is the issuee here?
To assign to HTML fields do this.
$('#selectChannel').val(data.channel);
$('#fromDate').val(data.fromDate);
In jquery there is same function that get and set the values in the element. val() is a common function that will get the value from specific element and also set the value to that element.
If you use val() with one parameter as a value then it will set the value to that HTML element so what you are doing inside success is getting the value from the element with id=selectChannel. You need to do
$('#selectChannel').val(data.channel);
To set the value data.channel into the element with id=selectChannel. And similar for other elements also.

How to parse json response in jQuery mobile?

I am new to jquery mobile. I am trying to get contact name from contacts. JSON by sending AJAX request. But I am not getting any alert when I click on submit button.
My jQuery ajax request
$(document).ready(function() {
//after button is clicked we download the data
$("#submit").click(function(){
//start ajax request
$.ajax({
url: "myURL/contacts.json",
dataType: "json",
success: function(data) {
var json = $.parseJSON(data);
alert(json.name);
});
});
});
contacts.json
{
"contacts": [
{
"id": "c200",
"name": "Ravi Tamada",
"email": "ravi#gmail.com",
"address": "xx-xx-xxxx,x - street, x - country",
"gender" : "male",
"phone": {
"mobile": "+91 0000000000",
"home": "00 000000",
"office": "00 000000"
}
},
{
"id": "c201",
"name": "Johnny Depp",
"email": "johnny_depp#gmail.com",
"address": "xx-xx-xxxx,x - street, x - country",
"gender" : "male",
"phone": {
"mobile": "+91 0000000000",
"home": "00 000000",
"office": "00 000000"
}
},
.
.
.
.
]
}
How to generate dynamic clickable list for above ajax response?
dataType: "json"
already specifies the returned data to be a json object. so to read the values, you can simply use the object syntax:
success: function(data) {
//cycle trough returned "contacts":
for(var i=0;i<data.contacts.length;i++){
console.log(data.contacts[i].name);
}
}
from the looks of it, your json will be an array of object. Try doing json[0].Name to test it
your json data present inside contacts,so you should take name in this format.
var json = $.parseJSON(data);
alert(json.contacts[0].name);
Firstly our code is badly formated (smart quotes, wrong placement of parentheses). Secondly since your contacts are in an array, you can't access them using json.name, you should try something like this instead:
$(document).ready(function () {
//after button is clicked we download the data
$("#submit").click(function () {
//start ajax request
$.ajax({
url: "myURL/contacts.json",
dataType: "json",
success: function (data) {
var json = $.parseJSON(data);
json.contacts.forEach(function(val, ind, arr){
alert(val.name);
});
}
});
});
});
In stead of parsing JSON you can do like followng:
$.ajax({
..
dataType: 'json' // using json, jquery will make parse for you
});
To access a property of your JSON do as shown in below:
data[0].name;
data[0].email;
Why you need data[0] because data is an array, so to its content retrieve you need data[0] (first element), which gives you an object {"name":"myName" ,"address": "myAddress" }.
And to access property of an object rule is:
Object.property
or sometimes
Object["property"] // in some case
So you need
data[0].name and so on to get what you want.
If you not
set dataType: json then you need to parse them using $.parseJSON() and to retrieve data like above.

JSONP ajax callback failing

I have following script running on my local test drive. It imports a JSON file and builds a webpage, but for some reason, there is an error in handling the data. No data is shown...
But whenever I use (the same) data hard-coded, I get the result I want. So this made me think it has something to do with the way I handle the JSON import...
This is my AJAX callback:
getGames: function(fn) {
$.ajax({
type: "GET",
url: App.Config('webserviceurl')+'games-payed.js',
dataType: "jsonp",
success: function (data) {
console.log('streets', data);
if(fn){
fn(data);
}
},
error: function (msg) {
if(fn){
fn({status:400});
}
}
});
}
And this code isn't working, nor am I getting any errors in my console...
When I load the data hard coded, it works perfectly:
getGames: function(fn) {
var games = App.Config('dummyGames');
if(fn){
fn(games);
}
}
Is there something wrong with my AJAX callback?
EDIT:
The JSON file looks like this:
jsonp1({
"status": "200",
"data": [
{
"id": "1",
"title": "Title 1",
"publishDate": "2013-03-27T15:25:53.430Z",
"thumbnail": "images/thumbs/image_game1.png",
"html5": "http://mysite.com/index.html"
},
{
"id": "2",
"title": "Title 2",
"publishDate": "2013-03-20T15:25:53.430Z",
"thumbnail": "images/thumbs/image_game2.png",
"html5": "http://mysite.com/index.html"
},
{
"id": "3",
"title": "Title 3",
"publishDate": "2013-03-18T15:25:53.430Z",
"thumbnail": "images/thumbs/image_game3.png",
"html5": "http://mysite.com/index.html"
}
]
});
In your example, I see that you wrap your json data inside jsonp1. I suppose that is a fixed name. If that's the case, try this:
getGames: function(fn) {
$.ajax({
type: "GET",
url: App.Config('webserviceurl')+'games-payed.js',
jsonp: false,
jsonpCallback:"jsonp1",
dataType: "jsonp",
success: function (data) {
console.log('streets', data);
if(fn){
fn(data);
}
},
error: function (msg) {
if(fn){
fn({status:400});
}
}
});
}
Notice the jsonpCallback:"jsonp1" and jsonp: false. The reason for this is: by default, jquery will generate the callback function name automatically and randomly and append ?callback=generatedFunctionName to the end of your url. Thanks to the callback parameter, the code on server side could use the same function name to call the callback on browser.
In your case, you're using fixed function name (jsonp1), so you have to:
Specify your function name explicitly using jsonpCallback="jsonp1"
Set jsonp = false to prevent jQuery from adding the "?callback" string to the URL or attempting to use "=?" for transformation.

Binding Complex array data returned from ajax call to viewmodel

I have a retrieveEntity web service method that returns fields as json strings and arrays. I am having trouble binding these fields to text boxes, while keeping the view model intact. First I make an ajax call to initialize my data and save it. Then inside my viewmodel I retrirve the values, and bind to the desired text box. Here is the code:
<script type="text/javascript" language='javascript'>
jQuery(function () {
myViewModel = new viewmodel();
ko.applyBindings(myViewModel);
});
var invoice = function () {
var initializeURL = "ajaxwebservicecalls.asmx/RetrieveEmptyEntity";
$.ajax({
type: "Post",
url: initializeURL,
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function retrieveemptyesuccess(msg) {
passedmodel = (msg.d.Data);
var data = ko.mapping.fromJS(passedmodel);
var x = $.toJSON(passedmodel)
},
Error: function initializefail(msg) { alert(msg) }
});
}
Here is a small snippet of what X returns:
{
"Entities": {
"Entity": [{
"Index": "1",
"Name": "BatchNumber",
"Value": ""
}, {
"Index": "2",
"Name": "InvoiceNumber",
"Value": ""
}]
},
"APInvoiceHeader": {
"VoucherNumber": "",
"PayLocationID": "",
"InvoiceDescription": "",
"InvoiceTypeID": "",
"TermsRuleID": "",
"TaxTypeID": "",
"RecurringInvoice": 0,
"APInvoiceItems": [{
"FixedAssetReferences": [{
"FixedAssetReferenceId": 0,
"FixedAssetReferenceIdSpecified": true,
"FormattedGLAccount": ""
}]
}
Next I construct my viewmodel based on the data returned:
var passedmodel;
var myViewModel;
var viewmodel = function () {
this.invoice = ko.observable(new invoice());
this.arrayentity = ko.observableArray([new invoice("ff"), new invoice("dd"), new invoice("zz"), new invoice("rr")]);
this.RetrieveEntity = function () {
var retrieveURL = "ajaxwebservicecalls.asmx/RetrieveEntity";
$.ajax({
type: "Post",
url: retrieveURL,
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function retrievesuccess(msg) {
passedmodel = msg.d.Data;
myViewModel.invoice(ko.mapping.fromJS(passedmodel, {}, myViewModel)); }
//I want to be able to Use the above, and then in the HTML binding specify for example:
data-bind="value:myViewModel.invoice().APInvoiceHeader.VoucherNumber"
or
data-bind="value:myViewModel.arrayentity().Entities.Entity()[0].Name"
However the binding syntax gives me an error. And instead i have parse the viewmodel and can't use it as a whole:
myViewModel.invoice(ko.mapping.fromJS(passedmodel.APInvoiceHeader, {}, myViewModel));
or
myViewModel.arrayentity([(ko.mapping.fromJS(passedmodel.Entities.Entity[0])), (ko.mapping.fromJS(passedmodel.Entities.Entity[1]))]);
and the HTML bindings then looks like
data-bind="value:myViewModel.invoice().VoucherNumber
or
data-bind="value:myViewModel.arrayentity()[0].Name"
which binds fine but that's not how I want the viewmodel to look like.
The reason I need to keep the viewmodel in as one and parse or navigate through is is because I need to next update value on screen, which updates the viewmodel, then convert the viewmodel back to JS, and pass it to another ajax call that saves the new data.
Can anyone please help? Any tips would be really appreciated. Thanks!

Categories

Resources