Pairs key=value are splitting by each symbol code when Ajax call - javascript

Can't understand why my key=value pairs transform into symbols and in my ajax GET call I have:
GET /admin_schedule/get_schedule_db/?0=%5B&1=o&2=b&3=j&4=e&5=c&6=t&7=+&8=O&9=b&10=j&11=e&12=c&13=t&14=%5D&15=%22&16=%26&17=t&18=e&19=a&20=c
Instead of:
GET /admin_schedule/get_schedule_db/?teacherArray[]=128&teacherArray[]=134...
My code:
var eventss = '';
$("input[type='checkbox'][name='teacher']").each( function() {
if(this.checked) {
eventss += "&teacherArray[]=" + $(this).attr("value");
}
});
events1.data += eventss;
ajax for fullcalendar eventSources:
var events1 = {
url: '/admin_schedule/get_schedule_db/',
type: 'GET',
data: {sch_teacher_id: (sch_teacher_id) ? sch_teacher_id : $('.teacher').val() },
success: function (response) {
return response;
}
};
And then fetch fullcalendar with events
eventSources: [
events1,
events2,
events3
],

Concatenating a string with an object is almost never a good idea as Object#toString always returns "[object Object]". Unless you override toString in your object, the object is cast to string as this string (meaning its content is lost) before it's concatenated. Moreover, the resulting string is not a valid query string.
Instead of
eventss += "&teacherArray[]=" + $(this).attr("value");
...
events1.data += eventss;
try creating an empty teacherArray in data and
events1.data.teacherArray.push($(this).attr("value"));
Also consider using $("#my-form").serialize()

I solved this problem! (thx Jan Dvorak for your comments!).
1. variable now is an array:
var sch_teacher_id = new Array("<?php echo $sch_teacher_id; ?>");
2. empty the array each time before loop:
$('.teacher').change(function (event) {
events1.data.sch_teacher_id = [];
events2.data.sch_teacher_id = [];
events3.data.sch_teacher_id = [];
if($(this).val()) {
$("input[type='checkbox'][name='teacher']").each( function() {
if(this.checked) {
events1.data.sch_teacher_id.push($(this).attr("value"));
events2.data.sch_teacher_id.push($(this).attr("value"));
events3.data.sch_teacher_id.push($(this).attr("value"));
}
});
}
$calendar.fullCalendar('refetchEvents');
});

Related

Array value becomes null while passing from Ajax

I am making an ajax call in my javascript submit function. In this ajax call, I am passing an array(globalSelection) as data to the servlet. This array consists elements of function textSelection which is also pasted below.
globalSelection =[];
function submit() {
console.log("globalSelection start")
console.log(globalSelection)
console.log("globalSelection end")
$.ajax({
async : false,
type : "POST",
url : 'http://example.com:8080/myApp/DataServlet',
data: {globalSelection:globalSelection},
success : function(data) {
alert(data)
},
error : function(data, status, er) {
alert("error: " + data + " status: " + status + " er:" + er);
}
});
}
function textSelection(range, anchorNode, focusNode) {
this.range = range;
this.type = 3;
this.rCollection = [];
this.textContent = encodeURI(range.toString());
this.anchorNode = anchorNode;
this.focusNode = focusNode;
this.selectionId = getRandom();
this.yPOS = getYPOS();
this.getTagName = function(range) {
var el = range.startContainer.parentNode;
return el;
}
this.getTagIndex = function(el) {
var index = $(el.tagName).index(el);
return index;
}
this.simpleText = function(node, range) {
if (!node)
var entry = this.createEntry(this.anchorNode, this.range);
else
var entry = this.createEntry(node, range);
this.rCollection.push(entry);
this.highlight(this.rCollection[0].range);
this.crossIndexCalc();
textSelection._t_list.push(this);
pushto_G_FactualEntry(this);
}
this.compositeText = function() {
this.findSelectionDirection();
var flag = this.splitRanges(this.anchorNode, this.focusNode,
this.range.startOffset, this.range.endOffset);
if (flag == 0) {
for (j in this.rCollection) {
this.highlight(this.rCollection[j].range);
}
}
this.crossIndexCalc();
textSelection._t_list.push(this);
pushto_G_FactualEntry(this);
}
}
I am ading the screen of my browser console below, which prints the globalSelection(array).
In my servlet I am getting this array as follows
String[] arrays = request.getParameterValues("globalSelection[]");
System.out.println(arrays);
Here I am getting null value for arrays.
If I put globalSelection as follows in submit function for simple test to servlet, I am able to get the arrays.
var globalSelection = ["lynk_url", "jsonBody", "lynk_dummy1", "lynk_dummy2", "lynk_name", "lynk_desc", "lynk_flag"];
Why my actual globalSelection is shows null in servlet, what I am doing wrong here.
Try with :
String[] arrays = request.getParameterValues("globalSelection");
System.out.println(arrays);
Because the parameter submitted with name "globalSelection" only not "[]" symbol.
I see your problem and I have a simple solution.
I recommend in that case that you convert the array as a string in JS:
JSON.stringify(globalSelection)
and then reconstructing the object on the backend using some sort of library for JSON conversion like: https://code.google.com/archive/p/json-simple/
You could then do something like this:
JSONArray globalSelection = (JSONArray) new JSONParser().parse(request.getParameter("globalSelection"));
Iterator i = globalSelection.iterator();
while (i.hasNext()) {
JSONObject selection = (JSONObject) i.next();
String type = (String)selection.get("type");
System.out.println(type);
}
This will parse your array and print the selection type. Try it, hope it helps.

Put XMLHttprequest results into one string

I'm trying to get my array of URL's to run through a JQuery .get function to get the site's source code into one string outside of the function. My code is below.
var URL = ["http://website.org", "http://anothersite.com"];
var array = URL.map(function(fetch) {
var get = $.get(fetch, function(sourcecode) {
sourcecode = fetch;
}
I need the sourcecode variable to be the combination of source code on all of the URLs in the array.
You need to put a variable outside of the function, something like this data variable below and append to it with +=:
var URL = ["http://website.org", "http://anothersite.com"];
var array = URL.map(function(fetch) {
var data = null;
var get = $.get(fetch, function(sourcecode) {
data += fetch;
}
}
Try this like,
var URL = ["http://website.org", "http://anothersite.com"];
var array = $(URL).map(function(fetch) {
var data='';
$.ajax({
url:fetch,
async:false,
success : function(d){
data=d;
}
});
return data;
}).get();
Since you're using jQuery, I suppose that jQuery.each() may be a better way to iterate over the array.
var URL = ["http://website.org", "http://anothersite.com"];
var str = [];
$.each(URL, function(index, fetch) {
$.get(fetch, function(sourcecode) {
str.push(sourcecode); // if you want an array
})
});
str.join(''); // if you want a string
console.log(str);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

How to call server side function from json?

this is my code
<script type="text/JavaScript">
var myarray = new array();
function getsvg1() {
$.ajax({
alert("hello");
type: "post",
url: "WebForm1.aspx/getsvg1",
alert("abc");
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var cars = response.d;
alert(cars);
alert("hi");
},
failure: function (msg) {
$('#output').text(msg);
}
});
}
</SCRIPT>
webservices
[System.Web.Services.WebMethod]
public static ArrayList getsvg1()
{
XDocument doc = XDocument.Load(System.Web.HttpContext.Current.Server.MapPath("~/NewFolder1/10000.svg"));
//XDocument doc = XDocument.Load(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/Orders/100001_PRO/2/svg0.svg"));
//XNamespace ns1 = "http://www.w3.org/2000/svg";
//Namespace of a root element can also be retrieved like this:
//XNamespace ns1 = doc.Root.GetDefaultNamespace();
//var g = doc.Descendants(ns1 + "image").FirstOrDefault();
// XDocument doc = XDocument.Load(Server.MapPath("~/excelfiles/svg0.svg"));
XNamespace ns1 = "http://www.w3.org/2000/svg";
//Namespace of a root element can also be retrieved like this:
//XNamespace ns1 = doc.Root.GetDefaultNamespace();
var retrieveimage = doc.Descendants(ns1 + "image").FirstOrDefault();
var retrivetext = doc.Descendants(ns1 + "g").FirstOrDefault();
ArrayList arlelem = new ArrayList();
foreach (XElement element in doc.Descendants(ns1 + "g"))
{
//string[] parts = element.Split(',');
Console.WriteLine(element);
arlelem.Add(element);
}
// var retrivetext1 = doc.Descendants(ns1 + "text").SelectMany(i => i.ElementExtensions.Select(e => e.GetObject<XElement>().Attribute("url").Value)).ToArray();
//var retrivetext = doc.Descendants(ns1 + "text").All();
string v = arlelem[1].ToString();
string values = retrieveimage.ToString();
string values1 = retrivetext.ToString();
char[] delimiterChars1 = { ' ', ',', '"', '\\', '\t', '=' };
//string text = "one\ttwo three:four,five six seven";
//System.Console.WriteLine("Original text: '{0}'", text);
string[] words = values.Split(delimiterChars1);
string[] words2 = values1.Split(delimiterChars1);
string[] newword = v.Split(delimiterChars1);
//Session["newimgwidth"] = words[15];
return arlelem;
}
alert is not coming for cars values and breakpoint not going for success and failure. in this example i m calling server side function from
json that function result
To start with your ajax request is filled with syntax errors.
The $.ajax({ }) block cannot have a alert("hello"); inside it
Remove alert("abc"); too
use console.log() instead of alerts in your success method, this is not one of the error but a suggestion/advice.
What is your method returning in case of error ? In your ajax error method it seems to be expecting a string value.
Why are you using type: "post" when you are not posting any data to your method. Use a 'get' instead.
To debug your server side code, try opening the WebForm1.aspx/getsvg1 url in your browser window and see if you get the expected response. If all is well next try sending an ajax request using a client like postman rest client to check the response again.
Hope this helps.
you can use jQuery for this:
$.getJSON( "http://server.com/webservice", function( data ) {
console.log(JSON.stringify(data));
}
See more details at: http://api.jquery.com/jquery.getJSON/
{key,value } it allow json data.means already availble options or new define json value only. you can enter,if you try to alert("hello") it doest allow.so it stopped.so,try without alert message use inside brackets {}.

Get JSON data from another page via JavaScript

I have a page where I want to add couple of controls
when I click on 1st control, I want my javascript to open particular JSONpage, gram the content and then output the content in specific <DIV id="one">. Then, when I select some of the elements in div id="one", I want The JavaScript to connect to another JSON page and get another array of data from there.
My question - how do I do the JSON part?
In other words, how do I get JavaScript version of:
$dataSet = json_decode(file_get_contents($url), true);
I am new to JavaScript and this thing takes so much time!!
Got this working
function getDates() {
jQuery(function($) {
$.ajax( {
url : "jsonPage.php",
type : "GET",
success : function(data) {
// get the data string and convert it to a JSON object.
var jsonData = JSON.parse(data);
var date = new Array();
var i = -1;
$.each(jsonData, function(Idx, Value) {
$.each(Value, function(x, y) {
if(x == 'date')
{
i = i + 1;
date[i] = y;
}
});
});
//output my dates; [0] in this case
$("#testArea").html(date[0]);
}
});
});
}

How to format jquery ui autocomplete with function that returns json?

I have a function that makes an AJAX call and returns the data as JSON.
Donor.prototype.GetFriends = function(callback)
{
$.post(apiUrl + "getfriends",
{
"authentication_code" : this.authcode
},
function(response)
{
if (response)
{
callback(response.result);
}
}, "json");
}
Now in my UI I have the following:
var donor = new Donor();
$("#msg-to").autocomplete({source: function()
{
donor.GetFriends(function(response){response.friends.candidates})
}
});
But this is not working...The json is being returned in firebug, but not displaying in the autocomplte field.
result
Object { error_state=0, friends={...}, error_msg=""}
error_msg
""
error_state
0
friends
Object { candidates="[{"follow_id":"3","0":"...","6":"227.jpg"},false]", donors="[{"follow_id":"4","0":"...","6":"224.jpg"},false]"}
candidates
"[{"follow_id":"3","0":"3","user_id":"227","1":"227","following":"222","2":"222","candidate_id":"61","3":"61","firstname":"Helen","4":"Helen","lastname":"Hunt","5":"Hunt","image":"227.jpg","6":"227.jpg"},{"follow_id":"5","0":"5","user_id":"225","1":"225","following":"222","2":"222","candidate_id":"55","3":"55","firstname":"Test","4":"Test","lastname":"Candidate","5":"Candidate","image":"225.jpg","6":"225.jpg"},{"follow_id":"1","0":"1","user_id":"222","1":"222","following":"226","2":"226","candidate_id":"59","3":"59","firstname":"New","4":"New","lastname":"Candidate","5":"Candidate","image":"226.jpg","6":"226.jpg"},{"follow_id":"6","0":"6","user_id":"222","1":"222","following":"227","2":"227","candidate_id":"61","3":"61","firstname":"Helen","4":"Helen","lastname":"Hunt","5":"Hunt","image":"227.jpg","6":"227.jpg"},false]"
donors
"[{"follow_id":"4","0":"4","user_id":"224","1":"224","following":"222","2":"222","donor_id":"124","3":"124","firstname":"Just","4":"Just","lastname":"A Donor","5":"A Donor","image":"224.jpg","6":"224.jpg"},{"follow_id":"2","0":"2","user_id":"222","1":"222","following":"224","2":"224","donor_id":"124","3":"124","firstname":"Just","4":"Just","lastname":"A Donor","5":"A Donor","image":"224.jpg","6":"224.jpg"},false]"
Also the json that is returned has a candidate_id, firstname, lastname and imageUrl returned, how can I have these displayed in the results, with the friend_id being the value and the others for display?
Thanks in advance...
Couple of things:
You might need to return the array you're creating in order for the autocomplete to use it
You also need to make sure the array of objects has the correct keys for the autocomplete to use
The minimum required keys that need to available for the autocomplete to work correctly are 'label' and 'value'. Other keys can be included, and can be fetched during an event like select or change.
As an example, I might try something like the following. Adjust your GetFriends function to use the request and response callback functions provided by jQuery automatically, and then feed the formatted data that the autocomplete needs back to them:
Donor.prototype.GetFriends = function(request, response){
// this is where you can grab your search term, if need be...
var search_term = request.term;
$.post(
apiUrl + "getfriends",
{"authentication_code" : this.authcode},
function(data)
{
// process your data here into an array that the autocomplete
// will appreciate...
var autocomplete_array = [];
$.each(data.friends.candidates, function(index, candidate)
{
autocomplete_array.push(
{
label: candidate.firstname + " " + candidate.lastname,
value: candidate.user_id,
another_key: candidate.follow_id,
and_another: candidate.image
});
});
// now send the array back to the response parameter...
response(autocomplete_array);
},
"json"
);
};
Then, I'd simplify the autocomplete initializer parameters to include your function:
$("#msg-to").autocomplete({source: donor.GetFriends});
As an additional note, to get to the keys of the items, you could modify your autocomplete field to include the select or change event handlers I mentioned earlier:
$("#msg-to").autocomplete(
{
source: donor.GetFriends
select: function(event, ui){
alert("You selected: " + ui.item.label);
// or...
alert("You selected: " + ui.item.another_key);
}
});
Hope this helps, and that I didn't have a type-o's! :)
The problem is that $.post method works asynchronously. So when autocomplete tries to get data, your function makes POST call and returns empty result. To solve this try adding "async:false" option to .post call or:
Donor.prototype.GetFriends = function(callback) {
$.ajaxSetup({async:false});
$.post(apiUrl + "getfriends",
{
"authentication_code" : this.authcode
},
function(response)
{
if (response)
{
callback(response.result);
}
}, "json");
}​
You have to use the setter in the callback (see the 2nd source parameter in my examples) to add the list. If you use arrays to fill the autocomplete, the array needs objects with a label property. If this works you can add the value property too.
1.) If you can update the result of the ajax-result on server-side, change the result to:
friends
Object { candidates=Array { Object { "label": "Helen Hunt" }, ... }, donors=... }
Then your javascript can be:
var donor = new Donor();
$("#msg-to").autocomplete({
source: function(request, setter) {
donor.GetFriends(function(response) {
// set list
setter(response.friends.candidates);
});
}
});
2.) If you can't make changes at the ajax result and candidates is already an array:
var donor = new Donor();
$("#msg-to").autocomplete({
source: function(request, setter) {
donor.GetFriends(function(response) {
// create autocomplete list
var list = response.map(function(element) {
return {
label: element.firstname + ' ' + element.lastname
};
});
// set list
setter(list);
});
}
});
3.) Otherwise (if candidates is a string) [try this first]:
var donor = new Donor();
$("#msg-to").autocomplete({
source: function(request, setter) {
donor.GetFriends(function(response) {
// parse json string
var jsonresult = $.parseJSON(response);
// create autocomplete list
var list = jsonresult.map(function(element) {
return {
label: element.firstname + ' ' + element.lastname
};
});
// set list
setter(list);
});
}
});

Categories