Error unexpected token when posting JSON string to JSP - javascript

Here's my code:
var polylineStringified = JSON.stringify(polyPath.getArray());
$.ajax({
type: 'POST',
url: 'jsonposttest.jsp',
data: { Polyline: polylineStringified },
dataType: 'json',
success: function(json) {
alert('json from post test: ' + JSON.stringify(json));
}, error: function(xhr, ajaxOptions, thrownError){
alert('Error xhr : ' + xhr.status);
alert('Error thrown error: ' + thrownError);
}
});
And serverside:
<%
String test;
test = getRequest(pageContext, "Polyline");
response.setContentType("application/json");
%>
[
{"val": "Got it: <%=test%>" }
]
polylineStringified looks something like this:
[{"d":41.919372021888826,"e":-87.69811456091702},{"d":41.90506457136218,"e":-87.23119561560452},{"d":41.80277524389252,"e":-87.23668877966702},{"d":41.74747099702249,"e":-87.35479180701077}]
And the error I'm getting in the console is is unexpected token d. Any ideas?

I think you are unnecessarily stringifying your javascript object. What happens if you use the following?
var polylineArray = [{
"d": 41.919372021888826,
"e": -87.69811456091702
}, {
"d": 41.90506457136218,
"e": -87.23119561560452
}, {
"d": 41.80277524389252,
"e": -87.23668877966702
}, {
"d": 41.74747099702249,
"e": -87.35479180701077
}];
$.ajax({
type: 'POST',
url: 'jsonposttest.jsp',
data: { Polyline: polylineArray },
dataType: 'json',
success: function(json) {
alert('json from post test: ' + JSON.stringify(json));
}, error: function(xhr, ajaxOptions, thrownError){
alert('Error xhr : ' + xhr.status);
alert('Error thrown error: ' + thrownError);
}
});
EDIT: Here's another example, which you can try at jsFiddle.
It should be quite straightforward, so you can compare it to yours at each step to find what is wrong in your situation.
jQuery(document).ready(function ($) {
var Q = function (d, e) {
this.d = d;
this.e = e;
}
var data = [];
for (var i = 0; i < 5; i++) {
var r1 = 100 * (2*Math.random() - 1);
var r2 = 100 * (2*Math.random() - 1);
data.push(new Q(r1, r2));
}
console.log("About to send data", data);
$.ajax({
type: 'POST',
url: '/echo/json/',
data: {
Polyline: data
},
dataType: 'json',
//processData: false,
success: function (data, textStatus, jqXHR) {
console.log("success", data, textStatus, jqXHR);
//alert('json from post test: ' + JSON.stringify(data));
},
error: function (xhr, ajaxOptions, thrownError) {
console.log("error", xhr, ajaxOptions, thrownError);
//alert('Error xhr : ' + xhr.status);
//alert('Error thrown error: ' + thrownError);
}
});
});

Related

How to avoid repeating the same $.ajax() call

I have two $.ajax() calls in my javascript code.
$.ajax({
url: 'http://localhost/webmap201/php/load_data.php',
data: {
tbl: 'district'
},
type: 'POST',
success: function(response) {
console.log(JSON.parse(response));
json_district = JSON.parse(response);
district = L.geoJSON(json_district, {
onEachFeature: return_district,
});
ctl_layers.addOverlay(district, "district", "Overlays");
ar_district_object_names.sort();
$("#text_district_find_project").autocomplete({
source: ar_district_object_names,
});
},
error: function(xhr, status, error) {
alert("Error: " + error);
}
}
);
$.ajax({
url: 'http://localhost/webmap201/php/load_data.php',
data: {
tbl: 'province'
},
type: 'POST',
success: function(response) {
console.log(JSON.parse(response));
json_province = JSON.parse(response);
province = L.geoJSON(json_province, {
onEachFeature: return_province,
});
ctl_layers.addOverlay(province, "province", "Overlays");
ar_province_object_names.sort();
$("#text_province_find_project").autocomplete({
source: ar_province_object_names,
});
},
error: function(xhr, status, error) {
alert("Error: " + error);
}
}
);
changes on both ajax are as below:
tbl: 'district' -> tbl: 'province'
json_district -> json_province
return_district -> return_province
(district, "district", "Overlays") -> (province, "province", "Overlays")
ar_district_object_names -> ar_province_object_names
$("#text_district_find_project") -> $("#text_province_find_project")
Is there a way I can call this $.ajax() inside a function with one parameter and call the function afterwards. As an example:
function lyr(shpName){
$.ajax({
url: 'http://localhost/webmap201/php/load_data.php',
data: {
tbl: `${shpName}`
},
type: 'POST',
success: function(response) {
console.log(JSON.parse(response));
json_shpName = JSON.parse(response);
shpName = L.geoJSON(json_shpName, {
onEachFeature: return_shpName,
});
ctl_layers.addOverlay(shpName, `${shpName}`, "Overlays");
ar_shpName_object_names.sort();
$("#text_shpName_find_project").autocomplete({
source: ar_shpName_object_names,
});
},
error: function(xhr, status, error) {
alert("Error: " + error);
}
}
);
}
lyr (district);
Can I use template strings? Can I use that a function inside a function. Any help would be highly appriceated.
Create a function for ajax call.
For eg.:-
function serviceajaxjson(_successfun, _failurefun, _url, _data, _async, _global) {
if (_successfun == null) _successfun = ajax_return_successfun;
if (_failurefun == null) _failurefun = ajax_return_failurefun;
if (_global != false) { _global = true; }
if (_async != false) { _async = true; }
$.ajax({
type: "POST",
url: _url,
data: _data,
global: _global,
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
async: _async,
success: _successfun,
error: ajax_return_error,
failure: _failurefun
});
}
function ajax_return_successfun(response) {
console.info("success for " + response.d);
}
function ajax_return_failurefun(response) {
console.error("failuer occoured for " + response);
}
function ajax_return_error(response) {
console.warn("error occoured for " + response);
}
// // // call the above function
function myResponseFn(response){
if(response.data){
// // your code...
}
}
var data = "{'tbl': 'district'}";
serviceajaxjson(myResponseFn,myResponseFn,"http://localhost/webmap201/php/load_data.php",data);
If you're using latest version of popular browser (IE's dead, use Edge instead), then the simplest answer is yes. You might need some tweaking on the parameters and its use, but it should work

executing function after function with ajax call has completed

I want to know which way is the best way to execute a function when a function with the ajax call has completed.
My code:
jQuery.when(AjaxCallToBokningar()).done(function () {
console.log("AjaxCallComplete");
});
function AjaxCallToBokningar() {
var url = `${_spPageContextInfo.webAbsoluteUrl}/_api/web/lists/getbytitle('Bokningar')/items
var call = jQuery.ajax({
url: url,
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
});
//Done
call.done(function (data, textStatus, jqXHR) {
//Filling globalArray
window.globalBokningsArray = data.d.results;
});
//Fail
call.fail(function (jqXHR, textStatus, errorThrown) {
console.log('Loading Bokningar content faild: ' + textStatus + jqXHR.responseText);
});
}
Am I on the right track or is there a better way?
If you want to be able to make the Ajax call and then call a function when it's complete you can use a function reference as a parameter and do it like this...
function AjaxCallToBokningar(doneCallback) {
var url = `${_spPageContextInfo.webAbsoluteUrl}/_api/web/lists/getbytitle('Bokningar')/items
var call = jQuery.ajax({
url: url,
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
});
//Done
call.done(function (data, textStatus, jqXHR) {
//Filling globalArray
window.globalBokningsArray = data.d.results;
doneCallback();
});
//Fail
call.fail(function (jqXHR, textStatus, errorThrown) {
console.log('Loading Bokningar content faild: ' + textStatus + jqXHR.responseText);
});
}
Then you can call it like this...
function ajaxCallComplete1() {
// this is executed after the 1st call is done - do something here
}
function ajaxCallComplete2() {
// this is executed after the 2nd call is done - do something here
}
AjaxCallToBokningar(ajaxCallComplete1);
AjaxCallToBokningar(ajaxCallComplete2);
or...
AjaxCallToBokningar(function() {
// this is executed after the call is done - do something here
});
You can also try something like this: (not tested)
function ajaxCallToBokningar() {
var url = `${_spPageContextInfo.webAbsoluteUrl}/_api/web/lists/getbytitle('Bokningar')/items`;
var options = {
url: url,
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
};
return jQuery.ajax(options);
}
function updateBoknigarArray(data) {
window.globalBokningsArray = data.d.results;
}
function showError(jqXHR, textStatus, errorThrown) {
console.log('Loading Bokningar content faild: ' + textStatus + jqXHR.responseText);
}
ajaxCallToBoknigar()
.done(updateBoknigarArray)
.fail(showError)

How can I succesfully update multiple items on a sharepoint list using AJAX?

Apologies as I have already asked a v. similar question.
I am trying to update a sp list with the following javascript/ajax. It succeeds until it gets to the ajax function, which is where it fails. It goes down the error route and in "alert(err.Message)" it posts "undefined"
Any help appreciated.
<script type="text/javascript">
function updateMultipleListItems(){
var listName="Address Validation";
//CustomerNumber.val("16");
var CustomerNumber="CustNum";
$.ajax({
url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items?$select=ID&$filter=Cust_x0020_Number eq 17",
type: "GET",
headers: {
"Accept": "application/json;odata=verbose",
},
success: function (data) {
for (var i = 0; i < data.d.results.length; i++) {
var item = data.d.results[i];
alert("1");
var itemType = GetItemTypeForListName(listName);
alert("2");
var ItemId = item.ID;
alert("3");
var item = {
"__metadata": {
"type": 'SP.Data.Address%20ValidationListItem'
},
"assign": "testinput"
};
alert("4");
$.ajax({
url:_spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items('" + ItemId + "')",
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(item),
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"X-HTTP-Method": "MERGE",
"If-Match": "*"
},
success: function (data) {
console.log('Update Success');
alert("Success");
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
}
},
error: function (data) {
alert("Error");
}
});
}
function GetItemTypeForListName(name) {
return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "ListItem";
}
</script>
What I'm trying to do:
I am trying to update all records in a list where the cust_number (a column in the list) field is 17 so that assign (another column) = "testinput".
eg:
Cust Number| Assign
17 | testinput
1 |
17 | testinput
So I found out that my metadata type was incorrect. I went to the following url:
sitename/apps/reserve/_api/lists/getbytitle('Address%20Validation')?$select=ListItemEntityTypeFullName
From here I found the correct ListItem type.
Thanks,
Kieran

jquery autocomplete - save data to DB when list item is clicked (select event)

i've read a lot about jq autocomplete, but it seems, there is no way to make an ajax request while the select event is fired.
I will write the search query into an DB-Table only when the element is clicked.
Firebug shows the url in redGET http://server.ccc/api/my/logSearchQuery?a=searchquery&b=11&v=0
$(document).ready(function(e){
var results = [];
var _request = null;
$("#input").autocomplete({
source: function( request, response ) {
_request = request;
$.ajax({
url: "http://dataserver",
dataType: "jsonp",
jsonp: 'json.wrf',
data: {
q: GenerateSearchQuery(request.term)
},
success: function( data ) {
results = $.map(data.response.docs, function(item) {
return {
label: item.Name,
value: {
id:cid
}
};
});
response(results);
}
});
},
minLength: 3,
select: function( event, ui ) {
event.preventDefault();
// ---------------- here is what i've tried, but it fails----------------------
$.ajax({
url: "api/my/logSearchQuery",
type: "get",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: {"a": encodeURIComponent(_request.term), "b": results.length, "v": 0},
success: function(data){
console.log(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(XMLHttpRequest+ " : "+ errorThrown + " : " + textStatus);
}
});
if (ui.item.value != "searchAll") {
self.location = "/list/"+ui.item.value.id;
} else {
$('#searchForm').submit();
}
}
});});
The Ajax call works into the source event, but thats not the right place i think.
The ajax errors are empty.
Please help.
Yes, i am a beginner;-)
The problem was, that the code under the ajax call...
select: function( event, ui ) {
event.preventDefault();
// ---------------- here is what i've tried, but it fails----------------------
$.ajax({
url: "api/my/logSearchQuery",
type: "get",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: {"a": encodeURIComponent(_request.term), "b": results.length, "v": 0},
success: function(data){
console.log(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(XMLHttpRequest+ " : "+ errorThrown + " : " + textStatus);
}
});
//----------this part---------------
if (ui.item.value != "searchAll") {
self.location = "/list/"+ui.item.value.id;
} else {
$('#searchForm').submit();
}
}
gets fired during the ajax call is working (asynchronous).
So i've putted the this part into the complete: event of $.ajax
complete: function(xhr, status){
if (ui.item.value != "searchAll") {
self.location = "/some /"+ui.item.value.pflnr;
} else {
$('#seachBar_searchForm').submit();
}
}
now it works fine.

jQuery.ajax converter not called

I'm having trouble with jQuery.ajax converters - I can't get my converter to be called.
I've got this jQuery AJAX code (simplified for the question) :
$.ajax({
url: "http://myurl/myservice",
dataType: "JSONP",
cache: false,
success: function (data, textStatus, jqXHR) { /* do stuff */ },
error: function (jqXHR, textStatus, errorThrown) { /* do stuff */ },
timeout: 5000,
converters: { "JSONP": myConversionFunction }
});
When I use this code, the converter function myConversionFunction isn't being called. I want to use the converter to convert dates in the response as show in other SO questions but just can't get it firing.
Using fiddler I've checked the response and it is JSONP, with content type "application/x-javascript".
Any ideas what I'm doing wrong?
Thanks,
Chris.
I think you can't overwrite jQuery's default converters like json. Introduce your own converter instead (and include text in your specifier, as in this case it's a conversion from text to your output):
$.ajax({
url: "http://myurl/myservice",
dataType: "jsonp myConversion",
cache: false,
success: function (data, textStatus, jqXHR) { /* do stuff */ },
error: function (jqXHR, textStatus, errorThrown) { /* do stuff */ },
timeout: 5000,
converters: {
"text myConversion": function(value) {
console.log("pre-processing...");
/* do stuff */
return value;
}
}
});
​
I use code like this to manage the 'd' data of asp.net:
$.ajaxSetup({
data: "{}",
dataType: "jsonp",
type: "POST",
contentType: "application/json",
converters:
{
"json jsonp": function(msg)
{
return msg.hasOwnProperty('d') ? msg.d : msg;
}
},
error: function(xhr, textStatus, errorThrown)
{
var errorMessage = "Ajax error: " + this.url + " : " + textStatus + " : " + errorThrown + " : " + xhr.statusText +
" : " + xhr.status;
if (xhr.status != "0" || errorThrown != "abort")
{
alert(errorMessage);
}
}
});
perhaps you need to make it lower case like:
converters:
{
"json jsonp": function(msg)
{
return yourfunction(msg);
}
}

Categories