How can I create a JSON (jQuery), post an whole array - php

I'm trying to create an event handler (jQuery) that will pick all elements of specific class, each unique ID value, post json array, loop through php, finally update view.
I have no problem with selecting one instance.
**Mostly looking how to create the array of id,value to pass for processing.
Thank You

You can do something like this (As a strting point):
$('.class').each(function(){
// do somthing with $(this)
});
Of course, if you post some more details, I can expand on this.

To get an array of all selected elements
var elArray = $('.classToSelect').get();
After this you may use
$.each(elArray, function(el){
var id = el.id;
var value = el.value;
//code goes here
}
A small plugin script from http://code.google.com/p/jquery-json/ is perfect for JSON encoding and decoding:
var postdata = $.toJSON(elArray);
generates a well formatted JSON string.

This snippet will give you an array of the ids of the elements with class myclass:
var id_array = $.map($(".myclass"),function(el){return el.id;});
You can then send the array to your server as JSON, or as a comma separated string, or any other way you want.

Related

Sending input array via AJAX

I've dealt with javascript in the past, but I'm trying to relearn it. For that reason I'd like to come up with a javascript solution without the use of libraries like JQuery.
I've come across several threads, and they have been close but not a perfect match to my situation.
I have a form generated dynamically by PHP, it grabs info from the database, and echoes out all the form inputs. They are all checkboxes representing the entry in the database. Normally I would use name="id[value]" where value is the id of the current entry being looped through.
So I would have something like this:
<input type="checkbox" name="del[1]"/>
<input type="checkbox" name="del[2]"/>
<input type="checkbox" name="del[3]"/>
When I would post this on form submit, I would just get the value of $_POST['del'] and call it a day. However, I'm trying to send it to a PHP page with an AJAX function so i can perform the functions without changing the page or refreshing.
My question is: How do I get all of the checkboxes(that are checked) and send them to the PHP page so it can understand which ones were checked. My understanding is that this will require some kind of conversion. My first though was to loop through each checked box, and grab its index (or give them all Ids and grab the id) and put it into a string that I could then explode PHP side.
Any thoughts? Thanks, sharf.
var i, child, str='', arr = Array(),
form = document.getElementById('form')
for(i=0; i<form.childNodes.length; i++) {
// grab the element
var child = form.childNodes[i];
// make sure it is an input and a checkbox
if(child.tagName!='INPUT' || child.getAttribute('type')!='checkbox') continue
// if the checkbox is checked, add the name and value to a url string
if(child.checked)
arr.push(child.getAttribute('name')+'='+encodeURIComponent(child.value))
}
}
// make the URL string
str = arr.join('&')
// now you can use this as a url:
SomeAjaxUrl + str
Then, in PHP:
<?php
$checked_options = $_REQUEST['del'];
print_r($checked_options);
?>
You can use jquery like you said and loop though
http://api.jquery.com/attribute-starts-with-selector/
But for ease i would look at something similar to backbone forms https://github.com/powmedia/backbone-forms
which manages your model for you and lets you send by ajax easily.
Their github has much more info on there along with some examples. This puts the checkboes in an array which you can handle php side easily
edit: pure javascript
var pairs = [];
var form = document.getelementbyid("form");
for ( var i = 0; i < form.elements.length; i++ ) {
var e = form.elements[i];
pairs.push(encodeURIComponent(e.name) + "=" + encodeURIComponent(e.value));
}
var output= pairs.join("&");
You should be able to modify that pretty easy
Use JSON.stringify()(MDN) to fix your problem.
You can convert an Array or an Object to a valid JSON Object which can be sent through AJAX.

AJAX Global Array Storage

Long story short, I'm trying to store corresponding data values from a JSON returning AJAX into these global arrays. I know that the arrays are constructing correctly because I've put alerts within AJAX, but when I put it outside the AJAX, the array is still undefined.
How can I export either the entire popData JSON object to work on it and store the values in the global arrays or get the populating of the arrays in the AJAX to carry outside the call? I need these arrays to be accessible by another function to compare the population values to a narrow range of values selected by the user--if anyone wants to suggest a better way of doing this, but it has to pull the population values onLoad which is already done in the HTML. I think this is the most streamlined way to do that with the fewest AJAX calls on the server, but I'm open to suggestions! :D
var popProducers = new Array();
var popProducersCount = new Array();
function getPopulationInfo(){
$.ajax({
url:phpURL,
cache:false,
dataType:"json",
data: { },
success:function(popData){
for (i=0;i<popData.length;i++){
//producers and producersCount should be the same length at all times!
//If current producer name isn't in array already
if(popProducers.indexOf(popData[i].ProducerName) == -1){
//add new element to represent new producer quantity (producerCount.length returns number of elements in the array, thus if there are no elements = 0 thus making index 0 equal to 1 and so on)
popProducersCount[popProducersCount.length] = 1;
//Adds the producer name to the list of producers
popProducers[popProducers.length] = popData[i].ProducerName;
} else {
//Otherwise, it will increment the index of the producersCount array corresponding with the pre-existing producer name's index by 1
popProducersCount[popProducers.indexOf(popData[i].ProducerName)] += 1;
}
}
}
});
alert("Population Data Alert: " + popProducers);
.ajax() and its underlaying XMLHttpRequest() create asyncronous requestes by default. That just means, your alert() statement is encountered before your success handler.
Easy solution here, move that alert() into the success handler at the very bottom.
If you want to deal with it in a more apropriate way, you could use jQuerys Deferred objects in a way like
function getPopulationInfo(){
return $.ajax({
// lots of stuff
});
}
and then call it like
getPopulationInfo().done(function() {
alert("Population Data Alert: " + popProducers);
});
by returning the .ajax() method we implcitly return a Deferred object. Long story short, you can pass in some additional callbacks for success (.done()), error (.fail()) and complete (.always())

Help with jQuery grabbing json data

I am having some trouble here, my json data is outputting as follows:
{"date":[{"day_w":"Tuesday","day_n":"28","month":"Dec"}],"subscriptions":[{"subscribe":"example1"},{"subscribe":"example2"},{"subscribe":"example3"}]}
I am using the jQuery code:
$.getJSON("example.php",function(data){
$.each(data.subscriptions, function(i, item) {
var subscribeData = "<li>"+ item.subscribe +"</li>";
$('#list').append(subscribeData);
});
but I am having an issue grabbing the date array. I don't want to have to use .each because there is only one array holding the date. Does this make sense? Can anyone please help?
Why is date an array at all? Why not just have the object in there directly?
{"date":{"day_w":"Tuesday","day_n":"28","month":"Dec"},"subscriptions":[...
If that's not an option, you can just access date[0]:
doSomethingWith(data.date[0].day_w);
You can write data.date[0] to get the first object in the array.
Try this - http://jsfiddle.net/FloydPink/bAtEW/

How do you post using jquery an associated array inside and array to a php script for proccessing

I am obtaining data from an api via xml which contains data about each user of a website.
I need to ultimately save this data into a mysql database.
I am parsing the data and obtaining the values for each user using jquery.
I am find the nodes for each user like so
$onlineid = $(this).find("onlineid");
$comment = $(this).find("comment");
and then obtaining the values..
var onlineid = $onlineid.text();
var comment = $comment.text();
This is where i am now stuck...
I need to create an associated array of users data and then add each users data to an array of users so that it can all be processed using php, then saved to mysql.
maybe something like this..?
var users = new Array();
var user_data = new Object();
user_data['onlineid'] = onlineid;
user_data['comment'] = comment;
then..
users.push(user_data);
This seems to build an array of objects.
If i post them to a php script like so using ajax
$.ajax({
type: "POST",
url: "sync.php",
data: 'users='+users
firebug shows them as a string of object separated by commas.
How on earth do i deal with that in the php script?
I basically need to process each object (user_data) in each of the array items (users) so that the values can be saved to a mysql database.
Any expert advice would be fantastic.
you break the "a string of object separated by commas" into pieces in PHP using explode:
$users_array = explode(",",$users);
Checkout this gist. It expands on the answer by #picus.
You could try to parse them out into a list of values in the qs that looks like this:
?users[]=user1&users[]=user2&users[]=user3
This should give you an array called users that is part of the POST request for your PHP page:
print_r($_POST['users']);
would output:
user1, user2, user3
I don't use PHP, but what I'd do is create a javascript object that is comprised of a single userid field/property and another field/property which holds a simple array of comments for that user (this permits multiple comments per user). Then I'd create a container to hold all of those objects, either a simple (numeric offset) array or an associative array using the userid (as a string) as the key. Then I'd JSONify the whole kit-and-caboodle and post the JSON-encoded string to the server where it would get decoded from JSON format back into objects the server could work with. PHP surely offers some helper methods to make this easy. I'd search for "PHP JSON".
I would transfer the data as a JSON-encoded string:
var users = [];
// in a loop:
users.push({onlineid: $(this).find("onlineid").text(),
comment: $(this).find("comment").text()});
// ajax request:
$.ajax({
type: "POST",
url: "sync.php",
data: {users: JSON.stringify(users)} // automatic HTTP encoding
The JSON object is either built in or available via this script.
In PHP use json_decode:
$users = json_decode($_POST['users'], true);

decode json as html

So I'm building a web application and I have an ajax request that pings a database (or database cache) and echos back a big thing of json. I'm totally new to json, and when the php pulls from the database I echo json_encode($databaseResults), then it shows up in my html page as a long string. My question is, how do I convert it and pull out the pieces I need into a nice format?
Thanks!
The Json result that was in the page looks like:
"[{\"currentcall\":\"1\",\"timecalled\":\"15:30\",\"etaTime\":\"15:35\",\"departmentID\":\"1\",\"memberID\":\"1\",\"callinnum\":\"1\",\"location\":\"Fire House\",\"billed\":\"N\",\"date\":\"2\\/12\\/11\",\"firstName\":\"Phil\",\"lastName\":\"asdf\",\"email\":\"pasdf#gmail.com\",\"homephone\":\"+19111111111\",\"cellphone\":\"+11234567891\",\"cellphone2\":null,\"workphone\":null,\"phonenumber5\":null,\"phonenumber6\":null,\"streetAddress\":\"10 asdfnt Dr\",\"city\":\"\",\"username\":\"pgsdfg\",\"password\":\"0623ab6b6b7dsasd3834799fbf2a08529d\",\"admin\":\"Y\",\"qualifications\":\"Interior\",\"rank\":null,\"cpr\":null,\"emt\":null,\"training\":null,\"datejoined\":null,\"dateactive\":null,\"state\":\"DE\",\"zip\":\"51264\",\"pending\":\"NO\",\"defaultETA\":\"7\",\"apparatus\":\"asdKE-286\"}]"
There can be multiple results... this is only one result
EDIT:
Basically, I'm trying to pass a bunch of rows in an array into an html file, and take out only the data I need and format it. I don't know if json is the best way to do this or not, just one solution I came up with. So if anyone has a better solution that would be awesome.
Edit2:
This is the jquery I have that makes the request, the php just has echo json_encode ($DBResults);
function getResponder(){
var responders = $.ajax({
type : "POST",
url: "/index.php/callresponse/get_responders",
success: function(html){
$("#ajaxDiv").html(html);
}
});
setTimeout("getResponder()", 10000);
}
As you flagged this as jquery I assume that you're using jQuery. If you're only going to get the one string you can skip the json part and use jQuery .load() like this $('#result').load('ajax/test.php'); that will load the contents from ajax/test.php into #result
However if you want to use json you can take a look over at getJSON on the jQuery documentation. You can also use the jQuery parseJSON function which will return the json an javascript object containing the jsonData.
Here's an example how you can use parseJSON
var object = $.praseJSON(jsonString); //jsonString is the string containing your actual json data
alert(object.location) //Will alert "Fire House" with the given json string
Here's an example of how you can use getJSON in the same way
$.getJSON('ajax/test.php', function(object) {
alert(object.location); //Will alert "Fire House" with the given json string
});
If you want to pass parameters as well you can do it like this
$.getJSON('ajax/test.php',
{
Param1 : "Value1",
Param2 : "value2"
},
function(object) {
alert(object.location); //Will alert "Fire House" with the given json string
}
);
If you are trying to send json from javascript to php you can use
$jsonArray = jsonDecode($_GET['key']);
Of course if you're using post you'll write $_POST instead.
You have to parse the data into a JSON object, then you can use properties of the object as you wish.
Without seeing the specifics, I can tell you that you'll need to use the JSON object to parse the text. See more here: http://www.json.org
var obj = JSON.parse(ajaxResponseText);
You should use php function json_decode which will give you an object or array with all the properties.
Then you should iterate recursively through this object and add the content of the properties to a string, which should be your final HTML.
Normally to display JSON response in an html element after jquery(for example) by web request, try this:
$("#box-content-selector").append(
"<pre>"+
JSON.stringify(JSON.parse(data), null, 4)+
"</pre>"
)

Categories