php to js array convert with jquery's ajax - php

Im trying to convert 5 PHP arrays to 5 js arrays.
I used to transfer php variables to js variables with json like this:
$return['variable'] = $variable;
echo json_encode($return);
And then fetch it as json object on the js side like this:
success : function(data) {
alert(data.variable);
}
now things are a bit more complicated, i need to transfer these 5 php arrays from a php script to my js script as 5 js arrays:
PHP arrays:
$i = 0;
while ($location = mysql_fetch_array($get_locations)) {
$location_full_name[$i] = $location['loc_full_name'];
$location_main_name[$i] = $location['loc_main_name'];
$location_sub_name[$i] = $location['loc_sub_name'];
$location_anchor_id[$i] = $location['loc_anchor_id'];
$location_type[$i] = $location['loc_type'];
$i++;
}
and fill these corresponding arrays:
var location_full_name = new Array();
var location_main_name = new Array();
var location_sub_name = new Array();
var location_anchor_id = new Array();
var location_type = new Array();
i dont know how to do this. hope i can get some help :)
regards,
alexander

Maybe if you post what returns in "data" so we can help you more (i think). hehe.
I suggest, for your php code, where you set the data into the arrays:
$i = 0;
$rsl = array();
while ($location = mysql_fetch_array($get_locations)) {
$rsl[$i]['full_name'] = $location['loc_full_name'];
$rsl[$i]['main_name'] = $location['loc_main_name'];
$rsl[$i]['sub_name'] = $location['loc_sub_name'];
$rsl[$i]['anchor_id'] = $location['loc_anchor_id'];
$rsl[$i]['type'] = $location['loc_type'];
$i++;
}
echo json_encode($rsl);
So to get this on the javascript
// You could do the same... var location = []...
var location_full_name = new Array();
var location_main_name = new Array();
var location_sub_name = new Array();
var location_anchor_id = new Array();
var location_type = new Array();
...
dataType: "json",
success : function(data) {
$.each(data, function(index, arr){
location_full_name[index] = arr['full_name'];
...
});
}

For each of your arrays, store the value returned from json_encode. And/or make them one array/object and do the same.

You can utilize the PHP array that is actually an ordered map. Below is an example:
PHP:
<?php
$location_full_name = array("Google, Inc.", "Siku-Siku.com");
$location_type = array("Google headquarter", "Virtual address");
$ret = array("full_name" => $location_full_name, "type" => $location_type);
echo json_encode($ret);
?>
JavaScript (jQuery):
<script type="text/javascript">
$(function() {
$.get("test.php", function(data) {
console.log(data.full_name[1]); // Prints "Siku-Siku.com".
}, "json");
});
</script>

Related

Object in jquery using json response

I want to create an object in jquery using a json response that is return from my controller
var cellContents = {'29-08-2018': '20','18-08-2018': '60'};
This is the desired format that i want and below given is my json response
{"status":1,"result":[{"followup_datee":"17-08-2018","date":[{"fcount":"1"}]},{"followup_datee":"18-08-2018","date":[{"fcount":"1"}]}]}
i tried some code to make the format that i want but it failed this is the code that i tried
var arr2 = [];
//var cellContents = JSON.parse(data.result);
for(var i=0; i<data.result.length; i++){
var arr = [];
for(var j=0; j<data.result[i].date.length; j++)
{
arr.push(parseInt(data.result[i].date[j].fcount));
}
var test = [data.result[i].followup_datee];
arr2.push(test.concat(arr));
}
var jsonString = JSON.stringify(arr2);
console.log(jsonString);
after i tried this code i got some response in the console like this
[["17-08-2018",1],["18-08-2018",1]]
This is the controller that i am using in php
public function getLeadcount()
{
$status = 1;
$arr = [];
$sess = $this->session->userdata('user_id');
$result = $this->mdl_lead_registration->getLeaddate($sess);
if(!empty($result))
{
$status = 1;
foreach($result as $res)
{
$res->{'date'} = '';
$res->date = $this->mdl_lead_registration->getLeadcount($sess,$res->followup_datee);
}
}
echo json_encode(array("status" => $status,"result" => $result));
}
I think you all understand my problem . Any sort of help is appreciable.
Use the following code:
var data = {"status":1,"result":[{"followup_datee":"17-08-2018","date":[{"fcount":"1"}]},{"followup_datee":"18-08-2018","date":[{"fcount":"1"}]}]};
var obj = {};
for (var i = 0; i < data.result.length; i++){
obj[data.result[i].followup_datee] = parseInt(data.result[i].date[0].fcount);
// Here you change the property.
// In js you can access to an object's property like an array,
// see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors.
// If you want to use the count as a string, use instead:
// obj[data.result[i].followup_datee] = data.result[i].date[0].fcount;
}
console.log(obj);

PHP array and jQuery autocomplete not working on first character

My autocomplete plugin from jQuery is not working first time with one character in the textbox.If I continue to type more than one character then the autocomplete kicks in...
So I'm expecting result from the first character but is not getting anything..
<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$( "#names" ).keyup(function() {
autocompleteNames();
});
});
function loadNames(){
//Gets the name
var nameSelected = $("#names").val();
var namesList = "";
$.ajax({
url: 'names.php',
type: "POST",
async: false,
data: { sport: nameSelected}
}).done(function(names){
namesList = names.split(',');
});
//Returns the javascript array of names.
return namesList;
}
function autocompleteNames(){
var names = loadNames();
$("#names").autocomplete({
source: names,
minLength: 1
});
}
</script>
</head>
<body>
Namn: <input type="text" id="names" name="names" />
</body>
</html>
And here's my names.php file that's very simple
<?php
$sport = $_POST["sport"];
//Defines the name array.
$names[0] = "Sam";
$names[1] = "Anna";
$names[2] = "Jens";
$names[3] = "Johanna";
$names[4] = "Emma";
$names[5] = "Mikael";
$names[6] = "Mattias";
$names[7] = "Sebastian";
$names[8] = "Johan";
$names[9] = "Mona";
$names[10] = "Lina";
$names[11] = "Linda";
$names[12] = "Ebba";
$names[13] = "Andreas";
$names[14] = "Marcus";
$names[15] = "Markus";
$names[16] = "Anders";
$names[17] = "Maria";
$names[18] = "Sandra";
$names[19] = "Jonatan";
$names[20] = "Jacob";
$names[21] = "Carolina";
$names[22] = "Tom";
$names[23] = "Tim";
$names[24] = "Zlatan";
$names[25] = "Emelie";
//Defines an empty variable that will return the javascript array.
$teams = generateAutocompleteArray($names);
//Returns the teams in the appropriate javascript array format.
echo $teams;
//Function converts PHP array a string where it can be split into an array easily.
function generateAutocompleteArray($namesArray){
$jsNamesArray = "";
$teamCount = count($namesArray);
for($i=0; $i<$teamCount; $i++){
$jsNamesArray.= $namesArray[$i].',';
}
//Removes the remaining comma so you don't get a blank autocomplete option.
$jsNamesArray = substr($jsNamesArray, 0, -1);
return $jsNamesArray;
}
?>
I don't think you should bind your autocomplete constructor to the keyup event of the input text. If so, you are recreating the object every time the user types something. Also, you are returning the namesList and maybe it is still loading from the ajax request. You have to wait for the request to complete in order to have the namesList, remember that javascript is asynchronous.
So basically, you have to construct the autocomplte just once, and look for the autocomplete parameters (source) to specify that your data is loaded via ajax. Take a look at this: jQuery autocomplete with callback ajax json

SESSION variable with json array

i have an xml file in my server that i want to extract a list of IDs with php then convert the array to a JSON using json_encode() and put it in a $_SESSION variable, to make this clear my ideal JS function is:
function getIDs() {
var x = <?php if(isset($_SESSION['IDs'])) echo $_SESSION['IDs']; ?>;
if(x == '') {
$.post('getPL.php','PL_name=cool&q=IDs',function(responseText){
x = responseText;
});
}
//some other code
//return array; // this is an array i use later in js
}
in my getPL.php i have:
$videos_list = $theOne->parentNode->parentNode->getElementsByTagName('video');
for ($i = 0; $i < $videos_list->length; $i++) {
$a = $videos_list->item($i);
$id_out = $a->getElementsByTagName('id')->item(0)->nodeValue;
$array[$i] = $id_out;
}
$IDs = json_encode($array);
$_SESSION['IDs'] = $IDs;
echo $IDs;
break;
if i alert var x = <?php if(isset($_SESSION['IDs'])) echo $_SESSION['IDs']; ?>; i get g8M8kxuaCWk,VWrBFt46J18
but when i alert the responseText i get ["g8M8kxuaCWk","VWrBFt46J18"]
all i want is to extract the IDs from the xml file and put them in a js array object
if there is anything need more tell me
i think you need the put quotes arround the php code in your JS like:
var x = '<?php if(isset($_SESSION['IDs'])) echo $_SESSION['IDs']; ?>';
ok i fixed it
so var x = '<?php if(isset($_SESSION['IDs'])) echo $_SESSION['IDs']; ?>'; would give me an array, which is what i actually want
but the alert(resposeText); was actually giving me a string so i did this JSON.parse(responseText);
thanks to who helped me get to this answer
after this in both cases if i alert(obj[0]); i get the first element so it is working
my ideal JS function becomes:
function getIDs() {
var x = <?php if(isset($_SESSION['IDs'])) echo $_SESSION['IDs']; ?>;
if(x == '') {
$.post('getPL.php','PL_name=cool&q=IDs',function(responseText){
x = JSON.parse(responseText); // this is the difference
});
}
return x;
}

can't set variable in JavaScript based on json id from php

I have a simple array from a php file (the reason for not using a json file is cause this info comes from a mysql database)
$array[0] = array('id' => 1,'price' => '325');
$array[1] = array('id' => 2,'price' => '486');
header('Content-type: application/json');
echo json_encode($array);
and it echos as:
[{"id":1,"price":"325"},{"id":2,"price":"486"}]
now what I want to do is take the id and add it to a variable called counterval so that JavaScript will read it as
counterval1 = 325;
counterval2 = 486;
but I can't seem to get it to read that way. Here is the script at the current moment.
$.getJSON('test.php',function(data) {
$.each(data, function(i) {
counterval + data[i].id = data[i].price;
console.log (counterval2);
});
$('#results').html(counterval2);
});
var counterval1 = 0;
var counterval2 = 0;
any help on this would be greatly appreciated.
you can't do that... but you can do this...
var counterval = [];
$.getJSON('test.php',function(data) {
$.each(data, function(i) {
counterval[data[i].id] = data[i].price;
console.log (counterval[2]);
});
$('#results').html(counterval[2]);
});
counterval[1] = 0;
counterval[2] = 0;
See my comment on your post. If you really want the vars to look like you explained:
eval("counterval" + data[i].id + " = data[i]..price");
alert(counterval1);

Pass an array from PHP (from DB) to JS?

My goal is to get - finally - a 'normal' JS array in my js-file. Maybe json is the way to do it - but the elements in the array should remain in order and its just an array of three arrays: [["1","2","3"]["1","2","3"]["1","2","3"]].
my php-query (it does produce the array above - I mean: it does work):
// this is file 'dbquery.php'
<?php
include_once('../resources/init.php');
$query = mysql_query("SELECT `useranswer`, `solution`, `time` FROM `results`");
$qlen = mysql_query("SELECT COUNT(1) FROM `results`");
$len = mysql_result($qlen, 0);
$user_a = array();
$solu_a = array();
$time_a = array();
while($row = mysql_fetch_assoc($query)){
array_push($user_a, $row['useranswer']);
array_push($solu_a, $row['solution']);
array_push($time_a, $row['time']);
}
$cd_result = array($user_a, $solu_a, $time_a);
$cd_answer = json_encode($cd_result);
echo $cd_answer;
?>
I assume json is not the adequat form here.
Now all I want is an js-array in my js-file like : my_array = [[1,2,3],[1,2,3],[1,2,3]]
But I terribly fail to achieve this.
With $.ajax() I don't know how to get ALL the data at once without 'data: ' each single value. I just want to "catch" my echo from the php - how to do so?
do like this
<?php
include_once('../resources/init.php');
$query = mysql_query("SELECT `useranswer`, `solution`, `time` FROM `results`");
$qlen = mysql_query("SELECT COUNT(1) FROM `results`");
$len = mysql_result($qlen, 0);
$user_a = array();
$solu_a = array();
$time_a = array();
while($row = mysql_fetch_assoc($query)){
array_push($user_a, $row['useranswer']);
array_push($solu_a, $row['solution']);
array_push($time_a, $row['time']);
}
$cd_result = array($user_a, $solu_a, $time_a);
$cd_answer = json_encode($cd_result);
echo json_encode ($cd_answer); // encode in json format
?>
and in ajax:
$.ajax({
type: "GET",
url: "test.php",
dataType: "json",
data : {anything : 1},
success:function(data){
var x = jQuery.parseJSON( data ); // parse the answer
// if you want in an array format then just use eval()
x = eval(x);
alert(x);
}
});
If you just need a PHP variable passed to JS when the page is rendered, then do this in your PHP view layer:
<script type="text/javascript">
var myInt = <?php echo $int ?>;
var myString = '<?php echo $string ?>';
var myArray = <?php echo json_encode($array) ?>;
// All these JS variables can now be used here
</script>
Obviously, you need to ensure that the variables are valid - so in the case of the int, if it is null or undefined, you need to ensure you don't render the assignment - otherwise it will produce a client-side error.

Categories