I'm using jQuery AJAX to load part of my web page. And my AJAX datatype is HTML. I've heard JSON is faster and I've used it too. But JSON doesn't seem to work when the data is a little big, for example:
It works when the data is short:
{"name" : "John Smith" , "age" : "32" , "status" : "married" }
{"name" : "Bella Gilbert" , "age" : "26" , "status" : "single" }
But not when the data is a little big:
{"name" : "John Smith" , "age" : "32" , "status" : "married" }
{"name" : "Bella Gilbert" , "age" : "26" , "status" : "single" }
{"name" : "Joseph Morgan" , "age" : "28" , "status" : "single" }
{"name" : "Paul Wesley" , "age" : "24" , "status" : "single" }
Is there any way I can just fetch the data without stating dataType as JSON and then decode it using javascript, as similar to PHP's function:
json_decode($data);
Or if not then please suggest a way to handle large JSON data using jQuery AJAX. Thanks!
use this
var obj = jQuery.parseJSON(json_data);
It will decode the json_data
http://api.jquery.com/jQuery.parseJSON/
use JSON.parse() to convert a JSON string to an object:
var jsontext = '{"firstname":"Jesper","surname":"Aaberg","phone":["555-0100","555-0120"]}';
var contact = JSON.parse(jsontext);
document.write(contact.surname + ", " + contact.firstname);
// Output: Aaberg, Jesper
jquery version: (Parses a JSON string.)
var obj = jQuery.parseJSON('{"name":"John"}');
alert(obj.name);
You could use the $.parseJSON() method to parse a JSON encoded string into the corresponding javascript object. But if you are performing an AJAX request to your server and the data is coming from it you don't need to use this method at all because jQuery will automatically parse the result passed to the success function:
$.ajax({
url: '/somescript.php',
dataType: 'json',
success: function(result) {
// result is already a parsed javascript object that you could manipulate directly here
}
});
And if you write your server side script properly so that it sets the response Content-Type HTTP header to application/json (which you should always be doing anyways) you don't even need to indicate to jQuery the dataType parameter. jQuery will analyze this response header and automatically parse the result for you:
$.ajax({
url: '/somescript.php',
success: function(result) {
// result is already a parsed javascript object that you could manipulate directly here
}
});
the jQuery.parseJSON method can do this.
Your json object is malformed. Should look like this:
[{"name" : "John Smith" , "age" : "32" , "status" : "married" },
{"name" : "Bella Gilbert" , "age" : "26" , "status" : "single" },
{"name" : "Joseph Morgan" , "age" : "28" , "status" : "single" },
{"name" : "Paul Wesley" , "age" : "24" , "status" : "single" }]
Use this tool to check your object.
Related
I'm receiving some JSON via a HTTP POST Callback to a PHP page and I'm having an issue parsing out the JSON. Here's an example of what the JSON data that is sent looks like:
[
{
"type" : "message-received",
"time" : "2016-09-14T18:20:16Z",
"description" : "Incoming message received",
"to" : "+12345678902",
"message" : {
"id" : "14762070468292kw2fuqty55yp2b2",
"time" : "2016-09-14T18:20:16Z",
"to" : ["+12345678902"],
"from" : "+12345678901",
"text" : "Hey, check this out!",
"applicationId" : "93de2206-9669-4e07-948d-329f4b722ee2",
"media" : [
"https://messaging.bandwidth.com/api/v2/users/{accountId}/media/14762070468292kw2fuqty55yp2b2/0/bw.png"
],
"owner" : "+12345678902",
"direction" : "in",
"segmentCount" : 1
}
}
]
I'm then processing this as follows:
$eventJSON = file_get_contents('php://input');
$event= json_decode( $eventJSON );
$eventType = $event->type;
but I'm not getting anything so far for my $eventType variable - I think the issue might be that the JSON is an array but I'm not sure how to handle this?
To parse json try
$eventType = $event[0]->type;
Refer :- How do I extract data from JSON with PHP? to know the difference between object properties and array elements
I want to insert json array elements like below using MongoDB and CodeIgniter.
"ticket" : [
{
"problem" : "testing",
"time_taken" : "5 hrs",
"number_of_visits" : "7",
"expenses" : {
"amount" : "2000",
"distance_travelled" : "4 km"
}
},
{
"problem" : "testing",
"time_taken" : "5 hrs",
"number_of_visits" : "4",
"expenses" : {
"amount" : "2500",
"distance_travelled" : "5 km"
}
}
]
What is the query I have to use for this?
What you need is the Bulk Write functions (https://docs.mongodb.com/manual/core/bulk-write-operations/)
The PHP depends on which library you are using (old or new, hopefully the new one!) but in plain English you:
create an array of operations (in your case "inserts")
call bulk write.
$this->mongo_db->where('_id', new MongoId($id))->push("ticket",$data)->update('engineer');
This is the query I'm using for inserting multiple array values in mongodb codeigniter.
I'm new to the map reduce concept and even though I'm making some slow progress, I'm finding some issues that I need some help with.
I have a simple collection consisting of an id, city and and destination, something like this:
{ "_id" : "5230e7e00000000000000000", "city" : "Boston", "to" : "Chicago" },
{ "_id" : "523fe7e00000000000000000", "city" : "New York", "to" : "Miami" },
{ "_id" : "5240e1e00000000000000000", "city" : "Boston", "to" : "Miami" },
{ "_id" : "536fe4e00000000000000000", "city" : "Washington D.C.", "to" : "Boston" },
{ "_id" : "53ffe7e00000000000000000", "city" : "New York", "to" : "Boston" },
{ "_id" : "5740e1e00000000000000000", "city" : "Boston", "to" : "Miami" },
...
(Please do note that this data is just made up for example purposes)
I'd like to group by city the destinations including a count:
{ "city" : "Boston", values : [{"Chicago",1}, {"Miami",2}] }
{ "city" : "New York", values : [{"Miami",1}, {"Boston",1}] }
{ "city" : "Washington D.C.", values : [{"Boston", 1}] }
For this I'm starting to playing with this function to map:
function() {
emit(this.city, this.to);
}
which performs the expected grouping. My reduce function is this:
function(key, values) {
var reduced = {"to":[]};
for (var i in values) {
var item = values[i];
reduced.to.push(item);
}
return reduced;
}
which gives somewhat an expected output:
{ "_id" : ObjectId("522f8a9181f01e671a853adb"), "value" : { "to" : [ "Boston", "Miami" ] } }
{ "_id" : ObjectId("522f933a81f01e671a853ade"), "value" : { "to" : [ "Chicago", "Miami", "Miami" ] } }
{ "_id" : ObjectId("5231f0ed81f01e671a853ae0"), "value" : "Boston" }
As you can see, I still haven't counted the repeated cities, but as can be seen above, for some reason the last result in the output doesn't look good. I'd expected it to be
{ "_id" : ObjectId("5231f0ed81f01e671a853ae0"), "value" : { "to" : ["Boston"] } }
Has this anything to do with the fact that there is a single item? Is there any way to obtain this?
Thank you.
I see you are asking about a PHP issue, but you are using javascript to ask, so I’m assuming a javascript answer will help you move things along. As such here is the javascript needed in the shell to run your aggregation. I strong suggest getting your aggregation working in the shell(or some other javascript editor) in general and then translating it into the language of your choice. It is a lot easier to see what is going on and there faster using this method. You can then run:
use admin
db.runCommand( { setParameter: 1, logLevel: 2 } )
to check the bson output of your selected language vs what the shell looks like. This will appear in the terminal if mongo is in the foreground, otherwise you’ll have ot look in the logs.
Summing the routes in the aggregation framework [AF] with Mongo is fairly strait forward. The AF is faster and easier to use then map reduce[MR]. Though in this case they both have similar issues, simply pushing to an array won’t yield a count in and of itself (in MR you either need more logic in your reduce function or to use a finalize function).
With the AF using the example data provided this pipeline is useful:
db.agg1.aggregate([
{$group:{
_id: { city: "$city", to: "$to" },
count: { $sum: 1 }
}},
{$group: {
_id: "$_id.city",
to:{ $push: {to: "$_id.to", count: "$count"}}
}}
]);
The aggregation framework can only operate on known fields, but many pipeline operations so a problem needs to broken down with that as a consideration.
Above, the 1st stage calculates the numbers need, for which there are 3 fixed fields: the source, the destination, and the count.
The second stage has 2 fixed fields, one of which is an array, which is only being pushed to (all the data for the final form is there).
For MR you can do this:
var map = function() {
var key = {source:this.city, dest:this.to};
emit(key, 1);
};
var reduce = function(key, values) {
return Array.sum(values);
};
A separate function will have to pretty it however.
If you have any additional questions please don’t hesitate to ask.
Best,
Charlie
Is there a concise neat way to turn an XML feed into an JavaScript object literal?
I have this XML feed
<jobs>
<industry>
<name>Technology</name>
<area>Refrigiration</area>
<area>Information Technology</area>
<area>Electronics</area>
<area>Avionics</area>
</industry>
<industry>
<name>Agriculture</name>
<area>Agri-Tourism</area>
<area>Animal Husbandry</area>
<area>Harvesting</area>
<area>Poultry</area>
</industry>
</jobs>
and wish to turn it to:
var jobs = [
{
"name" : "Technology",
"areas" : [ "Refrigiration" , "Information Technology", "Electronics", "Avionics" ]
},
{
"name" : "Agriculture",
"areas" : [ "Agri-Tourism" , "Animal Husbandry", "Harvesting", "Poultry" ]
},
{
"name" : "Media",
"areas" : [ "Journalism" , "Camera person", "Reality tv person", "Commentator" ]
}
];
I succeeded in encoding the JSON object using php. What I am missing is the rest.
echo json_encode(simplexml_load_string("<jobs>
<industry>
<name>Technology</name>
<area>Refrigiration</area>
<area>Information Technology</area>
<area>Electronics</area>
<area>Avionics</area>
</industry>
<industry>
<name>Agriculture</name>
<area>Agri-Tourism</area>
<area>Animal Husbandry</area>
<area>Harvesting</area>
<area>Poultry</area>
</industry>
</jobs>"));
This gives you:
{
"industry": [
{
"name": "Technology",
"area": [
"Refrigiration",
"Information Technology",
"Electronics",
"Avionics"
]
},
{
"name": "Agriculture",
"area": [
"Agri-Tourism",
"Animal Husbandry",
"Harvesting",
"Poultry"
]
}
]
}
You need to convert your XML to an array, https://stackoverflow.com/questions/4844476/xml-to-php-array
Then you'll need to convert the array to json using php json_encode()
If you are receiving a JSON encoded string in your javascript callback, you probably need to run $.parseJSON() to make jQuery treat it as a JSON object instead of a string
Two solutions:
PURE JQUERY
Using jQuery's parseXML , combined with jQuery get you can have the object you need:
$.get("http://www.example.com/path/to/file.xml", function(data){
var xml = $.parseXML(data);
console.log(xml);
});
PHP+JQUERY
if you've already parsed the object into a json, just print it into an html file and get that file using jquery's getJSON
$.getJSON("http://www.example.com/json/feed",function(data){
console.log(data);
});
I have a textarea that I want to submit via ajax. When I try to output the value, I only get [object Object]
Jquery (ajax)
$("#insertAddresses").click(function() {
$.ajax({
type: "POST",
url: "insertAddr.php",
data: 'addresses=' +
}).done(function(list) {
//getList(); // run query to get addresses and populate list
});
});
PHP (i've tried)
$_POST['addresses'];
or
$addresses = explode("\n", $_POST['addresses']);
Regardless of anything i've tried, always returns
[object Object]
Help?!
Your serverscript is returning a json object, which is correctly recognized by JavaScript as an object. You can do a whole lot of things with that object, but you can't just put it on your website, as it is not html or text.
Here is a short description of json: http://en.wikipedia.org/wiki/JSON
I don't know how your data is structured, so i can't tell you how you can access your data. But in a json like this (example from wikipedia):
{
"firstName": "John",
"lastName" : "Smith",
"age" : 25,
"address" :
{
"streetAddress": "21 2nd Street",
"city" : "New York",
"state" : "NY",
"postalCode" : "10021"
},
"phoneNumber":
[
{
"type" : "home",
"number": "212 555-1234"
},
{
"type" : "fax",
"number": "646 555-4567"
}
]
}
You could, ie., excess the firstName simply with:
data.firstName
An voila, there is your excpected data.
You're data should be an object:
data: { adresses: "value" }
Just a little tip: the shorthand ajax-call for what you're doing in jQuery is $.post(.... and then you can lose the "type". Does exactly the same, but I think it's just a little neater.