Calling function and running it - 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.

Related

Send data via '.getJson' in jQuery and retrive on 'PHP' File

So i want to send a variable to my php page and output appropriate json there based on the data.
THis is what i did.I am new to jquery but have done php
$(function() {
$("#json-one").change(function() {
var dropdown = $(this);
var name=dropdown.val();
$.getJSON("categories_php?name=",{ "name": name },
function(data) {
prompt(data.name);
var $jsontwo = $("#json-two");
$jsontwo.append("<option>" + data.name + "</option>");
});
});
});
on the php page for test i have not done much
<?php
$m=new Mongo();
$db=$m->admin;
$collection=$db->categories;
$cur=$collection->find();
$name['name']= $_REQUEST['name'];
print_r(json_encode($name));
?>
You can use:
$.getJSON("categories_php",{ name: name }, function() {
//Some code
});

Processing PHP variable in javascript and returning back to PHP

I am working on an application where I fetch data from database and process it using javascript/jquery like this:
$sqlEdit = "select revisionContent from tbl_revision where revisionId='".$_SESSION['contentId']."'"; //Query to fetch the result
$rsEdit = $dbObj->tep_db_query($sqlEdit);
$resEdit = $dbObj->getRecord($rsEdit);
$IdLessContent = $resEdit['revisionContent'];
<script language="javascript">
var getSavedContent = '<?php echo json_encode($IdLessContent); ?>';
var trimmedCont=($.trim(getSavedContent).slice(1));
//console.log(trimmedCont);
var lengthCont= trimmedCont.length;
var trimmedCont=$.trim(trimmedCont.slice(0,lengthCont-1));
console.log(trimmedCont);
var test = $('<div class="addId">');
test.append(trimmedCont);
//console.log(test.html());
test.children().each(function(index, value) {
$(this).attr('id', "com-"+randomString());
});
//console.log(test.html());
viewContent = test.html();
I get the required data in viewContent.I want to display it on the page in this section
<div id="mainWrap" onClick="fnDestroyEditable();">
<?php echo $resEdit['revisionContent']; ?> //THis is the unprocessed data displayed directly from database.I want to display the processed data here
</div>
I know we cannot get javascript variables to PHP as both are different (one server side and other client). But then how can I achieve this in my scenario?
EDIT I would like to add that the returned data is HTML stored in the database.So,I get the html->process it(add id attribute)->want to return back after processing
you can put the viewContent inside #mainWrap using javascript.
just make sure the DOM is loaded wrapping your js code with $(document).ready()
and add:
$('#mainWrap').html(viewContent);
at the end of your function.
$(document).ready(function () {
var getSavedContent = '<?php echo json_encode($IdLessContent); ?>';
var trimmedCont=($.trim(getSavedContent).slice(1));
//console.log(trimmedCont);
var lengthCont= trimmedCont.length;
var trimmedCont=$.trim(trimmedCont.slice(0,lengthCont-1));
console.log(trimmedCont);
var test = $('<div class="addId">');
test.append(trimmedCont);
//console.log(test.html());
test.children().each(function(index, value) {
$(this).attr('id', "com-"+randomString());
});
//console.log(test.html());
viewContent = test.html();
// put viewContent in the innerHtml of your wrapper
$('#mainWrap').html(viewContent);
});
if you need to send back info to the server you have to do it with ajax.
I added a javascript function addId() that will be invoked on click on one of the elements.
the new code is:
$(document).ready(function () {
var getSavedContent = '<?php echo json_encode($IdLessContent); ?>';
var trimmedCont=($.trim(getSavedContent).slice(1));
//console.log(trimmedCont);
var lengthCont= trimmedCont.length;
var trimmedCont=$.trim(trimmedCont.slice(0,lengthCont-1));
console.log(trimmedCont);
var test = $('<div class="addId">');
test.append(trimmedCont);
//console.log(test.html());
test.children().each(function(index, value) {
$(this).attr('id', "com-"+randomString());
});
//console.log(test.html());
viewContent = test.html();
// put viewContent in the innerHtml of your wrapper
$('#mainWrap').html(viewContent);
$('#mainWrap .addId').children().click(function({
addId(this);
}));
}
addId = function(elem){
// elem is the child element you clicked on
// $(elem).attr('id') should be "com-[randomString]"
$.ajax({
type: "POST",
url: "path/to/php/script", // update id PHP script
data: data, // whatever you need in json format
dataType: "json",
error: function() {
// error function you want to implement
errorFunction();
},
success: function(resp) {
// do whatever you need with the response from you PHP action
}
});
};
if you need to to call server with out human interaction just substitute
$('#mainWrap .addId').children().click(function({
addId(this);
}));
with:
$('#mainWrap .addId').children().each(function({
addId(this);
}));
if I undesrstand you, you shold only add in the end of your js code this line:
$('#mainWrap').html(viewContent);
If you want to send JS data to PHP, you should use ajax request.

javascript based Jquery ajax function, unable to send post values

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

autocomplete source from php file

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.

JQuery, AJAX, PHP, XML; Image overlay script stops working on callback content

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.

Categories