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.
Related
I tried the JavaScript example from the Yelp developer site. Everything´s working but I wonder how to append the JSON data to an html list (ul). The list should contain restaurants in my town. Does anybody know how to do this?
P.S. PHP would be OK, too.
Edit:
Thank you for your answers but it still doesn´t work. I´m not able to give you more details because the Yelp API is poorly documented and I´m new to JSON and PHP.
If the JSON object is being returned as part of an Ajax request you'll need something vaguely like this:
$.post("yourajaxrequest.php", //calls .php file and transmits data via $_POST
{
//variables required by the PHP file go here
},
//the function to perform when an object is returned from .php file
function(toreceive){
var obj = JSON.parse(toreceive);
var first = obj.returnone;
});
Without reading the Yelp documentation I'm not sure quite how you'll receive the object from Yelp, but the JSON.parse() method is the approach you should take to decode the object.
After parsing the object to a variable, you can assign the elements of the object by calling object.*insert array value here*;
This would be declared in PHP normally with something similar to:
$toencode = "The first string to be encoded";
$tosend['returnone'] = $toencode;
echo json_encode($tosend);
exit;
You can then append to a <ul> by using .append
<html>
<head>
</head>
<body>
<ul id="list">
</ul>
</body>
</html>
In your <script>:
$('#list').append('<li>'+first+'</li>');
Without any sample code or reading the Yelp documentation, there's not a lot more to go on.
Hope it helps.
**edited to add closing bracket and semi-colon to first line of code.
assume that outputs of the api call is ["blah", "blah", "blah", "blah"]
$("#container").append("<ul>");
$.ajax({
// options go here
success: function(datas){
for(var i in datas){
var data = datas[i];
$("#container ul").append("<li>"+data+"</li>");
}
}
});
demo: http://jsfiddle.net/cDU52/1/ - fixed
read: http://api.jquery.com/append/
read: How to Loop through plain JavaScript object with objects as members?
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.
I'm having trouble accessing an array created in php, to use in a javascript block.
I know about
<?php echo json_encode($myArray); ?>
but I'm not getting any results out of it.
I have a 'index.html' file where I try to access the array through javascript.
The html page exists out of a drop down menu. When the user chooses an item in that drop down menu, the chosen item is used as an argument to retrieve data from a database.
The 'ajax.js' file contains the code to execute the 'retrieve.php' file which constructs the array ('$myArray') from database content. So the array is retrieved through an ajax call.
Can I 'echo' to the javascript code from my php file:
echo 'dataArray = ' . json_encode($data_array) . ';';
and use that javascript variable?
In other words, how can I execute my javascript code using that new 'dataArray' variable?
To get the bigger picture: I'm trying to use that array for use in a 'Google Chart', for which I need to use javascript to display the chart.
I can query all data and put it in a php array, but I'm not succeeding in transfering it properly to my html page with javascript and reload the chart.
Edit: I use an ajax call to no to reload the entire page.
Instead of " echo 'dataArray = ' . json_encode($data_array) . ';'; ", you should just write this-
"echo json_encode($data_array)"
And then interpret it in the client using JSON.parse(response) where response the response you received from the server (the json)
I found that the best way to do this is like so:
Client code:
<script>
var phpdata = <?=json_encode($jsData)?>;
</script>
Server code:
$jsData = '';
$jsData->first = $first;
$jsData->second = $second_array;
Client side usage:
alert(phpdata.second[1]);
EDIT:
To get an array from php using AJAX, use jQuery http://api.jquery.com/jQuery.getJSON/
Client side:
var stored_array;
$.getJSON(url, function(data){
stored_array = data;
// run any other code you wish to run after getting the array.
});
Server side:
print(json_encode($array));
this will get a json encoded variable and store it for your use.
Yes you can use this array of php by assigning the above json_encode function
You can use it as associative array if the array is associative or object used in php and if no-associative you can use it as normal array.
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>"
)
I've a php file which processes a query and returns an array.
How do i get these and array and parse them and display them using ajax.
I call the file using ajax. Its used to display the matching products while typing a text box with the price...
responseText doesn't return anything...
Your data needs to be encoded in a format that JavaScript can understand, like JSON. You want to serialize the PHP array and return that as the HTTP Response, more information on how to JSON serialize data can be found here. Once the data is serialized, you can parse it in the ResponseText as though it were a JavaScript object (i.e. you can pull data like this: ResponseText[0].some_key)
I should note that jQuery makes this very, VERY easy. Like... this easy:
var url = '/json-data.php?id=2';
$.getJSON(url, function(data) {
$("#target").text(data.some_key);
}