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

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

Related

Pass jquery - generated variable to php in same page

I have a script that gets tha data on the row of a button when that button is clicked. The id of the button is id='show-button'. This is the script:
<script>
$(document).ready(function(){
$(".show-button").click(function() {
var $row = $(this).closest("tr"); // Find the row
var names = $row.find(".name").text(); // Find the name
var surname = $row.find(".surname").text(); // Find the surname
var lecturer_id = names."_".surname;
$("#show_dialog").dialog({autoOpen: false});
$(".show-button").on("click", function() {$("#show_dialog").dialog("open");});
});
});
</script>
The last two significant lines open a jquery dialog box.
With that, i mean these lines:
$("#show_dialog").dialog({autoOpen: false});
$(".show-button").on("click", function() {$("#show_dialog").dialog("open");});
Now, I need to pass the value of var lecturer_id to a php script outside this code, but inside the same document. This php code will generate the content of the dialog crated by these two lines. Lets assume that I just want to echo the variable passed inside the dialog box (with the php).
Any idea on how to make it work?
Your question is not 100% clear, but, just an idea, if I got you right:
<script>
$(document).ready(function(){
$(".show-button").click(function() {
var $row = $(this).closest("tr"); // Find the row
var names = $row.find(".name").text(); // Find the name
var surname = $row.find(".surname").text(); // Find the surname
var lecturer_id = names."_".surname;
$.post( "test.php", { names: names, surname: surname; lecturer_id: lecturer_id })
.done(function( data ) {
$("#show_dialog")[0].innerHTML = data ;
$("#show_dialog").dialog({autoOpen: false});
$(".show-button").on("click", function() {$("#show_dialog").dialog("open");});
});
});
});
</script>
And I agree with #JayBlanchard you don't even need any ajax call here, just generate your html like:
$(document).ready(function(){
$(".show-button").click(function() {
var $row = $(this).closest("tr"); // Find the row
var names = $row.find(".name").text(); // Find the name
var surname = $row.find(".surname").text(); // Find the surname
var lecturer_id = names."_".surname;
$("#show_dialog")[0].innerHTML = ' Name = '+names +'; Surname = '+surname ;
$("#show_dialog").dialog({autoOpen: false});
$(".show-button").on("click", function() {$("#show_dialog").dialog("open");});
});
});
You can use jQuery post or ajax.
$.post( "test.php", { name: "John", time: "2pm" })
.done(function( data ) {
alert( "Data Loaded: " + data );
});
test.php will be the reciving end of php, where it expects data sent by jquery.
{ name: "John", time: "2pm" } will be the data you are wishing to send off to php.
data will be the the data output by php.
refer to http://api.jquery.com/jquery.post/ for more information

Use $.post methods returned function(data) value to variable

Dear Coders!
The purpose of my code:
Get URL of files listed in specific folder, then assign them to an Array in javascript.
How I'm imagining it:
JavaScript function in test.php uses $.post() method to send a value to getURL.php file. After this, getURL.php uses this value to get specific file URLs in a specific folder. I'm getting the result(s) in the $.post() methods function(data) parameter. After this, the resulted value of the "data" is (/would be used) in JavaScript.
The problem:
Inside the $.post() methods function: function(data,status) I'm satisfied with the result of the returned value of the data parameter; the PROBLEM is that I can't assign it's value outside this function:function (data,status)`.
TEST.php
<script src="jquery-1.9.1.js">
</script>
<script type="text/javascript">
var imgPath; // <--He is who should get the value of "data"
function getTargetUrl(szolg){
$.post(
"getURL.php",
{ x: szolg },
function(data,status){
alert("in function: " + data + " status: " + status);
imgPath=data;
alert (imgPath);
}
);
}
$(document).ready(function() {
var a="szolg5"; //it will be "user defined", used in getURL.php
getTargetUrl(a);
alert(imgPath);
});
</script>
getURL.php
<?php
if(isset($_POST["x"])){
$queryGlob='img/'.$_POST["x"].'/batch/*.jpg';
foreach (glob($queryGlob) as $filename) {
$imgFiles=json_encode($filename);
$imgFiles=str_replace('\/','/',$imgFiles);
echo $imgFiles;
}
//$data = str_replace('\\/', '/', json_encode(glob('img/'.$_POST["x"].'/batch/*.jpg')));
}
else{
$imgFiles="FAIL";
echo $imgFiles;
}
?>
Note: for testing I'm using Google Chrome.
So that's all I guess, hope someone can give me a solution and possible explanation.
The post call is asynchronous, so in your code here:
$(document).ready(function() {
var a="szolg5"; //it will be "user defined", used in getURL.php
getTargetUrl(a);
alert(imgPath);
});
...the alert occurs before the post call has completed, and so shows the old value of imgPath. What you want to do is pass a function into getTargetUrl that it will call when the post completes, and put the subsequent code in there.
Something like this:
var imgPath; // <--He is who should get the value of "data"
function getTargetUrl(szolg, callback){
$.post(
"getURL.php",
{ x: szolg },
function(data,status){
alert("in function: " + data + " status: " + status);
imgPath=data;
callback();
}
);
}
$(document).ready(function() {
var a="szolg5"; //it will be "user defined", used in getURL.php
getTargetUrl(a, function() {
alert(imgPath);
});
});
And you can do away with the global variable entirely by doing what post does and passing the data back as an argument:
function getTargetUrl(szolg, callback){
$.post(
"getURL.php",
{ x: szolg },
function(data,status){
alert("in function: " + data + " status: " + status);
callback(data);
}
);
}
$(document).ready(function() {
var a="szolg5"; //it will be "user defined", used in getURL.php
getTargetUrl(a, function(path) {
alert(path);
});
});
No, AJAX is asynchronous meaning that the $.post method will return immediately. If you want to use the results of an AJAX call, the only safe place to do so is inside the success callback. Do not attempt to assign the result to global variables.
So you should put the alert inside the success callback.
As explained by others the reason for this behavior is the asynchronous nature of ajax requests.
My solution will to return the ajax promise request from getTargetUrl and use it to register callback methods
function getTargetUrl(szolg){
return $.post(
"getURL.php",
{ x: szolg },
function(data,status){
alert("in function: " + data + " status: " + status);
alert (data);
}
);
}
$(document).ready(function() {
var a="szolg5"; //it will be "user defined", used in getURL.php
getTargetUrl(a).done(function(data){
alert('from callback' + data);
});
});

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.

Calling function and running it

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.

Jquery Select list items in loop using keyup and key down

I am trying to make autosuggest in Jquery,ajax and json to search cities when user register to website.
So far I am able to get results from database.And i appended to list.but now i need to select data using up down and enter keys.
Key down event is adding class to first city. But I want to loop through all results using key up and down and add value to city textbox if user hits enter. I limit data by 5 in php so 5 results are coming in list item.
Here is my code:
$('#city').keyup(function (event) {
var input_query = $(this).val();
$.post("get_city.php", {
"query": input_query
}, function (data) {
$('#cityres').html("");
$.each(data, function (i, item) {
$('#cityresults').append("<li>" + item.city + "</li>");
});
}, "json");
//below code is for key event
var key = gtKeycode(event);
if (key == 40) {
// I am not sure i need to do this way
$('li').first().addClass('SelectedCity');
}
});
function gtKeycode(e) {
var code;
if (!e) var e = window.event;
if (e.keyCode) code = e.keyCode;
return code;
}
i think i have now the solution for your problem hope this will help you..!
I made a php file that echo out json encode just list this:
//PHP "action.php?action=show"
e.g $option[] = array(
'option0'=>".Choose an option",
'option1'=>'somepage1',
'option2'=>'somepage2',
'option3'=>'somepage3');
echo json_encode(array('options'=>$option));
I made up html that will be the handler of the output, then will append
<select class="myoptions">
</select> | <span class="optcap"></span>
JS
function selectedOption()
{
var myoptions = $(".myoptions");
$.ajax({
type:'GET',
url:'action.php?action=show',
dataType:'JSON',
success:function(data){
if(data.s==1){
myoptions.empty();
$.each(data.options, function(x,val){
myoptions.append("<option class='option' value='"+val.option0+"'>"+val.option0+"</option>"
+"<option class='option' value='"+val.option1+"'>"+val.option1+"</option>"
+"<option class='option' value='"+val.option2+"'>"+val.option2+"</option>"
+"<option class='option' value='"+val.option3+"'>"+val.option3+"</option>");
});
}
}
});
}
$(document).ready(function(){
selectedOption();
$(".myoptions").keyup(function(){
var option = [];
$("option.option:selected").each(function(x){
option[x] = $(this).val();
});
$(".optcap").html("["+option+"]");
});
});

Categories