Jquery post and missing data - javascript

I'm retrieving an a list of sites, groups, and users. I'm concatenating and placing them in their respective variable, sending them in a query string to an aspx file.
var url = (Page._BASE_URL + 'Mo/Un/Unis/Unifie.aspx?' + getUserSecurityParameter() +
'&action=sending&userIds=' + encodeURI(userIds) +
'&siteName=' + encodeURI(site) +
'&groupName=' + encodeURI(groupName) +
'&siteList=' + encodeURI(siteList) +
'&team=' + encodeURI(team) +
'&users=' + encodeURI(users)+
'&site=' + encodeURI(site));
Ii'm using this code to retrieve those values on from the ajax post. I notice when I notice check the aspx source, There's so much data between the groups and sites that the users variable and data is never present.
var siteName = $.getUrlVar('siteName');
var groupName = $.getUrlVar('groupName');
var users= $.getUrlVar('users');
Is there a better way to do this so I won't have this issue? Because of missing users data it throws of a query that is written on the back end. Thanks in advance.
This is what I have now. When I try to send the data over I get an error. I can't see the what the error is unfortunately.
var requestParameters =
{
siteList: siteList,
team: team,
users: users,
siteName: site,
site: site,
group: group,
userId: userId,
securityCode: getUserSecurityParameter()
};
$.ajax({
url: Im._B + 'Mo/Uni/Unif/Ui.aspx/getValues',
type: "POST",
data: JSON.stringify(requestParameters),
contentType: "application/json; charset=UTF-8",
done: function (requestParameters, textStatus, jqXHR) {
var left = Math.floor((screen.width - 545) / 2);
windowManager.openFixed(url, 'DocumentListWindow', left, /* top: */ 10, /* width: */ 1480, /* height: */ 840);
},
error: function (jqXHR, textStatus, errorThrown) {
alert('An error occurred trying to send the data.');
}
});
Ui.aspx.cs
[System.Web.Services.WebMethod]
public static string getValues(string requestParameters)
{
string mystuff = requestParameters;
return mystuff;
}
ERROR
"{\"Message\":\"Operation is not valid due to the current state of the object.\",\"StackTrace\":\"

Although there is technically no limit to the length of a query string, individual browsers do have limits. Follow Alex's advice and convert this to a post.

Related

Iterating over a list of skus in jQuery to dynamically add it to HTML

I'm at a beginner level in front-end development; I'm attempting to refactor some code as a side project for myself to improve my skills. My job has a list of images targeted by their skus being dynamically added to div's. I have included the following code that I have attempted to refactor.
var getProductNavigateDetail = function(skuList) {
var postUrl = "/Browse/ProductDynamicComponent/GetProductNavigateDetailJson";
$.ajax({
url: postUrl,
type: "POST",
data: { skus: skuList },
dataType: "json",
success: function(result) {
if (result[0] != null) {
$('#a1Price').html(result[0].FormattedPrice);
$('#a1Name').html(result[0].Name);
$('#a1Link').attr('href', result[0].NavigateUrl);
$('#a1Link').attr('href', result[1].NavigateUrl);
$('#b1Price').html(result[1].FormattedPrice);
$('#b1Name').html(result[1].Name);
$('#c1Price').html(result[2].FormattedPrice);
$('#c1Name').html(result[2].Name);
$('#c1Link').attr('href', result[2].NavigateUrl);
$('#a2Price').html(result[14].FormattedPrice);
$('#a2Name').html(result[14].Name);
$('#a2Link').attr('href', result[14].NavigateUrl);
$('#b2Price').html(result[15].FormattedPrice);
$('#b2Name').html(result[15].Name);
$('#b2Link').attr('href', result[15].NavigateUrl);
$('#c2Price').html(result[16].FormattedPrice);
$('#c2Name').html(result[16].Name);
$('#c2Link').attr('href', result[16].NavigateUrl);
}
},
error: function(jqXhr, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
}
getProductNavigateDetail('160555,665087,159816,482743,228984,519217,320165,216235,229010,687943,332256,513663,482508,216243,330495,340218,668637,232524,414899,444139,560632,329734');
It seems pretty obvious that it just needs to iterated over with a loop so I made this code.
var getProductNavigateDetail = function(skuList) {
var postUrl = "/Browse/ProductDynamicComponent/GetProductNavigateDetailJson",
imageURL = "www.website.com/";
$.ajax({
url: postUrl,
type: "POST",
data: { skus: skuList },
dataType: "json",
success: function(result) {
if (result[0] != null) {
for (let i = 0; i < skuList.length; i++) {
$('#a' + [i] + 'Price').html(result[i].FormattedPrice);
$('#a' + [i] + 'Name').html(result[i].Name);
$('#a' + [i] + 'Link').attr('href', result[i].NavigateUrl);
$('#a' + [i] + 'Image').attr('src', imageURL + result[i].ImagePath);
}
}
},
error: function(jqXhr, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
}
getProductNavigateDetail('160555,665087,159816,482743,228984,519217');
Trying to figure out a way to get the implementation of the first but just using a short iteration with jQuery. Any tips, advice or scenarios to look at would be gladly appreciated!
Ok so result is the response from the AJAX request, and I'm assuming this is an array of products. such as:
[ { FormattedPrice: 'somethin', Name: 'someName' } ]
What you send as data is a comma-seperated list of SKUs ('160555,665087,159816,482743,228984,519217'). Firstly, you assume that the result you get back is in the exact same order as your comma-seperated list you sent in, and that it will always contain the same number of products as you have asked for. If any products are missing from the database, and your array is 1 less than you expect, you will get an error in your loop as your try and access that missing array entry...
Secondly, your loop is not going to implement the exact same thing as what is done in the original code (the div ID's can start with either a, b or c, and then it jumps from results[2] to results[14]). So I am unsure how you are going to target the correct div ID with only the index of the array you are looping through unless it follows a strict pattern.
So overall I'm not entirely sure what you need to achieve and it would be hard to write the code for you without seeing the full result object and your front-end HTML.

Sending an array in POST body

Im trying to send an array to my Node/MongoDB server via and AJAX POST request. The body also contains other variables. Here is the client side JS code:
function setupForm(){
$("#add").submit(function(event) {
event.preventDefault();
var name = $("#name").val();
var logo = $("#logo").val();
var phone = $("#phone").val();
var email = $("#email").val();
var address = $("#address").val();
var postcode = $("#postcode").val();
var openingHours = $("#openingHours").val();
var loc = [44, 44];
$.ajax({
type: "POST",
url: "http://localhost:3000/services",
data: "name=" + name + "&logo=" + logo + "&phone=" + phone + "&email=" + email + "&address=" + address + "&postcode="+ postcode +"&openingHours=" + openingHours + "&loc=" + loc,
success: function(){alert('success');}
});
});
}
And here is the the server side code:
exports.addWine = function(req, res) {
var wine = req.body;
console.log('Adding wine: ' + JSON.stringify(wine));
db.collection('services', function(err, collection) {
collection.insert(wine, {safe:true}, function(err, result) {
if (err) {
res.send({'error':'An error has occurred'});
} else {
console.log('Success: ' + JSON.stringify(result[0]));
res.send(result[0]);
}
});
});
}
It adds it to the database but in this format. I would like it in an array:
"postcode" : "ugh",
"openingHours" : "fhgfh",
"loc" : "44,44"
As mentioned, use serializeArray(). To add your extra parameter, just append it to the array as shown below.
function setupForm(){
$("#add").submit(function(event) {
event.preventDefault();
var data = $(this).serializeArray();
// add extra parameters (don't forget brackets)
data.push({ name: 'loc[]', value: 44 });
data.push({ name: 'loc[]', value: 44 });
$.ajax({
type: "POST",
url: "http://localhost:3000/services",
data: data,
success: function() {
alert('success');
}
});
});
}
If you want to continue using your method of just building the query string, you would have to add &loc[]=44&loc[]=44 but it is better in the long run to just use one of the serialize functions.
Given the data you are using, I would advise sending the data in the POST requests' body. This will retain the datatypes (array, bools, etcs) thanks to JSON.
$.post("http://localhost:3000/services", {
name: $("#name").val(),
loc: [44, 44]
...etc
}, function(){alert('success');}
);
Backend should work fine without alterations. You might need to add body-parser to your middleware stack. The body-parser middleware will transform the body into a javascript object that you can push right into your database.
Take a look at jQuery's .serialize() and .serializeArray(). They should be able to do what you're looking for.

How to get URL of Facebook Post made using Graph API?

I have been able to successfully post a status update with image to Facebook using the graph API via an AJAX call. Now I would like to get the URL of the post, and redirect the user to the post as soon as it has been made, but I can't figure out how to get the URL. I thought the URL would be included in the response success data object, but I have tried iterating through it, and all I got was seemingly random numbers. Does anyone know how I can get the URL of the post and send the user there? Thanks. Here is my code below:
$.ajax({
url:"https://graph.facebook.com/" + userID + "/photos?access_token=" + accessToken,
type:"POST",
data:fd,
processData:false,
contentType:false,
cache:false,
success:function(data){
console.log("success " + data);
for (var key in data) {
if (data.hasOwnProperty(key)) {
var obj = data[key];
for (var prop in obj) {
// important check that this is objects own property
// not from prototype prop inherited
if(obj.hasOwnProperty(prop)){
console.log(prop + " = " + obj[prop]);
}
}
}
}
},
error:function(shr,status,data){
console.log("error " + data + " Status " + shr.status);
},
complete:function(){
console.log("Ajax Complete");
}
});

AJAX success function called successfully but does not update page properly

I have the code section below which is a simple AJAX call to retrieve a JSON string from a .ASMX VB .NET Web Method. On success, it calls the createList function below, which should take the values in the JSON string (now parsed and formatted) and add them as new list items.
My issue is that the page does not update with the new list items, even though the callback function is successful. The loop executes, data is received and I have already tested with alerts just to make sure I'm not going crazy.
When I use the exact same line (substituting test data for the JSON string) to append my new list items, everything works fine.
As a side note for anyone that might be wondering why I believe I have to use this methodology:
It is important that I call the AJAX function the way I do, so I may pass multiple parameters to the function when I build the list. The other parameters allow me to specifically find which element is active in my user control.
I am relatively new to using AJAX as well. I hope I was able to explain everything clearly.
Thanks!
function getPcList(activeRow, activeTd) {
var row = $(activeRow).attr("id");
$.ajax({
url: "AJAXWebService.asmx/getPartnerColleges",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(data) {
createList(data, activeRow, activeTd);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
function createList(data, activeRow, td) {
var obj = JSON.stringify(eval("(" + data.d + ")"));
var json = $.parseJSON(obj);
var row = $(activeRow).attr("id");
var newtd = $(td).attr("id");
for (i = 0; i < json.length - 1; i++) {
$("#"+row+ "#" + newtd + " > #list > #thelist")
.append("<li id='listitem'" + i +
"' style='width:100%; z-index:300; position:relative' onclick='txtAppend($(this).parents().eq(2))'>" +
json[i] + "</li>");
}
}
If the string returned from the server is a JSON, as indicated by the dataType field of the $.ajax() call, you shouldn't need to use JSON.stringify() and eval(). You should be able to parse the string directly with $.parseJSON().

Passing an array to a web method in Javascript

I am currently trying to pass an array that I have created in Javascript to my webmethod in my aspx.cs.
Heres what I have:
JAVASCRIPT
function callServer(requestMethod, clientRequest) {
var pageMethod = "Default.aspx/" + requestMethod;
$.ajax({
url: pageMethod, // Current Page, Method
data: JSON.stringify({ request: clientRequest }), // parameter map as JSON
type: "POST", // data has to be POSTed
contentType: "application/json", // posting JSON content
dataType: "JSON", // type of data is JSON (must be upper case!)
timeout: 60000, // AJAX timeout
success: function (result) {
ajaxCallback(result.d);
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
}
function myButtonCalls()
{
var values=[];
values[0] = "Hello";
values[1] = "goodbye";
callServer("myMethod", values);
}
ASPX.CS
[WebMethod]
public static string myMethod(string[] request)
{
return "This is test";
}
It fails before it even gets to my web method. I know this code works for regualr strings but The ajax code that uses JSON doesnt see to want to work with arrays.
Any ideas of what i need to change?
Thanks
In the aspx.cs, I needed to accept with type list not array. Thanks for the comments!

Categories

Resources