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.
Related
i am currently building an frontend app to display a generated qr code from an api. I started to implement the code but got a problem with the parsing of the response
here is the frontend code with the call
<template>
<div>
<p>test</p>
</div>
</template>
<script>
// Configuration
let myConfiguration = {
"Account" : "CH4431999123000889012",
"CreditorName" : "Muster AG",
"CreditorAddress1" : "Hauptstrasse 1",
"CreditorAddress2" : "8000 Zürich",
"CreditorCountryCode" : "CH",
"DebtorName" : "LivingTech GmbH",
"DebtorAddress1" : "Dörflistrasse 10",
"DebtorAddress2" : "8057 Zürich",
"DebtorCountryCode" : "CH",
"Amount" : "1.50",
"ReferenceNr" : "21000000000313947143000901",
"UnstructuredMessage" : "Mitteilung zur Rechnung",
"Currency" : "CHF",
"QrOnly" : "false",
"Format" : "PDF",
"Language" : "DE"
}
// Call function to create invoice
let myFile = generateQrInvoice(myConfiguration);
// Work with binary data
if(myFile != null) {
// ...
}
function generateQrInvoice(myRequestConfiguration) {
// Main configuration
let myEndpointUrl = "http://qrbillservice.livingtech.ch";
let myEndpointPath = "/api/qrinvoice/create/";
let myApiKey = "(falseApiKey)";
// GET parameters
let myGetParams = new URLSearchParams(myRequestConfiguration);
// Perform request
fetch(myEndpointUrl + myEndpointPath + "?" + myGetParams, {
method: "GET",
mode: "cors",
cache: "no-cache",
headers: {
"APIKEY": myApiKey,
"Accept": "application/json"
}
}).then(function (myResponse) {
try {
// Check status
if(myResponse.status == 200) {
// Read and parse JSON
let myJsonObject = JSON.parse(myResponse);
// Check if error
if(myJsonObject["isSuccessed"] == "true") {
if("base64Content" in myJsonObject && myJsonObject["base64Content"].trim() != "") {
// E.g. send file to client
let myBlob = new Blob(atob(myJsonObject["base64Content"]), {type: "application/pdf"});
let myBlobUrl = URL.createObjectURL(myBlob);
window.open(myBlobUrl);
// Return data
return atob(myJsonObject["base64Content"]);
} else {
throw "no data provided";
}
} else {
throw myJsonObject["message"];
}
} else {
throw "status code " . myResponse.status;
}
}
catch(e) {
// Handle exception
console.warn("Error: " + e.message, e);
return null;
}
}).catch(function (err) {
// Handle exception
console.warn("Error: " + err.message, err);
return null;
});
}
</script>
and here is the response i get when i inspect on the browser :
Error: Unexpected token 'o', "[object Response]" is not valid JSON SyntaxError: Unexpected token 'o', "[object Response]" is not valid JSON
at JSON.parse (<anonymous>)
at app.vue:61:42
I didn't write the apikey here but it is written on my code.
As it has been a long time since i didn't code like this, i don't really see yet how to tackle the problem. I tried to test with postman but it appears my request is not good yet.
If someone has an idea, i would be very happy to learn.
Thank you very much in advance,
Eugene
So i test myResponse and it is a JSON.
However the problem remains : i saw in the console that the api answers successfully api response
So i figured that i could just replace
let myJsonObject = JSON.parse(myResponse)
by
let myJsonObject = myResponse
and try to see what goes.
Now it goes directly in the catch(e) and send me an error response.
It looks like in my code, i don't go in the right direction to use the information i got from the api.
Here is partially the information i got : {"isSuccessed":true,"statusCode":200,"mimeType":"application/pdf","message":"QrBill is successfully generated","isQrOnly":false,"errors":"null","base64Content":(here is the content, i didn't added because it is quite long)}
my question therefore is how could recover the pdf and show it to the end user?
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 am trying to send JSON object but in result it is sending a parse error .
{"readyState":4,"responseText":"","status":200,"statusText":"OK"}
here is code
var data = {
fb_id: response.id,
email: response.email,
name: response.name,
first_name: response.first_name,
last_name: response.last_name,
verified: response.verified,
birthday:response.birthday,
picture: response.picture.data.url,
hometown: response.hometown.name,
gender: response.gender
};
$.ajax({
url:'connect.php',
type: 'POST',
data: {
user: data
},
dataType: 'JSON',
success: function(html){
//page();
console.log(JSON.stringify(data));
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
if (XMLHttpRequest.readyState == 4) {
console.log(JSON.stringify(XMLHttpRequest));
}
}
});
and the backend is here:
The JSON object is sending here
if(isset($_POST['user'])) {
//convert json object to php associative array
$data = $_POST['user'];
$fbid = $data['fb_id']; // To Get Facebook ID
$fbfullname = $data['name']; // To Get Facebook full name
$femail = $data['email']; // To Get Facebook email ID
$fbname = $data['first_name'];
$fblname = $data['last_name'];
$fbgender = $data['gender'];
$fverified = $data['verified'];
$faddress = $data['hometown'];
$fbirth = $data['birthday'];
$img = $data['picture'];
}
The object is sending something like that:
{
"fb_id":"xxxxxxxxxxx99",
"email":"sxxxxxx#xxx.in",
"name":"Sagar xxxx",
...
}
PS: I am using 1.12.4 version of jquery.min.js
Updated
When I tries to send request using this query to connect.php page it returns error in console log. and If i change dataType to "text" or exclude it then it doesn't return any error but then connect.php cannot identify any query posted using ajax request ,i.e., isset($_POST['user']) will not be able to identify any query .
In your php script add this code after reading json:
if(isset($_POST['user']))
{
//convert json object to php associative array
$data = $_POST['user'];
$fbid = $data['fb_id']; // To Get Facebook ID
$fbfullname = $data['name']; // To Get Facebook full name
$femail = $data['email']; // To Get Facebook email ID
$fbname = $data['first_name'];
$fblname = $data['last_name'];
$fbgender = $data['gender'];
$fverified = $data['verified'];
$faddress = $data['hometown'];
$fbirth = $data['birthday'];
$img = $data['picture'];
Add this code:
header("Content-Type: application/json", true);
/* Return JSON */
echo json_encode("Success");
/* Stop Execution */
exit;
}
"Success" text is sent in onSuccess(html)
I'm not a PHP expert, but could be the problem is you are sending JSON as a post body and on backend operate with it as urlencoded form.
I suppose you need to get a plain json from request, parse it to an array and then process. You can find useful example here Issue reading HTTP request body from a JSON POST in PHP
Also change dataType to "application/json"
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 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.).