Textarea list via jquery .ajax to php - php

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.

Related

json decode and get value using PHP

I have a JSON string and i want to get the value.
$s='{
"subscriptionId" : "51c04a21d714fb3b37d7d5a7",
"originator" : "localhost",
"contextResponses" : [
{
"contextElement" : {
"attributes" : [
{
"name" : "temperature",
"type" : "centigrade",
"value" : "26.5"
}
],
"type" : "Room",
"isPattern" : "false",
"id" : "Room1"
},
"statusCode" : {
"code" : "200",
"reasonPhrase" : "OK"
}
}
]
}';
Here is the code which I used but it didn't work.
$result = json_decode($s,TRUE); //decode json string
$b=$result ['contextResponses']['contextElement']['value']; //get the value????
echo $b;
ContextResponses contains a numerically indexed array (of only one item) and value property is more deeply nested than what you are trying to reference (it is within attributes array). This would appear to be what you need:
$b = $result['contextResponses'][0]['contextElement']['attributes'][0]['value'];
When reading a JSON-serialiazed data structure like that, you need to make sure and note every opening [ or { as they have significant meaning in regards to how you need to reference the items that follow it. You also may want to consider using something like var_dump($result) in your investigations, as this will show you the structure of the data after it has been deserialized, oftentimes making it easier to understand.
Also, proper indention when looking at something like this would help. Use something like http://jsonlint.com to copy/paste your JSON for easy reformatting. If you had your structure like the following, nesting levels become more readily apparent.
{
"subscriptionId": "51c04a21d714fb3b37d7d5a7",
"originator": "localhost",
"contextResponses": [
{
"contextElement": {
"attributes": [
{
"name": "temperature",
"type": "centigrade",
"value": "26.5"
}
],
"type": "Room",
"isPattern": "false",
"id": "Room1"
},
"statusCode": {
"code": "200",
"reasonPhrase": "OK"
}
}
]
}

MongoDB Map Reduce newbie (PHP)

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 any Javascript function similar to PHP's JSON_DECODE function?

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.

How to turn JSON to object literal using PHP and jquery

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);
});

Execute different actions depending on search results

I have a form with a lot of inputs (text inputs, textareas, checkboxes...) that users can populate with their own presets. At the moment, users can search for their presets, an ajax query is called and I return HTML with a list of found presets. The HTML is (elaboratly) generated in a PHP file that adds an onclick="" with lots of different actions. The users can click the presets and the form gets populated.
An example of generated HTML (that gets put in the page) could be
<a onclick=" $('#AgendaItemName').val('Preset 1'); $('#AgendaItemOpmerking').val(''); $('#AgendaItemLokaalID').val(''); $('#AgendaItemPlaats').val(''); $('#AgendaItemBegeleidendeLeerkrachten').val(''); $('#AgendaItemDoelgroep').val(''); $('#AgendaItemIsPubliek').val('1'); $('#AgendaItemLesFicheAbonnementID').val(''); $('#AgendaItemAgendaItemTypeID').val('2'); $('#AgendaItemAgendaItemPublicatieTypeID').val(''); $('#AgendaItemLeergebiedID').val('1'); $('#AgendaItemLeerdomeinID').val('1'); $('#AgendaItemLessenTaken').val(''); $('#AgendaItemVerloop').val('Test verloop\r\n\r\ntest opslaan vanuit agendaitem'); $('#AgendaItemBeginsituatie').val(''); $('#AgendaItemMateriaal').val(''); $('#AgendaItemEvaluatie').val('Test evaluatie'); $('#AgendaItemEigenLesdoelen').val('Test lesdoelen'); $('#AgendaItemAgendaItemHerhaalModeID').val(''); $('#AgendaItemHerhaalStartDatum').val(''); $('#AgendaItemHerhaalEindDatum').val(''); $('#AgendaItemAgendaItemKleuterModeID').val('0'); UpdateVisibleFields('AgendaItem');$('.HoekVeldInput').val('');$('#AgendaItemAgendaItemBelangstellingsCentrumID').val(''); $('#AgendaItemLesFicheID').val('791'); $('#AgendaItemIsBestaandeFicheAanpassen').attr('disabled', false); loadFieldsets(791, 'LesficheID'); return false; " href="#">Preset 1</a>
You don't actually have to fully read that piece of code, cuz it's... well, not so good. Most of the times it's just setting values, but sometimes, I also need to execute a few functions, depending on preset settings. Now I was thinking about a better way to approach this, but I'm stuck. Is there any way to send these actions along with JSON? Is it possible to do something like
var returndatafromajax = [
{
"html" : "preset",
"actions" : "dothis(); dothat();"
},
{
"html" : "preset 2",
"actions" : "someofthis();"
},
{
"html" : "preset 3",
"actions" : "noneofthat();"
}
]
$('ul').on('click', 'a', function() {
var index = $(this).attr('rel');
somehowexecute(returndatafromajax[index].actions);
});
Yes you can do this in this way
var returndatafromajax = [
{
"html" : "preset",
"actions" : {"1":"dothis","2":"dothat"}
},
{
"html" : "preset 2",
"actions" : {"1":"someofthis"}
},
{
"html" : "preset 3",
"actions" : {"1":"noneofthat"}
}
]
use only function names not the (); with their names.

Categories