I'm getting an uncaught syntax error: unexpected string the chrome console when running ajax where I am trying to add a row to the bottom of a html table with the saved data returned with json. I really can't spot it....
function create_person() {
console.log("create person is working!")
$.ajax({
url : "{% url 'tande:create_person' %}",
type: "POST",
data: { first_name : $('#person-first-name').val(), surname : $('#person-surname').val(), email : $('#person-email').val(), coach_id : $('#person-coach-id').val(), is_coach : $('#person-is-coach').val(), position : $('#person-position').val(), contract_type : $('#person-contract').val()},
success : function(json) {
$('#person-first-name').val('');
$('#person-surname').val('');
$('#person-email').val('');
$('#person-coach-id').val('');
$('#person-is-coach').val('');
$('#person-position').val('');
$('#person-contract').val('');
console.log(json);
// ERROR OCCURS ON FOLLOWING LINE
var html = '<tr><td>'+json.personid+'</td><td>'+json.personfirstname+' '+json.personsurname'</td><td>'+json.personposition+'</td><td>'+json.personcontract+'</td><td>'+json.personemail+'</td><td>'+json.personcoachid+'</td></tr>';
console.log("success");
$('div#talk').html(html);
console.log(html)
},
error : function(xhr,errmsg,err) {
// $('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+
// " <a href='#' class='close'>×</a></div>"); // add the error to the dom
console.log("uh oh");
}
});
};
The data is saved successfully and the json object is returned to the console, I just can't display it.
def create_person(request):
if request.method == "POST":
print "request post data in view"
firstname = request.POST.get('first_name')
print firstname
lastname = request.POST.get('surname')
emailadd = request.POST.get('email')
coachid = request.POST.get('coach_id')
isacoach = request.POST.get('is_coach')
positionheld = request.POST.get('position')
contracttype = request.POST.get('contract_type')
response_data = {}
starfruit = Person(first_name=firstname, surname=lastname, email=emailadd, coach_id=coachid, assign_as_coach=isacoach, position=positionheld, contract_type=contracttype)
starfruit.save()
response_data['personfirstname'] = starfruit.first_name
response_data['personsurname'] = starfruit.surname
response_data['personemail'] = starfruit.email
response_data['personcoachid'] = starfruit.coach_id
response_data['personiscoach'] = starfruit.assign_as_coach
response_data['personposition'] = starfruit.position
response_data['personcontract'] = starfruit.contract_type
response_data['personid'] = starfruit.id
# response_data = {
# ''
# }
print response_data
return JsonResponse(response_data)
else:
print "no post request in view"
return JsonResponse(response_data)
The error I'm getting in the console is just as follows:
(index):845 Uncaught SyntaxError: Unexpected string
and it refers to the line I've highlighted above
var html = '<tr><td>'+json.personid+'</td><td>'+json.personfirstname+' '+json.personsurname'</td><td>'+json.personposition+'</td><td>'+json.personcontract+'</td><td>'+json.personemail+'</td><td>'+json.personcoachid+'</td></tr>';
I'm unsure how else to approach this...
You're missing a + between json.personsurname and the following '</td><td>'.
Generally it's a really bad idea to build up HTML like that; this sort of thing is easy to miss.
Related
I am having a problem getting both of these submissions to work. I will search with one and it will be successful then when I refresh and try to search with the other one I get a url not found error. Been fighting with this all day thank you for your help
<playlist>
<input id = "url2" type = "text" name = "url"
placeholder = "Genre">
<input type = "submit" name = "button" onclick =
"test()">.
<script>
function test() {
var url2= document.getElementById("url2").value;
document.write("Generating Playlist");
setTimeout(function(){window.location=
"http://127.0.0.1:5000/recommend/genre/"+url2;}, 3000);
}
</script>
Sorry I'm new to this I didn't realize I wasn't allowed to post screenshots yet. I have 2 of these submissions one with /genre and the other with /limit, when they are alone in the code they work but when I have both of them in there one of them gives me a URL error. Here is the genre function in python.
"test()">.
#app.route("/recommend/genre/<seed_genres>")
def recommend_two(seed_genres):
endpoint_url = "https://api.spotify.com/v1/recommendations?"
limit=2
market="US"
#seed_genres="indie"
target_danceability=0.9
combo = ""
q=drake&type=artist&limit=5'
query = f'{endpoint_url}limit={limit}&market={market}&seed_genres=.
{seed_genres}&target_danceability={target_danceability}'
token = getAccessToken(clientID, clientSecret)
response =requests.get(query,
headers={"Content-Type":"application/json",
"Authorization":"Bearer " + token})
json_response = response.json()
head_one = "<h1/>"
head_two = "</h2"
for i in json_response['tracks']:
combo += (f"\"{i['name']}\" by {i['artists'][0]['name']}")
return (head_one+combo+head_two)
I am trying to replicate the following lines of python code from the https://github.com/joshfraser/robinhood-to-csv repo from GitHub in order to read my transaction history.
orders = robinhood.get_endpoint('orders')
paginated = True
page = 0
while paginated:
for i, order in enumerate(orders['results']):
executions = order['executions']
instrument = robinhood.get_custom_endpoint(order['instrument'])
fields[i + (page * 100)]['symbol'] = instrument['symbol']
for key, value in enumerate(order):
if value != "executions":
fields[i + (page * 100)][value] = order[value]
if order['state'] == "filled":
trade_count += 1
for key, value in enumerate(executions[0]):
fields[i + (page * 100)][value] = executions[0][value]
elif order['state'] == "queued":
queued_count += 1
# paginate
if orders['next'] is not None:
page = page + 1
orders = robinhood.get_custom_endpoint(str(orders['next']))
else:
paginated = False
Where we also have
def get_endpoint(self, endpoint=None):
res = self.session.get(self.endpoints[endpoint])
return json.loads(res.content.decode('utf-8'))
I have thus been working on the following iOS code. I work with this code in an XCode playground so feel free to make one to follow along
import UIKit
import PlaygroundSupport
let LoginEndpoint:String = "https://api.robinhood.com/api-token-auth/"
let LoginRequestData:[String : String] = ["username": "EmailAdress", "password": "Password"]
let OrdersEndpoint:String = "https://api.robinhood.com/orders/"
func httpReq(type: String, url: String, body:[String : String], header:[String : String]) -> ([String : Any]?, Data?, String?){
let url = URL(string: url)
var returnData:([String : Any]?, Data?, String?)? = nil
if let url = url {
var request = NSMutableURLRequest(url: url) as URLRequest
request.httpMethod = type
var postString = ""
for (key, value) in body {
if (postString != "") {
postString += "&"
}
postString += "\(key)=\(value)"
}
request.httpBody = postString.data(using: .utf8)
for (key, value) in header {
request.addValue(value, forHTTPHeaderField: key)
}
let _ = URLSession.shared.dataTask(with: request, completionHandler: {(data, response, error) in
if let data = data {
do {
let jsonSerialized = try JSONSerialization.jsonObject(with: data, options: []) as? [String : Any]
returnData = (jsonSerialized, data, nil)
} catch (_) {
returnData = (nil, data, "JSON Parse Erro")
}
} else if let error = error {
returnData = (nil, nil, error.localizedDescription)
}
}).resume()
}
while (returnData == nil) {}
return returnData!
}
let tokenQuery = httpReq(type: "POST", url: LoginEndpoint, body: LoginRequestData, header: [:])
if let token = tokenQuery.0?["token"] {
print("token \(token)")
let historyQuery = httpReq(type: "GET", url: OrdersEndpoint, body: [:], header: ["Authorization": "Token \(token)"])
if let results = historyQuery.0?["results"], let countString = historyQuery.0?["count"] {
}
}
RunLoop.main.run()
PlaygroundPage.current.needsIndefiniteExecution = true
So as you can see I am using the auth token to get to the orders endpoint. I am indeed getting a good response from the orders endpoint but I have no clue how to interpret it.
It would seem from the python code that it is returning an array of JSON objects however I cant figure out how to get to that array in swift. I am not even sure if I am decoding it properly. The funny thing is when you look at the object returned in Playgrounds it would seem XCode knows that there is an array going on. How do I get to it?
Can't really get a good idea of the information being returned by your service, because of the lack of credentials.
However, check out SwiftyJSON. It's a really good library, and is extremely helpful with handling JSON data in Swift. It should solve your JSON handling issues.
The API returns both JSON and also render the template and when i call $.getJSON it will only return that render template but not JSON value. I have tried this
if request.args['type'] == 'json':
return json.dumps(group)
else:
return render_template("/c.., summary=json.dumps(group))
but it says
bad request
Is there any way I can get that JSON value whenever I need it?
This is my view
#cms.route('/add/asset/<client_id>', methods=["GET"])
#login_required
def asset_add(client_id):
if int(current_user.id_) == int(client_id):
group = {}
group['id'] = []
group['pid'] = []
group['name'] = []
for index in range(len([r.id_ for r in db.session.query(Assetgroup.id_)])):
for asset in (Assetgroup.query.filter_by(parent_id=(index or ''))):
group['id'].append(asset.id_)
group['pid'].append(asset.parent_id)
group['name'].append(asset.name)
if request.args['type'] == 'json':
return json.dumps(group)
else:
return render_template("/cms/asset_add.html", action="/add/asset", asset=None,
client_id=client_id,
types=Type.query.all())
else:
return 'permission denied'
and this is my ajax request
$(document).ready(function () {
$('#group_id').click(function () {
$.getJSON(
'/add/asset/' + {{ client_id }},
function (data) {
$('#group_id').find('option').remove();
var len = data.id.length;
for (var i = 0; i < len; i++) {
var option_item = '<option value="' + data.id[i] + '">' + data.name[i] + "</option>";
$('#group_id').append(option_item);
}
}
);
});
});
You can add parameter in html call to get the json result...
i.e)
const Endpoint = '/add/asset/?'
$.getJSON(Endpoint, {type: 'json'}).done(function(data...)
I believe this is what you are looking for
http://flask.pocoo.org/docs/0.12/api/#flask.Request.is_json
That is a flask method that checks if the request is json
Then you can use jsonify still in flask to return json (you need to import it though)
from flask import jsonify
so your code becomes
if request.is_json:
return jsonify(group)
Hope you find that useful and more elegant
One of the easier ways to debug is just return json alone for a start to see how the response looks in a browser. So you can remove login required (assuming you are not yet in production), do not check if the request is_json, then call the api and see what it returns. So assuming your client id is 1
#cms.route('/add/asset/<client_id>', methods=["GET"])
def asset_add(client_id):
if int(current_user.id_) == int(client_id):
group = {}
group['id'] = []
group['pid'] = []
group['name'] = []
for index in range(len([r.id_ for r in db.session.query(Assetgroup.id_)])):
for asset in (Assetgroup.query.filter_by(parent_id=(index or ''))):
group['id'].append(asset.id_)
group['pid'].append(asset.parent_id)
group['name'].append(asset.name)
return jsonify(group)
Now you can visit http://yoursite.com/add/asset/1 to see your response
I am sending a POST request to my server which is throwing a 500 error when my server code attempts to read data from the POST request. But the data looks perfectly ok to me.
The POST data is:
<QueryDict: {u'{"firstname":"jack","lastname":"rowley","username":"jack","email":"info#mybiz.co.uk","password":"jack","city":"London","country":"UK","photo":"","genre1":"Comedy","genre2":"Horror","genre3":"Documentary","platform":"Cinema"}': [u'']}>
The Python code that is reading the POST data is:
username = request.POST['username']
password = request.POST['password']
email = request.POST['email']
It falls over at the first line, trying to access the username.
The AngularJS code that makes the POST request looks like this:
url = apiDomain + '/profile/register/';
var fn = 'jack';
var ln = 'rowley';
var un = 'jack';
var pw = 'jack';
var cf = 'jack';
var em = 'info#mybiz.co.uk';
var lc = 'London';
var ct = 'UK';
var ph = ''; //$('#photo_set').val();
var genre1 = 'Comedy';
var genre2 = 'Horror';
var genre3 = 'Documentary';
var platform = 'Cinema';
return $http({
method: 'POST',
url: url,
headers: {
'Content-Type': "application/x-www-form-urlencoded"
},
data: {
firstname: fn,
lastname: ln,
username: un,
email: em,
password: pw,
city: lc,
country: ct,
photo: ph,
genre1: genre1,
genre2: genre2,
genre3: genre3,
platform: platform
}
}).then(function successCallback(response) {
return response;
}, function errorCallback(response) {
return -1;
});
You are trying to access this data as if it were form-encoded. It is not; it is JSON.
You need to access the raw post body, and decode it from JSON.
data = json.loads(request.body)
username = data['username']
password = data['password']
email = data['email']
You're getting a KeyError because you don't have a username.
Your query dict is not a dict. It's a single-item string key, with an empty-string value. The key happens to be a string-encoding of some url encoding string. Look at it.
QueryDict: { u'{"fi text text text': u'' }
You are passing a URL-encoded string where you should be passing a dict, probably in the client.
I'm trying to build a page where when the user presses a button a variable which initially is 0 increments with 1. This number is then sent asynchronously to the server by using jQuery AJAX.
What I have so far is:
In my __init__.py file:
def main(global_config, **settings):
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind = engine)
Base.metadata.bind = engine
config = Configurator(settings = settings)
config.include('pyramid_jinja2')
config.add_static_view('static', 'static')
config.add_static_view('scripts', 'scripts')
# Removed the other views
config.add_route("declare_usage", '/user/{user_id}/{address_id}/declare')
config.add_route("declare_usage_json",'/user/{user_id}/{address_id}/declare.json')
config.scan()
My HTML + Jinja2:
#Removed code for simplicity
<div id="button_add">Add</div>
{{val}}
My JS:
$(document).ready(function(){
var room = 0;
jQuery.ajax({type:'POST',
url: '/user/1/5/declare', #I use a direct user ID and a direct address ID as I'm not sure how to send this to JS from Pyramid ... yet :).
data: JSON.stringify(room),
contentType: 'application/json; charset=utf-8'});
$('#button_add').click(function(){
room = room + 1;
});
});
My view code:
#view_config(route_name = 'declare_usage', renderer = 'declara.jinja2')
#view_config(route_name = 'declare_usage_json', renderer = 'json')
def declara_consum(request):
#Removed code for simplicity
val = request.POST.get('room') #I get a "None value in my html" if I change to request.json_body -> I get an error that there is no json to be parsed.
return { 'val' : val }
What happens is that when I open the debugger the POST request is successful with no data and on the page I get 2 options for 'val':
None -> When I use val = request.POST.get('room')
Error ValueError: No JSON object could be decoded -> When I use val = request.json_body
Also, still can't get it to work if in my JS i change url to be /user/1/5/declare.json and/or data to {'room' : room}
Can somebody please point out what I'm doing wrong?
you don't need another route declare_usage_json, just need separate two function like this
#view_config(route_name = 'declare_usage', renderer = 'declara.jinja2')
def declara_consum(request):
# this will response to your jinja2
return { 'val' : val }
#view_config(route_name = 'declare_usage', xhr=True, renderer = 'json')
def declara_consum_ajax(request):
# this will response to your asynchronously request
val = request.POST.get('room')
return { 'val' : val }
when you send a request using ajax, this will goto the second function.
$.ajax({
type: 'POST',
url: '/user/1/5/declare',
data: {'room' : room},
dataType: 'json'
}).done(function(response){
// update your data at html
});