i have a webservice that is returning this response :
<string xmlns="http://tempuri.org/">{ "Head":[ { "ID":"1","Name":"David"} ]}</string>
when i try to get the response back, i keep getting the error :
"missing ; before statement"
i am just starting to get into this so am probably doing something very wrong.
why is the response not working for me?
my dojo code looks like this
var targetNode = document.getElementById("foo");
var def = dojo.io.script.get({
url: "http://localhost/WebData/PublicData.asmx/HelloWorld",
timeout: 30000,
handleAs: "json",
preventCache: true,
handle: function(error, ioargs) {
var message = "";
switch (ioargs.xhr.status) {
case 200:
message = "Good request.";
break;
case 404:
message = "The requested page was not found";
break;
case 500:
message = "The server reported an error.";
break;
case 407:
message = "You need to authenticate with a proxy.";
break;
default:
message = "Unknown error.";
}
targetNode.innerHTML = message;
}
});
thanks!
david
Your server's response mixes XML-like data (<string xmlns="http://tempuri.org/">)with JSON.
For dojo to handle the response using handleAs: 'json' you will need your server to return pure JSON data only, i.e just
{ "Head":[ { "ID":"1","Name":"David"} ]}
Failing that you would need to handle the response as text, strip out the tags and then parse just the JSON content. As a general tip "missing ; before statement" usually means mal-formed JSON.
EDIT
I just noticed the first argument to your handle function is "error". The first argument to the handle function contains the server's response (In this case a javascript object based on the JSON received.).
Related
so I have been struggling with this for a couple of days and need to find a solution. I followed a tutorial on how to setup Stripe payments the code below is where I am getting the error :
var buyBtn = document.getElementById('payButton');
var responseContainer = document.getElementById('paymentResponse');
// Create a Checkout Session with the selected product
var createCheckoutSession = function(stripe) {
return fetch("stripe_charge.php", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
checkoutSession: 1,
}),
}).then(function(result) {
return result.json(); // JSON PASSED FROM HERE
});
};
// Handle any errors returned from Checkout
var handleResult = function(result) {
if (result.error) {
responseContainer.innerHTML = '<p>' + result.error.message + '</p>';
}
buyBtn.disabled = false;
buyBtn.textContent = 'Buy Now';
};
// Specify Stripe publishable key to initialize Stripe.js
var stripe = Stripe('<?php echo STRIPE_PUBLISHABLE_KEY; ?>');
buyBtn.addEventListener("click", function(evt) {
buyBtn.disabled = true;
buyBtn.textContent = 'Please wait...';
createCheckoutSession().then(function(data) { // TO HERE - ERROR IS HERE
if (data.sessionId) {
stripe.redirectToCheckout({
sessionId: data.sessionId,
}).then(handleResult);
} else {
handleResult(data);
}
});
});
So you can see above where I am trying to return the json and where I am receiving it. I have double checked the value that is being returned and it is as followed:
json result being returned
and here is the error I am getting :
checkout.php:1 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
From what I can see it seems that somewhere in the return of the data.json(). The data is being changed so that it is not accepted later in the code.
If anyone could help with this or shine some more light on the situation I would greatly appreciate it. I've had a look online loads and can't seem to find anything other than a HTML file is being passed through instead. The issue is that I don't know HOW this is happening even when looking through the debug.
Thanks a lot.
There is a result, yes, but it is not JSON. Your stripe_charge.php request is almost certainly returning an HTML page instead of the JSON you expect. The error is happening when you try to return result.json(). You need to check your network responses and debug your server code.
See here: https://www.codeproject.com/Tips/1239019/Unexpected-token-in-JSON-at-position
It may be cause because you have put your code in a custom folder.
It works for me by just removing the "/" in fetch("/create-checkout-session.php", {method: "POST",})
in the checkout.html.
I have a Logic App that gets the contents from a SharePoint (.xlsx) and posts the body to an endpoint to get processed. now the content I see is a base64-encoded file, what I wanted to do was to post this data as is.
when I try to post it using postman it gets accepted successfully but when it is posted form the Logic app I get
BadRequest. Http request failed: the content was not a valid JSON.
but I can see that the body that was meant to be sent is of the type, which is a valid Json
{
"$content-type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"$content": "AA....VeryLong...B1241BACDFA=="
}
also tried this expression
decodeBase64(triggerBody()?[body('getFile')])
but I get a different error
InvalidTemplate. Unable to process template language expressions in action 'HTTP' inputs at line '1' and column '2565': 'The template language expression 'decodeBase64(triggerBody()?[body('getFile')])' cannot be evaluated because property '{
"$content-type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"$content": "UEsDBBQABgAIAAAAIQDuooLHjAEAAJkGAAATAAgCW0Nvb...
What I want to achieve is simple really I want to post to my end point the Json as is or the contents of the base64Encoded string.
If you decode the content with base64 you will find the content is garbled. This is because the content is in ooxml format then encoded with base64. And in logic app you could not decode the ooxml.
First solution, you could use Azure Function to write a method to read the document then return the content. Then in logic app call the function to get the content.
Second solution, change your file to a directly readable file(like .txt file), this way I tried and you could parse it Json.
Can you send me your postman request save it in collect and then export as file.
I think what you can do in postman can be done in logic app too.
Or send me your code I can modify it.Make sure you have post as body and it matches the parameter of Post at web api level.
var Webrequestdata = {
"webserviceurl": "http://examplecom/u/b/b/e.ee.msg",
"username": "123"
};
$.ajax({
cache: false,
type: "POST",
url: 'http://example.com/res/api/Outlookapi',
data: JSON.stringify(Webrequestdata),
contentType: "application/json",
success: function (result) {
console.log("email sent successfully");
},
error: function (response) { alert('Error: ' + response.responseText); }
});
after looking at your statement:
Logic App gets the contents from a SharePoint (.xlsx) and posts the
body to an endpoint to get processed. now the content I see is a
base64-encoded file
i assume your endpoint is still looking for a content type -
vnd.openxmlformats-officedocument.spreadsheetml.sheet
but you are passing a Base64 String
1) check if your "content-type" header is correctly placed change it to application/json if possible
2) Make sure you are processing the base64 string correctly.
In my case, I extracted the base64 string from an image file using Javascript. I got special keys at the start of base64 string like ''data:image/png;base64','ACTUAL BASE 64 STRING...' so i removed the special keys before the actual base64 string with some regular expression.
This sample Json request might help in attaching the base64 Content
Make sure you are converting your request to JSON using JSON.stringify
//var finalString = srcData.replace('data:image/png;base64,','');
var finalString = srcData.replace(/^,+?(\,)/, '');
finalString = srcData.substring(srcData.indexOf(',')+1, srcData.length);
var data = JSON.stringify({
"requests": [
{
"image": {
"content": finalString
},
"features":
[
{
"type": "DOCUMENT_TEXT_DETECTION",
"maxResults": 1
}
]
}
]
});
This is the XMLHttpRequest i used:
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
var obj = JSON.parse(this.responseText);
try
{
//do something
}catch(err)
{
//do something
}
}
});
try {
xhr.open("POST", "https://vision.googleapis.com/v1/images:annotate?key=blablabla");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.setRequestHeader("Postman-Token", "111111111");
xhr.send(data);
}
catch(err) {
//do something
}
This is my code creating a json file:
$( ".save" ).on("click", function(){
var items=[];
$("tr.data").each(function() {
var item = {
itemCode : $(this).find('td:nth-child(1) span').html(),
itemQuantity : $(this).find('td:nth-child(4) span').html()
};
items.push(item);
});
});
Now the json object looks like:
[{"itemcode":"code1","itemquantity":"quantity1"},{"itemcode":"code2","itemquantity":"quantity2"},...]
My question is how do I parse this data in Django view?
Following is my AJAX function for reference:
(function() {
$.ajax({
url : "",
type: "POST",
data:{ bill_details: JSON.stringify(items),
calltype:'save'},
dataType: "application/json", // datatype being sent
success : function(jsondata) {
//do something
},
error : function() {
//do something
}
});
}());
Since I'm sending multiple AJAX request to the same view, I need the 'calltype' data as well.
Thanks you on your answer!! BTW, I badly need to know this simple stuff, which I'm missing
This is my code snippet for parsing:
if (calltype == 'save'):
response_data = {}
bill_data = json.loads(request.POST.get('bill_details'))
itemcode1=bill_details[0]['itemCode']
#this part is just for checking
response_data['name'] = itemcode1
jsondata = json.dumps(response_data)
return HttpResponse(jsondata)
The error being raised is
string indices must be integers
Request your help
For your reference, this is my POST response (taken from traceback):
bill_details = '[{"itemCode":"sav","itemQuantity":"4"}]'
calltype = 'save'
csrfmiddlewaretoken = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
EDITED Django View
This is my edited view:
if (calltype == 'save'):
bill_detail = request.POST.get('bill_details')
response_data = {}
bill_data = json.loads(bill_detail)
itemcode1=bill_data[0]['itemCode']
#this part is just for checking
response_data['name'] = itemcode1
jsondata = json.dumps(response_data)
return HttpResponse(jsondata)
I fail to understand the problem. SO, to solve it, my question: what is the datatype of the return for get call and what should be the input datatype for json.loads. Bcoz the error being shown is json.loads file has to be string type!! (Seriously in limbo)
Error:
the JSON object must be str, not 'NoneType'
I'm new to JSON and have been using it with MVC3 ASP.NET but could somebody shed some light on how to return an error per a JSON result?
I have the following call from my View:
$.ajax({
type: "POST",
dataType: "json",
url: "EditJSON",
data: { FilmID: InputFilmID, Title: InputTitle, Description: InputDescription},
success: function (result) {
alert(result.Message + " updating film " + result.Title);
window.location = "../All";
},
error: function (error) {
alert('error');
}
});
Controller handles the request as a success. What would I pass back for a JSON error so that the error: function handled back at the View?
[AcceptVerbs("POST")]
public JsonResult EditJSON(BobsMoviesMVC2.Models.Film film)
{
filmRepository.Update(film);
return Json(new {Message = "Success", Title = film.Title });
// What would I return for an error here?
}
Thanks!
jQuery uses the HTTP response code to determine success or failure.
HTTP response codes >= 400 are considered errors. HTTP response codes >= 200 and < 400 are considered successes.
Return appropriate HTTP codes from your server-side code to get the behavior you're after.
Confirmed, in .NET you can put:
Response.StatusCode = (int)HttpStatusCode.InternalServerError,
or whatever error status code you wish, right before your JSON return statement. (Thank you Mariah).
Check out the 'error' option of the jquery ajax call to see what you can do with the resulting error on the client-side.
A header with a status code other than 2xx or 3xx, probably a 5xx or 4xx error code.
i have a webservice that is returning this response :
<string xmlns="http://tempuri.org/">{ "H...[ { "ID":"1","Name":"Test"} ]}</string>
when i try to get the response back, i keep getting the error :
"missing ; before statement"
i am just starting to get into this so am probably doing something very wrong.
why is the response not working for me?
my dojo code looks like this
var targetNode = document.getElementById("foo");
var def = dojo.io.script.get({
url: "http://localhost/WebData/PublicData.asmx/HelloWorld",
timeout: 30000,
handleAs: "json",
preventCache: true,
handle: function(error, ioargs) {
var message = "";
switch (ioargs.xhr.status) {
case 200:
message = "Good request.";
break;
case 404:
message = "The requested page was not found";
break;
case 500:
message = "The server reported an error.";
break;
case 407:
message = "You need to authenticate with a proxy.";
break;
default:
message = "Unknown error.";
}
targetNode.innerHTML = message;
}
});
thanks!
david
The get function is trying to parse the response as pure json, as the handleAs attribute is set to 'json'; but the response actually is an xml document containing some json text, causing the error you have.
Either change the response to pure json, like this:
{ "H": [ { "ID":"1","Name":"Test"} ]}
or set the handleAs attribute to 'xml' and parse the response to extract the json content; you can then unmarshall the json string using dojo.fromJson.