This is probaly a really easy question but am struggling with this four about 2 hours now.
I have a php file:
$array = array(
"id"=> 1, "firstName"=> "James", "lastName"=> "King", "managerId"=> 0, "managerName"=> "", "title"=> "President and CEO", "department"=> "Corporate", "cellPhone"=> "617-000-0001", "officePhone"=> "781-000-0001", "email"=> "jking#fakemail.com", "city"=> "Boston, MA", "pic"=> "James_King.jpg", "twitterId"=> "#fakejking", "blog"=> "http://coenraets.org"
);
echo json_encode($array);
Now I want to give this an object like the following:
Object
blog: "http://coenraets.org"
cellPhone: "617-000-0001"
city: "Boston, MA"
department: "Corporate"
email: "jking#fakemail.com"
firstName: "James"
id: 1
lastName: "King"
managerId: 0
managerName: ""
officePhone: "781-000-0001"
pic: "James_King.jpg"
title: "President and CEO"
twitterId: "#fakejking"
Right now i'm getting the following response:
abort: (a)
always: ()
complete: ()
done: ()
error: ()
....
readyState: 4
responseText: "{"id":1,"firstName":"James","lastName":"King","managerId":0,"managerName":"","title":"President and CEO","department":"Corporate","cellPhone":"617-000-0001","officePhone":"781-000-0001","email":"jking#fakemail.com","city":"Boston, MA","pic":"James_King.jpg","twitterId":"#fakejking","blog":"http:\/\/coenraets.org"}"
setRequestHeader: (a,b)
state: ()
...
__proto__: Object
I really don't know where to look and am probaly doing something wrong but I really have no idea.
UPDATE
js
var result = $.ajax({
url: "http://localhost/cordova/employees/index.php?name="+ searchKey,
context: document.body
});
console.log(JSON.parse(result.responseText));
The line console.log(JSON.parse(result.responseText)) gives me the following error:
Uncaught SyntaxError: Unexpected token o
That's because you're looking at the XMLHttpRequest object. You need to parse out the response to get the object.
var obj = JSON.parse(xhr.responseText);
where xhr is the name of the object you're doing a console.log on.
$.ajax() makes an asynchronous HTTP request, so you can't just get the response right way. You have to wait for the response to come to you. The done() construct can be used to fire a callback when your response is ready.
var getEmployee = $.ajax({
url: "http://localhost/cordova/employees/index.php?name="+ searchKey,
context: document.body,
dataType: 'json'
});
// the callback will get fired when the response is received
getEmployee.done(function (result) {
console.log(result.blog);
});
// this will get fired immediately before the response is even received
console.log(getEmployee.responseText);
It's simple feature.
read about stdClass in PHP
and modify your php code to:
$array = new stdClass();
$array->id = 1;
$array->firstName = "James";
//..... other fields
echo json_encode($array);
Related
I am fetching some records :
$companies = \App\User::where('type', 'pet-salon')->orWhere('type', 'veterinarian')->get();
return response()->json($companies);
The data coming back is an array of objects:
[{
id: 2,
type: "xxx",
deactivate: 0,
xxx: "Hello",
middle_name: "Mid",
lastname: "xxx",
//...
}]
This is the jQuery typeahead code:
$('#getCompaniesForConnection').typeahead({
source: function (query, process) {
return $.get('/all/companies', { query: query }, function (data) {
return process(data);
});
}
});
The exception its giving me :
Uncaught TypeError: b.toLowerCase is not a function
And the results drop-down is not showing too, What am i missing here ?
Yes, you need to json_encode your companies.
$companies = \App\User::where('type', 'pet-salon')->orWhere('type',
'veterinarian')->get();
$result = json_encode($companies ); // return this or echo
First, the PHP code looks like it's a laravel code, so you can just return the $companies variable like so:
$companies = \App\User::where('type', 'pet-salon')->orWhere('type', 'veterinarian')->get();
return $companies;
Since models and collections are converted to JSON when cast to a string, you can return Eloquent objects directly from your application's routes or controllers.
And also, let's see the definition of the process function to be sure that's not where the error is coming from.
Hi Guys I'm new to Django and Python... I'm using REST Framework to develop some webservices. I want to loop through all the orders of a JSON item. The request from javascript is done in this way:
function TestDjangoPostWithNoCsrlTokenAndWithMultipleObjectsJson() {
var JSONObject = new Object();
JSONObject.Orders = [];
JSONObject.Orders.push({ id: 1, Name: 'Name1', Description: 'Description1' });
JSONObject.Orders.push({ id: 2, Name: 'Name2', Description: 'Description1' });
JSONObject.Orders.push({ id: 3, Name: 'Name3', Description: 'Description1' });
console.log(JSON.stringify(JSONObject));
$.ajax
({
type: "POST",
url: URL_PostOrdersMultipleObjects,
headers: {
"Authorization": "Basic " + btoa("xxx" + ":" + "xxx")
},
data: JSONObject,
dataType: 'json',
success: function (data, status, xhr) {
console.log(JSON.stringify(data));
if (xhr.readyState == 4) {
if (xhr.status == 201) {
console.log("Created");
}
} else {
console.log("NoGood");
}
},
complete: function (xhr) {
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(thrownError);
}
});
}
On Django side, I have...
#api_view(['GET', 'POST'])
def JSONPostTest(request):
if request.method == 'POST':
stream = io.BytesIO(request.body)
obj = JSONParser().parse(stream)
for order in obj['Orders']: # First Example
serializer = QASerializer(data=order)
if serializer.is_valid():
serializer.save()
else :
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
return Response('OK', status=status.HTTP_201_CREATED)
else:
return Response('OK', status=status.HTTP_201_CREATED)
If In javascript i stringify my object before to send it the above code works fine. The problems is when I don't stringify.
If I stringify
request.body =
b'{"Orders":[{"id":1,"Name":"Name1","Description":"Description1"},{"id":2,"Name":"Name2","Description":"Description2"},{"id":3,"Name":"Name3","Description":"Description3"}]}'
if I don't stringify
request.body
b'Orders%5B0%5D%5Bid%5D=1&Orders%5B0%5D%5BName%5D=Name1&Orders%5B0%5D%5BDescription%5D=Description1&Orders%5B1%5D%5Bid%5D=2&Orders%5B1%5D%5BName%5D=Name2&Orders%5B1%5D%5BDescription%5D=Description1&Orders%5B2%5D%5Bid%5D=3&Orders%5B2%5D%5BName%5D=Name3&Orders%5B2%5D%5BDescription%5D=Description1'
and
request.data
<QueryDict: {'Orders[1][Description]': ['Description1'], 'Orders[2][id]': ['3'], 'Orders[0][Name]': ['Name1'], 'Orders[0][Description]': ['Description1'], 'Orders[2][Description]': ['Description1'], 'Orders[1][id]': ['2'], 'Orders[0][id]': ['1'], 'Orders[1][Name]': ['Name2'], 'Orders[2][Name]': ['Name3']}>
I can stringify no problem on that. But I want to understand if it's possible to obtain the same result without stringifing starting from the QueryDict I have.
Thank you
You've not only constructed your JSON object in an unnecessarily verbose and complex way, you're also using the wrong data structure. If you want to iterate something, it should be an array (which maps to a list in Python), not an object (which maps to a dict). Your JS code should look like this:
JSONObject.Orders = [];
JSONObject.Orders.push({id: 1, Name: 'Name1', Description: 'Description1'});
JSONObject.Orders.push({id: 2, Name: 'Name2', Description: 'Description1'});
JSONObject.Orders.push({id: 3, Name: 'Name3', Description: 'Description1'});
(You could actually make that more compact by defining the objects inline with the array, but this is at least clearer for now.)
Now, it's simple to iterate in Python:
for obj in jsondata['Orders']:
...
Since you write you have a Serializer for Order I assume it is also a model on your backend and you would like to store it in the database. In that case I would not bother to manually deserialize the list of orders but let django-restframework unpack the nested child objects along with the parent.
Have a look here: https://stackoverflow.com/a/28246994/640916
I'm trying to convert a returned json object into a serialized string that I can process further with some PHP server side code:
The returned object looks like this:
Object {id: "123456787654321", email: "some-email#gmail.com", first_name: "First", gender: "male", last_name: "Last"}
I can convert the object to a string with the following:
var paramString = JSON.stringify(response);
console.log(paramString);
// doesn't work
//var params = paramString.serialize();
How do I now convert the string to a serialized string that I can pass to my server with the following client side call:
I would expect something like this:
id=123456787654321&email=some-email#gmail.com&first_name...
My server side code:
$.post("/functions/test_functions.php", {params: params}, function(data) {
...
}, "json");
I handle the params array like this server side:
$vars = $_SERVER['REQUEST_METHOD'] === "GET" ? $_GET : $_POST;
$params = array();
isset($vars['params']) ? parse_str($vars['params'], $params) : null;
You can pass JSON-string to server and decode it with json_decode(). See http://php.net/manual/en/function.json-decode.php for details.
Unless there's a specific reason for stringifying, you don't actually need to. jQuery .post will handle the serialization for you, for example:
var response = {id: "123456787654321", email: "some-email#gmail.com", first_name: "First", gender: "male", last_name: "Last"};
$.post("/functions/test_functions.php", response, function(data) {
...
}, "json");
Will make a POST request like this:
/functions/test_functions.php
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Form Data: id=12345654321&email=some-email#gmail.com&first_name....
I'm trying to update a JSON file with the value of a textarea using jquery push. I'm receiving the following error: " JavaScript runtime error: Unable to get property 'push' of undefined or null reference"
My jquery:
function submittedMsg(ctx) {
var id = $('.msg-input form').attr('id');
var newMsg = $('.msg-input textarea').val();
var url = "/ajax.aspx?vtl=ajax-conversation-json&cv=" + id;
$.getJSON(url, function (messageString, message) {
var message = [];
message.push({
msgcontent: newMsg,
sendname: sendRname,
mbrhref: mbrUrl,
datetime: ""
});
});
}
My JSON:
{
"messageString" :
[
{ "subject": "hello",
"msgstring": "5",
"unread": "1",
"datetime": "Oct 1 2013 9:59PM",
"orderid": "17",
"recipient": [
{
"mbrname": "Jane Doe",
"mbrhref": "/profile.aspx?mem=1227"
},
{
"mbrname": "John Smith",
"mbrhref": "/profile.aspx?mem=1337"
}
],
"message": [
{
"datetime":"2013-10-01T21:59:33.063",
"sendname":"Jane Doe",
"mbrhref":"/profile.aspx?mem=1227",
"msgcontent": "<p>Hi. I would like to talk with you about Dwarf Beryl Beauty</p>"
},
{
"datetime":"2013-11-26T16:29:17.037",
"sendname":"John Smith",
"mbrhref":"/profile.aspx?mem=1337",
"msgcontent": "Tough luck."
}
]
}
]
}
I don't necessarily need to use push to update the JSON file if there is a better way, I'm open to suggestions. I've verified my URL path is correct. Am I just missing something obvious? I'm new to JSON and only have passable jquery skills. Help!
Thanks in advance for any direction.
Try to use:
data.message.push
instead of:
data.messageString.message.push
Ah I see the issue, you have a local var and parameter of the same name message:
$.getJSON(url, function (messageString, message) { //here is param message
var message = []; //here is a local var parameter
message.push({ //this is probably referencing the parameter which is not an array or object that supports .push
Instead:
$.getJSON(url, function (data) { //I renamed the param to be more consistent with documentation, although it doesn't really matter, just will generate confusion
data.messageString.push({ //modify the json we were passed in the data param
I am writing some code to educate myself in the ways of ExtJS. I am also new to JSON so hopefully this question will be easy for you to answer. I am trying to retrieve some data from a basic web service that I have written which should be returning its results as JSON (seeing as I am new to JSON - it could be that that is broken).
The error I am getting is
SyntaxError: missing ) in
parenthetical
The JSON that I am returning from my web service is
{
"rows": [
{
"id": "100000",
"genre_name": "Action",
"sort_order": "100000"
}, {
"id": "100002",
"genre_name": "Comedy",
"sort_order": "100002"
}, {
"id": "100001",
"genre_name": "Drama",
"sort_order": "100001"
}]
}
My ExtJS code is as below. The loadexception callback is where I have retrieved the JSON and error above from
var genres = new Ext.data.Store({
proxy: new Ext.data.HttpProxy({
method: 'POST',
url: 'http://localhost/extjs_training/Demo_WebService/Utility.asmx/GetGenres',
failure: function(response, options){
Ext.get('my_id').dom.innerHTML = 'Load failed: ' + response.status;
}
}),
reader: new Ext.data.JsonReader({
fields: ['id', 'genre_name'],
root: 'rows'
}),
listeners: {
loadexception: function (proxy, options, response, e) {
var result = response.responseText;
Ext.MessageBox.alert('Load failure', e + " ..... " + result);
}
}
});
var loadSuccess = genres.load({
callback: function(r, options, success){
Ext.get('my_id').dom.innerHTML = 'Load status: success=' + success;
}
});
Is the JSON you included above what is actually being returned from the call, or what you are anticipating it should look like? The string you included looks clean, but it looks like you formatted it as well. I'm not sure if the space after "id": is allowed, either. It might not be a big deal, though.
The missing parenthetical typically indicates that something in the JSON is wrong. It could be an extra character before/after the string. Use Firebug to examine what you are getting back, and make sure it is clear of any extra characters.
http://www.sencha.com/forum/showthread.php?10117-Solved-missing-%29-in-parenthetical.
Echoeing two statements was the reason in my case. So check your echoes again.