I don't have very much to my code but I seem to be getting Illegal invocation with my order variable - works fine and shows in console.log if I comment it out
$('body').on("click", "#brands_by_category_submit_btn", function (e) {
e.preventDefault();
var self = $(this);
var order = $(".order").toArray();
var id = $("#manID").data("id");
var brand_name = $("#brand_name").data("id");
var data = grabData(true);
if(data.length)
{
var data_array = {
id : id,
brand_name : brand_name,
cat_id : data,
order : order,
state : 1
};
var url = $("#brands_by_category_submit_btn").data("url");
//console.log(data_array);
ajaxCall(url, data_array);
alert("Categories Updated");
}
});
AjaxCall:
function ajaxCall(url, data_array, div_id, callback_fn) {
return $.ajax({
type:'POST',
url:url,
beforeSend: function(){
$("#" + div_id).html("<img src='http://www.#.co.nz/files/large/ajax-loader.gif' alt='Loading..' title='Loading..'/>");
},
data:data_array,
complete:function (data) {
$("#" + div_id).html(data.responseText);
if(callback_fn != null)
{
eval(callback_fn + '()');
}
}
});
}
Your problem is that you're converting an array of HTML elements into POST data which simply isn't possible. You should instead loop through your elements and grab their .text() property:
var self = $(this);
var order = []; //or "new Array()". Whatever you prefer for readability
$(".order").each(function() {
order.push($(this).text());
});
var id = $("#manID").data("id");
var brand_name = $("#brand_name").data("id");
var data = grabData(true);
Related
If condition to equal two string values in javascript is not working in server, but its working in localhost. Given below is my code.
var res_id = $(this).attr('name');
var fld_id = $(this).attr('id');
var ans = $('#'+fld_id).attr('value');
//var mod_id = $('#mod_id').attr('value');
//alert(typeof(ans));
$.post("multiple_check_answer.php", { resid: res_id, answ: ans}, function(data){
//alert(typeof data);
if(ans==data)
{
//alert(data);
$('#span_'+res_id+'_'+ans).css({'color':'green', 'font-weight':'bold'});
}
else
{
$('#span_'+res_id+'_'+ans).css({'color':'red', 'font-weight':'bold'});
$('#span_'+res_id+'_'+data).css({'color':'green', 'font-weight':'bold'});
}
});
for ex. if ans and data values are A but its showing red color.
Here is the new code which is working fine. Changed data value to integer.
$("input[type=radio]").click(function(){
var res_id = $(this).attr('name');
var fld_id = $(this).attr('id');
var ans = $('#'+fld_id).attr('value');
//var mod_id = $('#mod_id').attr('value');
//alert(ans);
$.post("multiple_check_answer.php", { resid: res_id, answ: ans}, function(data){
//alert(data);
if(data==1)
{
//alert(data);
$('#span_'+res_id+'_'+ans).css({'color':'green', 'font-weight':'bold'});
//$('#dis_msg'+res_id).html('<strong style="color:green">Your Answer is Correct</strong>');
}
else
{
$('#span_'+res_id+'_'+ans).css({'color':'red', 'font-weight':'bold'});
$('#span_'+res_id+'_'+data).css({'color':'green', 'font-weight':'bold'});
//$('#dis_msg'+res_id).html('<strong style="color:red">Your Answer is In-Correct</strong>');
}
});
});
I need to run function "testfun 2 times", for each function I will have a few of names lets say testfun(5, global_user) // output [1,2,4,4,5] and for testfun(7, global_user) // output [9,10,11]
How I can put this 2 arrays in one array after I will run 2 functions?
testfun(5, global_user);
testfun(7, global_user);
function testfun(groupId, myUser) {
var selectStr = "Title";
var itemsUrl = "https://info.com(" + groupId + ")/users" + "?" + selectStr + "&" + orderbyStr;
var executor = new SP.RequestExecutor;
executor.executeAsync(
{
url: itemsUrl,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: loadTeamNames,
error: errorHandler
}
);
}
var arr = [];
function loadTeamNames(data){
var jsonObject = JSON.parse(data.body);
var results = jsonObject.d.results;
var hide_groups = false;
$(results).each(function(){
var name = $(this)[0].Name;
});
}
Thanks
With JS
var mergedArray = outputOne.concat(outputTwo);
With JQuery
var mergedArray = $.merge( $.merge( [], outputOne), outputTwo);
Since testFun() uses asynchronous methods you can't do anything immediately after running it twice without waiting for both instnces to complete. This is accomplished using promises
You could use $when() and return a promise from testFun(). Will need to move loadTeamNames into testFun to do it
$.when() won't complete until both of the promises are resolved
function testfun(groupId, myUser) {
var defer = $.Deferred();
var selectStr = "Title";
var itemsUrl = "https://info.com(" + groupId + ")/users" + "?" + selectStr + "&" + orderbyStr;
var executor = new SP.RequestExecutor;
executor.executeAsync(
{
url : itemsUrl,
method : "GET",
headers : {"Accept" : "application/json; odata=verbose"},
success : loadTeamNames,
error : errorHandler
}
);
function loadTeamNames(data) {
var jsonObject = JSON.parse(data.body);
var results = jsonObject.d.results;
var hide_groups = false;
$(results).each(function () {
var name = $(this)[0].Name;
});
// resolve deferred and pass data to be used in `$.when()`
defer.resolve(results);
}
return defer.promise;
}
To use
$.when(testfun(5, global_user),testfun(7, global_user)).done(function (results1, results2) {
//do what you need to with arrays results1 & results2
});
Add defer.reject() in the errorHandler
Assuming that jsonObject.d.results is an array already, you can just do:
arr.concat(results)
This will concatenate your array so far with the new result. Have that code inside of loadTeamNames and each run of testfun will concatenate the result to your current array. not really sure what you're using all those variables inside of loadTeamNames for however.
function getTeamNames(groupId, myUser) {
var defer = $.Deferred();
var selectStr = "$select=Title,LoginName";
var orderbyStr = "$orderby=Title";
var itemsUrl = "https://sites.sp.kp.org/pub/qosstgcat/_api/web/SiteGroups/getbyid(" + groupId + ")/users" + "?" + selectStr + "&" + orderbyStr;
var executor = new SP.RequestExecutor(carootUrl);
executor.executeAsync(
{
url : itemsUrl,
method : "GET",
headers : {"Accept" : "application/json; odata=verbose"},
success : loadTeamNames,
error : errorHandler
}
);
function loadTeamNames(data) {
var jsonObject = JSON.parse(data.body);
var results = jsonObject.d.results;
var hide_groups = false;
$(results).each(function(){
var login_name = $(this)[0].LoginName;
});
defer.resolve(results);
}
return defer.promise;
}
result
$.when(getTeamNames(4, global_user),getTeamNames(185, global_user)).done(function () {
console.log(results);
});
Is it possible to consolidate the two sections of code below. If you look at each section you will notice they are almost identical. I have another 3 or 4 sections of code which are also identical. I'm wondering if there's a neater way for me to use the same code?
$("#agencies").on("click", ".applyClick", function(event) {
event.stopPropagation();
event.preventDefault();
var target = $(this);
var currentParent = $(this).closest('tr');
var id = currentParent.attr('id');
var items = $("input,select,textarea", currentParent);
var strData = items.serialize() + '&id=' + id;
$.post("agencies.php", strData, function(data) {
var data = $.parseJSON(data);
if(data.redirect_location){
window.location = data.redirect_location;
}
else{
var type = data.type;
var result = $.map(data, function(val,index) {
if(index != 'type'){
var str = val;
}
return str;
}).join("<br>");
if(type == 'error'){
alert(result);
}
else{
$("div#messages").html('<div class="'+ type +'-message">' + result + '</div>').slideDown("slow");
closeRow('quit', target);
}
}
});
});
$("#builders").on("click", ".applyClick", function(event) {
event.stopPropagation();
event.preventDefault();
var target = $(this);
var currentParent = $(this).closest('tr');
var id = currentParent.attr('id');
var items = $("input,select,textarea", currentParent);
var strData = items.serialize() + '&id=' + id;
$.post("builders.php", strData, function(data) {
var data = $.parseJSON(data);
if(data.redirect_location){
window.location = data.redirect_location;
}
else{
var type = data.type;
var result = $.map(data, function(val,index) {
if(index != 'type'){
var str = val;
}
return str;
}).join("<br>");
if(type == 'error'){
alert(result);
}
else{
$("div#messages").html('<div class="'+ type +'-message">' + result + '</div>').slideDown("slow");
closeRow('quit', target);
}
}
});
});
I will recomend to add attribute to your buttons like this
<input type="button" data-url="agencies" id="agencies" />
<input type="button" data-url="builders.php" id="builders" />
and same code like this
$("#agencies, #builders").on("click", ".applyClick", function(event) {
var url = $(this).attr('data-url');
....
$.post(url, strData, function(data) {
...
...
});
This question is in the margins of Code Review and SO.
The only difference between the two handlers appears to be the .post URL, and that appears to be derivable from the ID of the click target.
So do a little string handling to build the URL and attach your modified function as click handler to both elements :
$("#agencies, #builders").on("click", ".applyClick", function(event) {
...
$.post(this.id + '.php', strData, function(data) {
...
}
Is it possible to use like fuse.js with an XML document instead of JSON? As it is now I only have an XML document with data and hope that I shouldn't make a new version as well for JSON.
Hope someone can help me out which direction I can/should go.
Kind regards,
Niels
Found the solution myself. Instead of the example with JSON placed on http://kiro.me/projects/fuse.html, here is the version with an XML call instead :)
$(function() {
function start(books) {
var $inputSearch = $('#hero-search'),
$results = $('#results ul'),
$authorCheckbox = $('#value'),
$titleCheckbox = $('#typeId'),
$caseCheckbox = $('#case'),
searchAuthors = true,
searchTitles = false,
isCaseSensitive = false,
fuse;
function search() {
$results.empty();
$.each(r, function(i, val) {
$resultShops.append('<li class="result-item"><span><img src="' + this.statusId + '" /></span> ' + this.value + '</li>');
});
}
function createFuse() {
var keys = [];
if (searchAuthors) {
keys.push('value');
}
if (searchTitles) {
keys.push('typeId');
}
fuse = new Fuse(books, {
keys: keys,
caseSensitive: isCaseSensitive
});
}
$inputSearch.on('keyup', search);
createFuse();
}
$.ajax({
type: 'GET',
dataType: 'xml',
url: 'xml-document/document.xml',
success: function(response) {
var suggestions = [];
$(response).find("searchResults").children().each(function(i, elm) {
var name = $(elm).find('name').text();
var url = $(elm).find('url').text();
var description = $(elm).find('description').text();
var statusId = $(elm).find('status').text();
var typeId = $(elm).find('type').text();
var result = {};
result.value = name;
result.url = url;
result.description = description;
result.statusId = statusId;
result.typeId = typeId;
suggestions.push(result);
});
start(suggestions);
},
error: function(response) {
console.log('failure',response);
}
});
});
I am trying to return a JSON object from a function using the JSON jQuery plugin (http://code.google.com/p/jquery-json/) but after returning the object from the function, it becomes undefined.
$(document).ready(function() {
var $calendar = $('#calendar');
$calendar.weekCalendar({
...
data : function(start, end, callback) {
var datas = getEventData();
alert(datas); // Undefined???
}
});
If I inspect the object before returning it, it is defined.
function getEventData() {
var dataString = "minDate="+ minDate/1000 + "&maxDate=" + maxDate/1000;
//alert(dataString);return false;
$.ajax({
type: "POST",
url: "busker_ops.php",
data: dataString,
dataType: "json",
success: function(data) {
if(data != null) {
var jsonArray = new Array();
var jsonObj = {};
for(var i = data.length - 1; i >= 0; --i) {
var o = data[i];
var set_id = o.set_id;
var start = o.startOrig;
var end = o.endOrig;
var title = o.title;
var deets = o.deets;
jsonObj =
{
"id":parseInt(set_id),
"start":$("#calendar").weekCalendar("formatDate", new Date(start), "c"),
"end":$("#calendar").weekCalendar("formatDate", new Date(end), "c"),
"title":title,
"body":deets
};
jsonArray[i] = jsonObj;
}
alert($.toJSON(jsonArray)); // Defined!
return ($.toJSON(jsonArray));
} else {
}
}
});
}
Any idea what I'm missing here?
function getEventData() {
function local() {
console.log(42);
return 42;
}
local();
}
Your missing the fact that the outer function returns undefined. And that's why your answer is undefined.
Your also doing asynchronous programming wrong. You want to use callbacks. There are probably 100s of duplicate questions about this exact problem.
Your getEventData() function returns nothing.
You are returning the JSON object from a callback function that's called asynchronously. Your call to $.ajax doesn't return anything, it just begins a background XMLHttpRequest and then immediately returns. When the request completes, it will call the success function if the HTTP request was successful. The success function returns to code internal in $.ajax, not to your function which originally called $.ajax.
I resolved this by using callbacks since AJAX is, after all. Once the data is retrieved it is assigned to a global variable in the callback and the calendar is refreshed using the global variable (datas).
$(document).ready(function() {
// Declare variables
var $calendar = $('#calendar');
datas = "";
set = 0;
// Retrieves event data
var events = {
getEvents : function(callback) {
var dataString = "minDate="+ minDate/1000 + "&maxDate=" + maxDate/1000;
$.ajax({
type: "POST",
url: "busker_ops.php",
data: dataString,
dataType: "json",
success: function(data) {
if(data != null) {
var jsonArray = new Array();
var jsonObj = {};
for(var i = data.length - 1; i >= 0; --i) {
var o = data[i];
var set_id = o.set_id;
var start = o.startOrig;
var end = o.endOrig;
var title = o.title;
var deets = o.deets;
jsonObj =
{
"id":parseInt(set_id),
"start":$("#calendar").weekCalendar("formatDate", new Date(start), "c"),
"end":$("#calendar").weekCalendar("formatDate", new Date(end), "c"),
"title":title,
"body":deets
};
jsonArray[i] = jsonObj;
}
//alert($.toJSON(jsonArray));
callback.call(this,jsonArray);
} else {
}
}
});
}
}
$calendar.weekCalendar({
data : function(start, end, callback) {
if(set == 1) {
callback(datas);
//alert(datas.events);
}
}
});
// Go get the event data
events.getEvents(function(evented) {
displayMessage("Retrieving the Lineup.");
datas = {
options : {},
events : evented
};
set = 1;
$calendar.weekCalendar("refresh");
});
});