I'm quite newbie in JSON, just started it the last night, I'm very close to the deadline of a project, I used xml, and tried now to switch to json.
I started with the simplest representation of a json object, let me go to code:
PHP Code:
<?php
//phpPage.php
$json = array();
$json[]='Jquery';
$json[]='AJAX';
$json[]='JSON';
//for example
echo json_encode($json);
?>
js code:
$(document).ready(function(){
$.post('phpPage.php', { /*no matter*/ }, showResult, "text");
});
function showResult(res){
var obj = JSON.parse(res);
$("input#autocomplete").autocomplete({
source: function() {
var rows = new Array();
for(var i=0; i<3; i++){//Assume that I know array size, skip it
//what to do here?
}
return rows;
}
});
}
I don't know how to convert the sent object to an array ready to be used in the 'source' of the autocomplete.
Thanks for your time,
Regards!
The solution:
<script type="text/javascript">
$(document).ready(function(){
$.post('phpPage.php', { /**/ }, showResult, "text");
});
function showResult(res){
var obj = JSON.parse(res);
$("input#autocomplete").autocomplete({
source: obj
});
}
</script>
use jquery's getJSON() function (if you can GET).
OR
$.post('phpPage.php', { /*no matter*/ }, showResult, "json");
function showResult(data){
$("input#autocomplete").autocomplete({
source: data;
});
}
Well there are a couple things that I would change and a couple things you are doing right. First your post request can encode the json all by it's self. Take a look at your line
$.post('phpPage.php', { /*no matter*/ }, showResult, "text");
and change it to
$.post('phpPage.php', { /*no matter*/ }, showResult, "json");
jQuery will parse the json and turn it into an object.
Now for an explanation, when you use encode_json() with php it does not create a json object all php does is format at an array like an object for JS to then turn into json.
What you are doing with JSON.parse is taking the string that php returns that will probably look like this
{"1":"jquery", "2":"AJAX","3":"JSON"}
with your example, and turning it into an object in JS.
Now for the important part. Objects in JS can be treated as an associative array, this means that they are array where the key is the index. So manipulation of an object or traversing an object can be very easy.
So you have the function showResult(res) if you want to traverse the json object and print results to the screen its pretty darn easy. First I want to change your for loop to a for...in then we just use your json object like an array
function showResult(res){
var obj = JSON.parse(res);
$("input#autocomplete").autocomplete({
source: function() {
var rows = new Array();
for (x in obj){//Assume that I know array size, skip it
$('body').append(obj[x]+'<br>');
}
return rows;
}
});
}
The only thing I changed in your code is
for (x in obj){//Assume that I know array size, skip it
$('body').append(obj[x]+'<br>');
}
This will traverse the array and plug in the correct key where x is to use every single value of the json object and add it to the body on a new line.
Now to use it with autocomplete is what ever those plugin docs say. I hope this helps you a little.
Related
I have a little bit of a problem, I have a JavaScript with jQuery where I work with an Array I got from PHP, in the script I add some data to two new arrays and here comes my problem, how can I work with those two arrays in my PHP file? I need to save the data from the two new arrays in a database. In the PHP I have a form where I enter some data about a User. Does someone knows a easy way to send my data back to the PHP?
Some information about the script: I have a table with the names of schools, and a checkbox with the id of the school as a value. when i check or uncheck one of the checkboxes the script checks if it is a school already saved in the database for this specific user or if it's a new user.
<script>
var schools = [];
var oldschools = [];
var uncheckedschools = [];
oldschools = <?php echo json_encode($oldschoolids); ?>;
$(".checkbox").change(function() {
if(this.checked) {
var additem = $(this).val();
for (var i=0; i<oldschools.length; i++) {
if (additem == oldschools[i]) {
uncheckedschools = jQuery.grep(uncheckedschools, function(value) {
return value != additem;
});
}
}
schools.push(additem);
} else {
var removeitem = $(this).val();
for (var i=0; i<oldschools.length; i++) {
if (removeitem == oldschools[i]) {
uncheckedschools.push(removeitem);
}
}
schools = jQuery.grep(schools, function(value) {
return value != removeitem;
});
}
});
</script>
I hope someone can help me with this problem!
You'll need to use AJAX to send your updates back to your server. Using jQuery's ajax() method, it would looks something like this:
$.ajax({
url: 'path/to/serverside/file.php',
dataType: 'json',
data: {schools: schools},
success: function(dataFromServer) {
//after the save is successful, you can do something here
},
error: function(dataFromServer) {
//if there was an error handle it here
}
});
EDIT: As mentioned by a few commentors, you'll need to use json_decode on the server-side to decode the JSON Object you're sending back: http://php.net/manual/en/function.json-decode.php
I am quite new to objects and OOP. I really don't know how to explain it well but I'll try.
So I am trying to read though JSON with JS, the JSON is passed from PHP. This would be easy if all of the information was on the same html page, but I' am trying something that I am new too.
So let me show my code...
First is the JS which is in app.js
var Donors = function(){
var api = this.list;
$(document).ready(function(){
$.getJSON(api, function(data){
var donorObj = data.payload;
$.each(donorObj, function(i, donor){
//console.log(donor.ign);
});
});
});
}
What I want this part to do is read from the JSON I'm giving it and console.log each name (or donor.ign) when the document is ready.
On the html page, or header.php
<script>
$(function(){
var list = <?php cbProxy(); ?>;
var Dons = new Donors();
Dons.list = list;
});
</script>
the data that's in list is the below JSON. You already know what the rest does, it just passes the JSON to the Donors() function.
JSON example:
{
"code": 0,
"payload": [
{
"time": 1349661897,
"packages": [
"49381"
],
"ign": "Notch",
"price": "15.99",
"currency": "USD"
}
I'm use to just making functions and calling it on the same page or file and this is my first doing this kind of function. How can I get the function to run with the data I sent it so it console.log() each name?
I did try
console.log(Donors());
Which only logged undefined.
New code:
app.js
var Donors = function(api){
this.list = api;
$(document).ready(function(){
$.getJSON(this.list, function(data){
var donorObj = data.payload;
$.each(donorObj, function(i, donor){
console.log(donor.ign);
});
});
});
}
index.php/inline script
<script>
$(function(){
var list = <?php cbProxy(); ?>;
var dons = new Donors(list);
});
</script>
If you execute
var Dons = new Donors();
Dons.list = list;
then you do invoke the constructor function before assigning something to the list property. That means your api variable will be undefined, as long as you haven't defined one on the prototype object from which your Donors inherit. Instead, pass the list as a parameter to the constructor:
function Donors(api) {
this.list = api;
// do something
}
var dons = new Donors(list);
I think it should be this way:
$.getJSON(api, function(data){
$.each(data.payload, function(i, donor){
console.log(donor.ign);
});
});
try this and see if works.
Hello this is code snippet which i get from Jquery Ajax based search
I am done with everything, just the problem is the following script may not be sending the POST variable and its values or may be i am not properly fetching it.
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$(document).ready(function() {
$("input[name='search_user_submit']").click(function() {
var cv = $('#newInput').val();
var cvtwo = $('input[name="search_option"]:checked').val();
var data = 'cv=' + cv + '&cvtwo=' + cvtwo; // sending two variables
$("#SearchResult").html('<img src="../../involve/images/elements/loading.gif"/>').show();
var url = "elements/search-user.php";
$.post(url, {
contentVar: data
}, function(data) {
$("#SearchResult").html(data).show();
});
});
});
});//]]>
</script>
In php file i have the following code:-
if (isset($_POST['cv']))
{
// My Conditions
}
else
{
// Show error
}
And its showing error, This means everything is correct just the post is not working properly, maybe.
Do the var data = 'cv=' + cv + '&cvtwo=' + cvtwo; // sending two variables will do the needful or we need to do any modifications. I know questions like this really annoy people, but what should i do i am stuck up.. #userD has really helped me a lot just, this part is left.
Since you're using $.post instead of $.ajax, your call should be:
$.post(url, data, function(response) {
/// ...
});
data must be a Javascript object, like this:
data = { "cv" : cv, "cvtwo" : cvtwo };
Check Jquery's documentation for more info:
http://docs.jquery.com/API/1.1/AJAX#.24.post.28_url.2C_params.2C_callback_.29
I've been looking around for a solution to what appears to be a simple problem, but am unable to find the solution...any guidance would be appreciated.
I am attempting to build a select box using JSON object retrieved from a PHP script. The PHP script (versions.php) is running a query against a database table; code is as follows:
$posts = array();
if(mssql_num_rows($result)) {
while($post = mssql_fetch_assoc($result)) {
$posts[] = $post;
}
}
header('Content-type: application/json');
echo json_encode($posts);
...and returns the following json structure:
[{"version":"3.3.0"},{"version":"1.5.0"}]
The PHP file is being called from a central JS file, which is structured as follows:
jQuery(function($){
$.getJSON('versions.php', function(data) {
var select = $('#release-list');
$.each(data, function(key, val){
var option = $('<option/>');
option.attr('value', val)
.html(data)
.appendTo(select);
});
});
});
Looking at firebug, I see lists of objects, but not the values in the array. I guess this is related to the code in the javascript file above - just not sure how to access the values from the json object.
Thanks in advance.
You're almost there. Based on your JSON structure, It should look something like this:
jQuery(function($){
$.getJSON('versions.php', function(data) {
var select = $('#release-list');
$.each(data, function(key, val){
$('<option/>').attr('value', val.version)
.html('version ' + val.version)
.appendTo(select);
});
});
});
A button click fires my function that fetches image data via an AJAX-call:
$("#toggle_album").click(function () {
album_id = $("#album_id").val();
$.post('backend/load_album_thumbnails.php', {
id: album_id
}, function(xml) {
var status = $(xml).find("status").text();
var timestamp = $(xml).find("time").text();
$("#album_thumbs_data_"+album_id+"").empty();
if (status == 1) {
var temp = '';
var output = '';
$(xml).find("image").each(function(){
var url = $(this).find("url").text();
temp = "<DIV ID=\"thumbnail_image\">[img-tag with class="faded" goes here]</DIV>";
output += temp;
});
$("#album_thumbs_data_"+album_id+"").append(output);
} else {
var reason = $(xml).find("reason").text();
var output = "<DIV CLASS=\"bread\">"+reason+"</DIV>";
$("#album_thumbs_data_"+album_id+"").append(output);
}
$("#album_thumbs_"+album_id+"").toggle();
});
});
The data is returned in XML format, and it parses well, appending the data to an empty container and showing it;
My problem is that my image overlay script:
$("img.faded").hover(
function() {
$(this).animate({"opacity": "1"}, "fast");
},
function() {
$(this).animate({"opacity": ".5"}, "fast");
});
... stops working on the image data that I fetch via the AJAX-call. It works well on all other images already loaded by "normal" means. Does the script need to be adjusted in some way to work on data added later?
I hope my question is clear enough.
Okay, apparantly I hadn't googled it enough. Surfing my own question here on stackoverflow pointed me to other questions, which pointed me to the JQuery live() function: live().
However, it does not work on hover(), so I rewrote the script to use mouseover() and mouseout() instead:
$("img.faded").live("mouseover",function() {
$(this).animate({"opacity": "1"}, "fast");
});
$("img.faded").live("mouseout", function() {
$(this).animate({"opacity": "0.5"}, "fast");
});
... and now it works flawlessly even on the content I fetch from the AJAX-call.
Sorry if anyone has started writing an answer already.
You have to bind the new events each time you add a DOM element to the page.
There is a built-in function in jquery called live that does that for you.
I noticed you add the images from your xml; you can add there the new binds too.
$(xml).find("image").each(function(){
//this actually creates a jquery element that you can work with
$('my-img-code-from-xml-goes-here').hover(
function() {
$(this).animate({"opacity": "1"}, "fast");
},
function() {
$(this).animate({"opacity": ".5"}, "fast");
}
//i did all my dirty stuff with it, let's add it where it belongs!
).appendTo($('some-already-created-element'));
});
EDIT: corrected a wrong sentence.