I'm using jquery UI auto completion to give the project name suggestion in a list. I'm providing a project name list as a json array from the php file as follows.
function getProjectList($projectList) {
foreach ($projectList as $project) {
$jsonArray[] = array('name' => $project['projectName'], 'id' => $project['projectId']);
}
$jsonString = json_encode($jsonArray);
return $jsonString;
}
And I'm geting the whole project name list to a javascript variable.
var projectsForAutoComplete=<?php echo $timesheetForm->getProjectListAsJson(); ?>;
This project list have more than 10000 projects and I'm have 20 project name text boxes which should provide the auto suggestions. So when I try to do it as follows at the load time the page get 30 seconds to get load due to higher procession of the js.
$(".project").autocomplete(projectsForAutoComplete, {
formatItem: function(item) {
var temp = $("<div/>").html(item.name).text();
return temp.replace("##", "");
}
,
matchContains:true
})
So I need to load the auto suggestions in the key press event as in the demo in the Jquery Documentation. http://jqueryui.com/demos/autocomplete/#remote-jsonp
But the example shows how to do it with a remote json source. Can I do the same with the local json array. Is it possible. Can someone help me on this.
If you already have the json array on the page then you can simply include it as a source
source: projectsForAutoComplete
However, autocomplete expects it's source to be a 1D array and your array is 2D. You'll either need to make two arrays, provide the one with the strings as the source, and write a function to map the name to the id, or do something similar to the combobox example in the jQueryUI autocomplete documentation.
Related
I have a question about using data pulled from the database in javascript.
In my controller I have this:
$this->view->projects = $projectsarray;
I send the array to my view. There I will loop through my array and show the titles. Now I need to get that array in javascript because I want to create a highchart with the data...
Does anyone knows how I could do this easily?
EDIT:
I now have this in my controller: (overviewcontroller)
public function getprojectdataAction($id){
}
In my javascript file:
var id = 1;
$.post('/overview/getprojectdata/',{id:id},function(data){
alert("test");
});
But I get the error that the resource can't be found:
POST http://www.namesite.com/overview/getprojectdata/ 404 (Not Found)
What am I doing wrong?
I assume $this->view->projects is array or object
in your view file
<script>
var projects = <?php echo json_encode($this->projects);?>;
console.log(projects);
</script>
then watch your firebug ...
you can do this by converting array to JSON you can send a ajax request to same controller
and return echo json_encode($array); then you can use directly with responce by decoding it...
$.post('controller/action',{id:id},function(data){
var arrayJson=JSON.parse(data);
});
you can use arrayJson as data array...
you can use json_encode in the php part of the code to generate a javascript object out of your array. For example:
$php = array("myAttrib" => "hallo");
echo json_encode($php);
and in javascript you can use
alert (output.myAttrib);
, where output refers to echo json_encode(php). This code would open a box showing "hallo". Your question seems to be quite similar to how to use json_encode. For creating of a highchart also this post Highcharts data series issue with ajax/json and PHP could be of interest for you.
I used ajax to call a php to get me some values stored in my DB.
I then echo these values in my php so that i can use the responseText property to get these retrieved values (which i want to store in a JS array) for further referral.
Here's where i get stuck. I do manage to do this when I have to retrieve just 1 row from the DB (I did this by separating the fields using a ',' and subsequently using the split() function in JS to parse the string). However when my DB returns more than 1 row then I reach a deadend as this method of mine doesn't seem to work. Kindly advice the easiest way to overcome this hurdle.
use
var jsArray = {};
$.each(response, function(i, item) {
jsArray[i] = item;
});
the above JQuery loop is equivalent to PHP loop:
foreach($response as $i => $item) {
$jsArray[$i] = $item;
}
You can convert the PHP array of multiple DB rows to json using json_encode on server side and parse JSON on the client side using javascript reading help from here. A more code oriented answer needs some code in question to work with.
My questions keep getting abandoned even though I am replying, so I am going to remake my question in the hopes that someone can see my error and help me out. I will try to be as thorough as possible.
Step 1: I have an array named divisionsLarge in the following form:
divisionsLarge = [{ "car":"Toyota", "color":"blue", "numberTires":"four" }, { "car":"Honda", "color":"red", "numberTires":"four"}, etc. etc. ... ]
(This data is fictional, but it's the process that is wrong somewhere (also ignore the fact that numberTires is being stored as a string instead of a int, it's fictional folks :P)
Anyway, I have 92 of the above entries, all with the same keys: car, color, and numberTires.
Now, I go through the array with the following function loop in order to build an array with just car & numberTires key:
var divisions = [];
for (var i = 0; i < divisionsLarge.length; i++) {
if(divisionsLarge[i].numberTires != "two"){
var obj = { "car": divisionsLarge[i].car,
"numberTires": divisionsLarge[i].numberTires};
divisions.push(obj);}
}
Ok, at this point, I THINK everything is good to go. If I use the console in FireBug and type in divisions[0] I get a beautiful object that consists of, for example,
Object { car = "Toyota", numberTires = "four"}
(I think there are still "" around the car & numberTires entries, this is just how FireBug displays the object, I could be wrong)
Now here's what I need help with. I've created more .ajax queries than I can count. I've used JSON.stringified, I've not used JSON.stringified, I've used json_decode(), I've just done print_r($_POST)...I've done so many things that I am completely unable to analyze what is affecting what in order to diagnose what the problem might be. It seems my .ajax POSTS might be wrong, it seems my PHP might be wrong. So here are the questions I would GREATLY appreciate being answered:
1) Is the divisions array being created by the javascript considered JSON, or in a format easily converted to JSON?
2) What does my AJAX call need to be? I have tried so many AJAX calls that I have NO idea what is considered right/wrong. Also, please use divisions and not the snippet of the array I provided above, as the divisions array is dynamically generated by what's contained in divisionsLarge.
3) What does my divisions.php PHP file need to look like? Right now it has an HTML skeleton around it with <script></script> tags that reference divisionsLarge.js and divisions.js [do these need to be in one .js file?] I have seen blank pages and Array() for so long that I'm even doubting the rest of the PHP file now.
4) How do I get, for example, the color value of the first index? This seems rudimentary but most examples that I see are just querying an array of just one object, e.g. echo $_POST["color"], but I have multiple entries of color, so I'm not sure how to just ask for the first one. I would like to know this mostly because I have had such bad success with testing whether the array is working or not - I have lost all faith in print_r($_POST) and var_dump($json).
Okay, First your questions. Then the code:
1.- Divisions is not considered JSON, it is just an object array. All javascript objects can easily be turned into JSON using JSON.stringify(); Look at the code below.
2.- Look at the code below.
3.- I am not sure what kind of processing you need in your PHP. The code below assumes you are posting this to another page, where you will do some processing and output something, that you can use in the complete function.
4.- Look at the code below.
I think this is what you want to do:
Javascript
divisionsLarge = [{ "car":"Toyota", "color":"blue", "numberTires":"four" }, { "car":"Honda", "color":"red", "numberTires":"four"}];
var divisions = [];
for (var i = 0; i < divisionsLarge.length; i++) {
if(divisionsLarge[i].numberTires != "two"){
var obj = { "car": divisionsLarge[i].car,
"numberTires": divisionsLarge[i].numberTires};
divisions.push(obj);}
}
//I am just going to send one of your array elements as a JSON object.
var postData = JSON.stringify(divisions[0]);
var url = "url where you want to post your data";
$.ajax(url, {
type: "POST",
data: { "jsonBeingSent" : postData },
success: function(data) {
//Do whatever you need to do with your PHP output here.
//If you are using something like my php sample then you will be receiving a JSON object(s)
}
});
Now, on your PHP you probably want something like this:
<?php
//You may want to do some checking about the sender, and so on.
$receivedData = json_decode($_POST['jsonBeingSent']);
//You should see something like this if you print_r $receivedData
// object(stdClass) {
// [car] => ...
// [numberTires] => ...
// }
//So you could access the car value like this
echo $receivedData->{'car'};
//Do your processing and then, if you are using an array or object you can use `json_encode()` to output your data.
?>
Hope that helps.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Call php function from javascript
can anyone help me on how can I call the php function on JS function?
Here is the event:
I have 2 selection box (e.g projects and task)
when selecting on project selection box, the task selection box will be populated.
values populated on the task selection box is in my PHP DAO.
Here is my javascript but it doesn't work but my idea is like that
function getProjTask()
{
var taskList = <?php $projTask->getProjectTask("ProjectName"); ?>
//values for task selection box has been populated here
}
For this to work, you need to use AJAX. This can be done using just plain old javascript or your favorite library. Using a library would be much easier. I tend to use YUI myself.
What you need to do is quite simple:
Listen to project selection box for changes.
When a change happens, send a request using AJAX to your PHP endpoint.
Your endpoint then returns a JSON response containing the values of the task selection box.
Use javascript to decode the JSON response and create <option> elements for your task selection box.
A quick example:
PHP side:
<?php
$list = array('list' => array('task1' => 1, 'task2' => 2));
header('Content-Type: application/json; charset=utf-8');
echo json_encode($list);
exit();
JS side (I am using YUI, and this is for the AJAX only, you will still need to write code to listen for the selection box changing):
<script>
// Create a YUI instance using io-base module.
YUI().use("io-base", function(Y) {
var uri = "get.php?foo=bar";
// Define a function to handle the response data.
function complete(id, o) {
var data = Y.JSON.parse(o.responseText);
//Parse the JSON, loop and insert the options here.
};
// Subscribe to event "io:complete"
Y.on('io:complete', complete);
// Make the request
Y.io('http://mysite.com/myendpoint.php');
});
<script>
Either use ajax to make a request dynamically. If you just want the value of the name to be in that function, then the error will be because you have no quotes (and it being a string)
function getProjTask()
{
var taskList = '<?php $projTask->getProjectTask("ProjectName"); ?>';
//values for task selection box has been populated here
}
maybe you could find this useful. You need AJAX for this. jQuery is the easiest way for me but if you want to use ajax using php try http://www.xajaxproject.org/
A friend of mine uses it all the time and it works good for him. I preffer js and jquery
If you don't mind learning a new language you can use haxe. Its a cross platform language. You can develop for js and php using haxe and link them together using haxe itself ( haxe remoting ).
I'm trying to load data into the html5 canvas roulette which I found here:
http://www.switchonthecode.com/tutorials/creating-a-roulette-wheel-using-html5-canvas
I added another button called loader which will load the data from a php file. The data is an array of names. I then assigned it to the people array. Then called the drawRouletteWheel(). The drawRouletteWheel uses the data from the people array.
var people = [];
$('#loader').click(function(){
$.post('loader.php', function(data){
people = data;
drawRouletteWheel();
});
});
The loader.php file just loads random records fetched from mysql database:
$select_random = $db->get_results("SELECT people FROM tbl_people ORDER BY RAND() LIMIT 12");
if(!empty($select_random)){
foreach($select_random as $k=>$v){
$data[] = $v->people;
}
echo json_encode($data);
}
Something is actually being loaded into the roulette but it seems to be incomplete. And firebug is also returning something:
What do I need to do here?It seems like the data that was returned from the php file isn't being treated as an array.
The data that is returned from the php page is treated as a string, so you are getting individual letters as javascript gets the character at each index.
To fix this:
var people = [];
$('#loader').click(function(){
$.post('loader.php', function(data){
people = $.parseJSON(data);
drawRouletteWheel();
});
});