javascript Undefined variable/array - javascript

I have a small function that takes a dynamic list of textboxes with urls and sends it to the server. I am trying to load the urls into an array then pass them off in a JSON object. The problem is, when I get to that point in the code, I keep getting the error:
TypeError: url_data[this_url] is undefined
http://localhost/2011/admin/public/assets/js/tssol.ui.js
Line 196
Here is the block that returns that error:
$("#dialogEditor").dialog('option', 'buttons', {'Save' : function() {
/* Define variables */
var url_data = new Array();
var this_url = 0;
/* I've tried this with and without explicitly passing the vars... */
$("#website_editor input").each(function(url_data, this_url) {
var id =$(this).attr('name').match(/\d+/);
var url=$(this).val();
/* Test the varible each iteration */
console.log("this_url: " + this_url + " id: " + id + " url: " + url);
/* Line 196 */ url_data[this_url].id = id;
url_data[this_url].url = url;
this_url++;
});
data = JSON.stringify(url_data);
//data = url_data;
//console.log(data);
$.ajax({
url: 'ajax.websites.php',
dataType: 'json',
data: {
action: "update_resort",
ResortId: resort,
data: data
}
});
$(this).dialog("close");
},
'Cancel': function(){$(this).dialog("close");
}});
},
Sorry about the formatting

I would do this:
url_data[this_url] = {
id: id,
url: url
}

Related

How to post a form with ajax and return data in array?

HI how to post a form and return data it will be a array as like this
{
"notes":'some notes',
"validUntil": '12/12/2015',
"status": 1,
"menuItemName": "HR Section",
"menuItemDesc": "gggg"
}
My code is this
$('#add-menu-list .btn[data-attr=submit-btn]').on('click', function(){
var formValidate = $('#add-menu-list').parsley().validate();
validateFront();
// console.log(formValidate);
var menuName = $('input[data-api-attr=menuItemName]').val();
var validUntil = $('input[data-api-attr=validUntil]').val();
var menuStatus = $('input[data-api-attr=status]').val();
var menuNote = $('textarea[data-api-attr=notes]').val();
var menuDesc = $('textarea[data-api-attr=menuItemDesc]').val();
var dataString = {
menuItemName: menuName,
validUntil : validUntil,
status : menuStatus,
notes : menuNote,
menuItemDesc : menuDesc
};
if(formValidate == true){
alert('success');
console.log(menuName + validUntil + menuStatus + menuNote + menuDesc);
var url = "xyz.html"; // the script where you handle the form input.
$.ajax({
type: "POST",
// url: url,
dataType: "json",
data: $(dataString).serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response
}
});
}else{
alert('Validation fail ');
}
});
Since "data" is a server response i guess that your server return a json object. In this case you have to somehow inform the jquery's ajax that you expect a json response from server or you have to translate the "data" to a json object by your self.
It is best to follow the first option so you don t have to deal with the translation your self you can easily do that by giving an extra parameter tou your ajax reuest : dataType: 'json', this will do the trick!
Now that you have a proper response object from your request you can either stringify it with var string_resp=JSON.stringify(data); and then alert it alert(string_resp) or you can access its elements like that : alert(data.status) which will alert your object's status field etc.
so your code will be :
$.ajax({
type: "POST",
url: url,
dataType: 'json',
data: $(menuName).serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // will alert an object
alert(data.status); // will alert object's status field in this case 1
alert(JSON.stringify(data)) // will alert the object as a string
}
});
you are sending only one value in serialize, serialize() should be on form element not on field element, like :
$('#add-menu-list .btn[data-attr=submit-btn]').on('click', function(){
...
$.ajax({
...
data:$("#form").serialize();
...
success: function(data)
{
alert(data.notes); // show response
....
}
var myObj = {
"notes":'some notes',
"validUntil": '12/12/2015',
"status": 1,
"menuItemName": "HR Section",
"menuItemDesc": "gggg"
};
myObj.toString = function()
{
var str = '';
for (var property in myObj)
{
if (myObj.hasOwnProperty(property) && (property != "toString") )
{
str += (property + ': ' + myObj[property] + "\n");
// do stuff
}
}
return str;
}
alert(myObj);

Uncaught ReferenceError: error is not defined in Ajax Callback

In my App, I get a list of Events from a Sharepoint Calendar List. That part works perfectly.
However after I get the collection of results, for each item I need to get the Display Form Url, which is another REST Call with the ListItem ID.
However I get the error below, but I still dont know what the problem might be
Uncaught ReferenceError: error is not defined App.js:87(anonymous function) App.js:87$.ajax.error App.js:40c jquery-1.9.1.min.js:22p.fireWith jquery-1.9.1.min.js:22k jquery-1.9.1.min.js:24send.r
I based my code on this answer:
https://sharepoint.stackexchange.com/questions/119236/how-to-get-the-display-form-url-using-rest
My adapted code is like this:
var SPHostUrl;
var SPAppWebUrl;
var ready = false;
// this function is executed when the page has finished loading. It performs two tasks:
// 1. It extracts the parameters from the url
// 2. It loads the request executor script from the host web
$(document).ready(function () {
var params = document.URL.split("?")[1].split("&");
for (var i = 0; i < params.length; i = i + 1) {
var param = params[i].split("=");
switch (param[0]) {
case "SPAppWebUrl":
SPAppWebUrl = decodeURIComponent(param[1]);
break;
case "SPHostUrl":
SPHostUrl = decodeURIComponent(param[1]);
break;
}
}
// load the executor script, once completed set the ready variable to true so that
// we can easily identify if the script has been loaded
$.getScript(SPHostUrl + "/_Layouts/15/SP.RequestExecutor.js", function (data) {
ready = true;
getItems();
});
});
function getListItemFormUrl(webUrl, listName, listItemId, formTypeId, complete, failure) {
$.ajax({
url: webUrl + "/_api/web/lists/GetByTitle('" + listName + "')/Forms?$select=ServerRelativeUrl&$filter=FormType eq " + formTypeId,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
var url = data.d.results[0].ServerRelativeUrl + '?ID=' + listItemId
complete(url);
},
error: function (data) {
failure(data);
}
});
}
// this function retrieves the items within a list which is contained within the parent web
function getItems() {
// only execute this function if the script has been loaded
if (ready) {
// the name of the list to interact with
var listName = "Events";
// the url to use for the REST call.
var url = SPAppWebUrl + "/_api/SP.AppContextSite(#target)" +
// this is the location of the item in the parent web. This is the line
// you would need to change to add filters, query the site etc
// "/web/lists/getbytitle('" + listName + "')/items?" +
"/web/lists/getbytitle('" + listName + "')/items?$select=Title,Category,EventDate,Description,EncodedAbsUrl,ID" +
"&#target='" + SPHostUrl + "'";
// create new executor passing it the url created previously
var executor = new SP.RequestExecutor(SPAppWebUrl);
// execute the request, this is similar although not the same as a standard AJAX request
executor.executeAsync(
{
url: url,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
// parse the results into an object that you can use within javascript
var results = JSON.parse(data.body);
var events = [];
$.each(results.d.results, function (i, obj) {
//Usage
getListItemFormUrl(SPAppWebUrl, 'Calendar', obj.ID, 4,
function (url) {
console.log('Display from url for list item: ' + url);
},
function (sender, args) {
console.log(JSON.stringify(error));
})
//use obj.id and obj.name here, for example:
var event = {
date: Date.parse(obj.EventDate).toString(),
type: obj.Category,
title: obj.Title,
description: obj.Description,
url: obj.EncodedAbsUrl + 'DispForm.aspx?ID=' + obj.ID
}
events.push(event);
});
var myJsonString = JSON.stringify(events);
$("#eventCalendarInline").eventCalendar({
jsonData: events,
openEventInNewWindow: true,
showDescription: true,
txt_GoToEventUrl: "Go to event"
});
Communica.Part.init();
},
error: function (data) {
// an error occured, the details can be found in the data object.
alert("Ooops an error occured");
}
});
}
}
Under //Usage:
function (sender, args) {
console.log(JSON.stringify(error));
})
error does not seem to be defined

GiantBomb API Work

I have made an account and have my api key currently i just want a simple search box and button that when hit will list the game and the image of that game
Have linked the site info below
http://www.giantbomb.com/api/documentation
I want to run is and get the output using json and jquery any help welcome
This is a working search now some what does not allow the user to enter in a new value and there is a problem bring up the image
two main problems wont load the image just says undefined and cant figure out how to make it a full search only when he user enters a new title
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.ajax({
url: "http://api.giantbomb.com/search/",
type: "get",
data: {api_key : "key here", query: "star trek", resources : "game", field_list : "name, resource_type, image", format : "jsonp", json_callback : "gamer" },
dataType: "jsonp"
});
});
function gamer(data) {
var table = '<table>';
$.each( data.results, function( key, value ) {
table += '<tr><td>' + value.image + '</td><td>' + value.name + '</td><td>' + value.resource_type + '</td></tr>';
});
table += '</table>';
$('#myelement').html(table);
}
</script>
</head>
<body>
<h1>Game Search</h1>
<input id="game" type="text" /><button id="search">Search</button>
<div id="myelement"></div>
</body>
</html>
Your working code as per standard of the giantbomb docs:
var apikey = "My key";
var baseUrl = "http://www.giantbomb.com/api";
// construct the uri with our apikey
var GamesSearchUrl = baseUrl + '/search/?api_key=' + apikey + '&format=json';
var query = "Batman";
$(document).ready(function() {
// send off the query
$.ajax({
url: GamesSearchUrl + '&query=' + encodeURI(query),
dataType: "json",
success: searchCallback
});
// callback for when we get back the results
function searchCallback(data) {
$('body').append('Found ' + data.total + ' results for ' + query);
var games = data.game;
$.each(games, function(index, game) {
$('body').append('<h1>' + game.name + '</h1>');
$('body').append('<p>' + game.description + '</p>');
$('body').append('<img src="' + game.posters.thumbnail + '" />');
});
}
});
http://jsfiddle.net/LGqD3/
GiantBomb Api example/explanation
First get your api key
Key: http://www.giantbomb.com/api/
Documentation: http://www.giantbomb.com/api/documentation
Your base url:
http://www.giantbomb.com/api/
Your url structure:
/RESOURCE?api_key=[YOUR_API_KEY]&format=json/FILTERS/FIELDS
/RESOURCE/ID example: /game/3030-38206/
The type of resource you which to return, in your case a search. Sometimes.. in case of a specific game you also want to pass in the ID under /ID (like in the example)
api_key
Your api key
You need this otherwise you cannot use the api :)
format
The format you which to output, in this case json.
FILTERS example: /search?limit=100
This manipulates the resourses output
See under the resources in the documentation for a what you can do.
FIELDS example: /search?field_list=description,
Which field to return, use this to "reduce the size of the response payload"
A game request for it's name & description would be:
http://www.giantbomb.com/api/game/3030-38206/?api_key=[YOUR-API-KEY]&format=json&field_list=name,description
A search request
Lets say we want to search for the game "Elder scroll online".
You would construct your url like this:
/search/?api_key=[YOUR-API-KEY]&format=json&query="elder scrolls online"&resources=game
To implement this in with $.ajax:
The ajax function
/*
* Send a get request to the Giant bomb api.
* #param string resource set the RESOURCE.
* #param object data specifiy any filters or fields.
* #param object callbacks specify any custom callbacks.
*/
function sendRequest(resource, data, callbacks) {
var baseURL = 'http://giantbomb.com/api';
var apiKey = '[YOUR-API-KEY]';
var format = 'json';
// make sure data is an empty object if its not defined.
data = data || {};
// Proccess the data, the ajax function escapes any characters like ,
// So we need to send the data with the "url:"
var str, tmpArray = [], filters;
$.each(data, function(key, value) {
str = key + '=' + value;
tmpArray.push(str);
});
// Create the filters if there were any, else it's an empty string.
filters = (tmpArray.length > 0) ? '&' + tmpArray.join('&') : '';
// Create the request url.
var requestURL = baseURL + resource + "?api_key=" + apiKey + "&format=" + format + filters;
// Set custom callbacks if there are any, otherwise use the default onces.
// Explanation: if callbacks.beforesend is passend in the argument callbacks, then use it.
// If not "||"" set an default function.
var callbacks = callbacks || {};
callbacks.beforeSend = callbacks.beforeSend || function(response) {};
callbacks.success = callbacks.success || function(response) {};
callbacks.error = callbacks.error || function(response) {};
callbacks.complete = callbacks.complete || function(response) {};
// the actual ajax request
$.ajax({
url: requestURL,
method: 'GET',
dataType: 'json',
// Callback methods,
beforeSend: function() {
callbacks.beforeSend()
},
success: function(response) {
callbacks.success(response);
},
error: function(response) {
callbacks.error(response);
},
complete: function() {
callbacks.complete();
}
});
}
search function
function search() {
// Get your text box input, something like:
// You might want to put a validate and sanitation function before sending this to the ajax function.
var searchString = $('.textox').val();
// Set the fields or filters
var data = {
query: searchString,
resources: 'game'
};
// Send the ajax request with to '/search' resource and with custom callbacks
sendRequest('/search', data, {
// Custom callbacks, define here what you want the search callbacks to do when fired.
beforeSend: function(data) {},
success: function(data) {},
error: function(data) {},
complete: function(data) {},
});
}
Example of a get game function
function getGame() {
// get game id from somewhere like a link.
var gameID = '3030-38206';
var resource = '/game/' + gameID;
// Set the fields or filters
var data = {
field_list: 'name,description'
};
// No custom callbacks defined here, just use the default onces.
sendRequest(resource, data);
}
EDIT: you could also make a mini api wrapper out of this, something like:
var apiWrapper = {};
apiWrapper.request = function(resource, data, callbacks) {
// The get function;
};
apiWrapper.search = function(data) {
// The search function
};
apiWrapper.getGame = function(id, data) {
// The game function
}
apiWrapper.init = function(config) {
var config = config || {};
this.apiKey = config.apiKey || false;
this.baseURL = config.baseURL || 'http://api.giantbomb.com';
}
apiWrapper.init({
apiKey: '[API-KEY]'
});
Have not tested the code, so there might be a bug in it, will clean it up tommorow :)
Edit: fixed a bug in $.ajax

How to concate function parameter value into object literal property name

I have the following JS code (also I use jQuery):
jQuery(function($) {
$(".to_manufacturer").click(function() {
var checked = $(this).is(':checked');
var man_id = $(this).attr("to_manufacturer_id");
update_is_in_to(man_id, "to_manufacturer", checked)
});
$(".to_model").click(function() {
var checked = $(this).is(':checked');
var man_id = $(this).attr("to_model_id");
update_is_in_to(man_id, "to_model", checked)
});
$(".to_type").click(function() {
var checked = $(this).is(':checked');
var man_id = $(this).attr("to_type_id");
update_is_in_to(man_id, "to_type", checked)
});
function update_is_in_to (man_id_val, modelname, checked_val) {
$.ajax({
url: "/admin/catalog/to/"+modelname+"s/ajax/update_is_in_to",
type: "GET",
data: {id: man_id_val, modelname_is_in_to_val: checked_val},
success: function(text)
{
//$("#total_count").html(text + " товар(ов)");
},
error: function(){
alert('Ошибка обновления объекта с id = '+man_id_val+' ! Очередная попытка...');
$.ajax(this);
},
dataType : "html"
});
}
});
How can I make it so that my param modelname_is_in_to_val is composite, where the first part is the method param modelname and second is the string "_is_in_to_val"?
I tried modelname + "_is_in_to_val" but I received errors. What is it right to do it?
Also is not my code to violate according js conventions?
You'll need to use bracket notation and build your object outside the function:
function update_is_in_to (man_id_val, modelname, checked_val) {
var data = {};
data.id = man_id_val;
data[modelname + '_is_in_to_val'] = checked_val;
$.ajax({
...
data: data,
...
});
}
You can't do it directly in the object literal syntax. You'll need to create the object first, then add that property using the square bracket version of the member operator. This lets you evaluate an expression, and use its result as the property name.
function update_is_in_to (man_id_val, modelname, checked_val) {
var data = {id: man_id_val};
data[modelname + "_is_in_to_val"] = checked_val;
$.ajax({
url: "/admin/catalog/to/"+modelname+"s/ajax/update_is_in_to",
type: "GET",
data: data,
success: function(text)
{
//$("#total_count").html(text + " товар(ов)");
},
error: function(){
alert('Ошибка обновления объекта с id = '+man_id_val+' ! Очередная попытка...');
$.ajax(this);
},
dataType : "html"
});
}

Passing jquery variable to ajax data

I am trying to pass these variables from 3 hidden fields to the data of the the ajax.
I am getting the correct variables. I verified via console.log. I tried to parse json but it didnt for me.
The error i am getting uncaught exception: [Exception... "Could not convert JavaScript argument" nsresult: "0x80570009 (NS_ERROR_XPC_BAD_CONVERT_JS)" location: "JS frame :: http://code.jquery.com/jquery-latest.js :: :: line 7740" data: no]
Line 2
I am trying to pass these variables using the ajax request to my controller. The other variables in the datastring I have no issues at all. When a user clicks on a star rating the values are posted and inserted to a db.
Here are the variables:
var TweetUserId = $(this).parents().prevAll('input[type=hidden:first]') ;
var TweetScreenName = $(this).parents().prevAll('input[type=hidden:second]') ;
var TweetPostText = $(this).parents().prevAll('input[type=hidden:third]') ;
// making it an object didnt work
// TweetUserId = new Object; TweetUserId = (TweetUserId);
// TweetScreenName = new Object; TweetScreenName = (TweetScreenName);
// TweetPostText = new Object; TweetPostText = (TweetPostText);
Here is the request
$.ajax({
url: '/Home/GetRating', //your server side script
dataType: "json",
data: { id: ratingid, value: value, TweetUserId: TweetUserId, TweetScreenName: TweetScreenName, TweetPostText: TweetPostText, tweetday: dateoftweet, tweettime: timeoftweet }, //our data
type: 'POST',
success: function (data) {
//$('#ratemsg').html(data);
msg.html(" The TweetId is " + ratingid + " the vote value is " + value + " " + dateoftweet + " " + timeoftweet );
// console.log(hiddenValue);
},
error: function (jxhr, msg, err) {
// $('#response').append('<li style="color:red">' + msg + '</li>');
msg.html(data);
}
});
});
});
your are using selectors the wrong way and some are invalid :first :second :third
(they should go outside the [type=hidden] and there are no :second :third .. use the :eq() selector instead
You are passing elements instead of their value to the ajax request..
Use this when populating the variables..
var TweetUserId = $(this).parents().prevAll('input[type="hidden"]:eq(0)').val();
var TweetScreenName = $(this).parents().prevAll('input[type="hidden"]:eq(1)').val();
var TweetPostText = $(this).parents().prevAll('input[type="hidden"]:eq(2)').val();
As a general pattern, it is better to cache a jQuery object when you intend to use it multiple times, instead of re-selecting it ..
so you could improve your code with
var hiddenElements = $(this).parents().prevAll('input[type="hidden"]'),
TweetUserId = hiddenElements.eq(0).val(),
TweetScreenName = hiddenElements.eq(1).val(),
TweetPostText = hiddenElements.eq(2).val();

Categories