I have a foreach loop that creates a string in php , I'm unable to pass the string value to mootools in wordpress (I'm integrating a MooTool function ) :::
I need to substitute the "hard coded" image URL's in the new Array() (below) with a variable created from my php string eg. new Array( $myimageurl ) :::
I've created a var from the php string even tried json_encode , with no luck :::
window.addEvent("domready", function(){
var counter = 0;
var images = new Array('http://localhost/square/wp-content/uploads/2011/10/test-foo/foo.jpg','http://localhost/square/wp-content/uploads/2011/10/test-foo/foo1.jpg');
er, why not just:
var foo= <?=json_encode(Array("foo.jpg", "bar.jpg"))?>;
EDIT
Since you implied in a comment your files source is comma separated, then do this instead:
<? $files = "foo.jpg,bar.jpg"; ?>
var foo = <?=json_encode(explode(',', $files))?>;
where the array could be anything of any length, read from wherever. it will result in an array literal looking like so:
var foo = ["foo.jpg","bar.jpg"];
// eg use.
foo.each(function(img) {
new Element("img", {src: img}).inject(document.body);
));
nb: just noticed #Marc B has already mentioned json_encode. sorry, will delete
try:
var images = new Array('<?php echo $miImageUrl[0];?>', '<?php echo $miImageUrl[1];?>');
Other way:
<?php
//sample data
$descargables[0] = 'cero';
$descargables[1] = 'uno';
$descargables[2] = 'dos';
$descargables[3] = 'tres';
// end sample data
$arrayToJs="var descargables = new Array();";
for ($i=0; $i < count($descargables); $i++) {
$arrayToJs .= "descargables[" . $i . "]='" . $descargables[$i]. "';";
}
?>
<script>
<?php echo $arrayToJs;?>
idx = 3;
alert("descargable:" + descargables[idx]);
</script>
Related
Edit:
I can output the table now but the strange thing is, trying to parse the JSON returned from PHP using JS or jQuery methods results in skipping all remaining lines in the debugger with zero output to the browser. Where as not parsing and using it to construct at table works.
Also, trying to .append() the JSON using the parse methods or not to a ` does not work.
I'm so confused right now.
Anyways, the jQuery that worked looks like this making a .post() request, notice I added the 'json' fourth parameter although it might work without it.
$(document).ready(function(){
$('#disease_btn').click(function(){
showDisease();
});
});
function showDisease(){
//var disease = $("#disease-dropdown:selected").text();
//var disease = $("#disease-dropdown:selected").val();
var disease_dropdown = document.getElementById("disease-dropdown")
var disease = disease_dropdown.options[disease_dropdown.selectedIndex].text;
var controller = 'controller.php';
$.post(controller, //url, data, callback, dataype=Json
{
page: 'SpaPage',
command: 'search-disease',
search_term: disease
},
function(disease_json, status){
//#search-results display table
//var disease_obj = JSON.parse(disease_json); this did not work
//var disease_obj = jQuery.parseJSON(disease_json); //this did not work
var disease_obj = disease_json;
//$('#test-out').append(disease_obj); /this did not work
var table = $.makeTable(disease_obj);
$('#search-results').append(table); //this worked!
}, 'json');
//https://stackoverflow.com/a/27814032/13865853
$.makeTable = function(disease_obj){
var table = $('<table border=1>');
var tblHeader = "<tr>";
for (var h in disease_obj[0]) tblHeader += "<th>" + h + "</th>";
$(tblHeader).appendTo(table);
$.each(disease_obj, function(index, value){
var tblRows = "<tr>";
$.each(value, function (key, val){
tblRows += "<td>" + val + "</td>";
});
tblRows += "</tr>";
$(table).append(tblRows);
});
return ($(table));
}
};
That table code I mimicked what I saw here: https://stackoverflow.com/a/27814032/13865853
I sort of get it but still not crystal clear on all of it. I guess it's outputting HTML so I can throw in a class for the table to take advantage of bootstrap.
On the PHP side I do this:
case 'search-disease':
$matches_arr = [];
$disease = $_POST['search_term'];
$matches_arr = search_disease($disease);
//todo: decide to use session or returned arr
if(isset($_SESSION['disease-matches_arr'])){
$matches_arr = $_SESSION['disease-matches_arr'];
}
if(count($matches_arr) > 0) {
//jsonify array here to send back
//https://stackoverflow.com/a/7064478/13865853
//https://stackoverflow.com/a/58133952/13865853
header('Content-Type: application/json');
$disease_json = json_encode($matches_arr);
echo $disease_json;
exit;
}
and then the model.php interaction with database looks like this:
function search_disease($disease_option){
// search DB for substring of question
//add results to an array of strings
//return array of strings or empty array
//
$user_id = -1;
$matches_arr = array();
$sql = "SELECT * FROM diseases
WHERE disease LIKE '%$disease_option%'";
$result = mysqli_query(Db::$conn, $sql);
if (mysqli_num_rows($result) > 0) {
//iterate
while($row = mysqli_fetch_assoc($result)){
//get username
$disease = $row['disease'];
$food = $row['food'];
$en_name = $row['en_name'];
$health_effect = $row['healthEffect'];
$metabollite = $row['metabollite'];
$citation = $row['citation'];
$next_row = array("Disease"=>$disease, "Food"=>$food,
"Name"=>$en_name, "Health Benefits"=>$health_effect, "Metabollite"=>$metabollite,
"Sources"=>$citation);
$matches_arr[] = $next_row;
}
}
$_SESSION['disease-matches_arr'] = $matches_arr;
return $matches_arr;
//https://stackoverflow.com/questions/1548159/php-how-to-sen
So I set a session variable and also return it, still have to decide which way but they are both working.
My questions still remaining are:
Why do the parse methods cause this strange behavior?
How can I just output the JSON to a testing <div>?
If you have to return data from PHP to javascript you must have use json_encode() if data type is array otherwise just return.
To take action with array type data by javascript you have to decode this json data by JSON.parse() function.
Array example
$data = array('carname' => 'TOYOTA','model'=>'ARTYIR500');
echo json_encode($data);
exit;
String example
echo 'lorem ipsum is a simple text';
exit;
I'm new to Parse and I'm not a very well-experienced PHP developer.
I'm trying to run a search query using Parse.com PHP SDK on _User class.
Here is my code:
<?php $query = new ParseQuery('_User');
$query->startsWith("s_first_name", $user);
$results = $query->find();
foreach ($results as $result) { ?>
<?php echo $result->get('s_first_name')." ".$result->get('s_last_name'); ?>
<?php } ?>
It works but it's case sensitive. Also I don't think the "startsWith" is the best function to use since I needed something similar to "contains" in MYSQL.
Any help will be much appreciated.
I wasn't able to fix this using PHP so I used their Javascript SDK instead with toUpperCase() and toLowerCase() functions.
function capitalize(str) {
var pieces = str.split(" ");
for ( var i = 0; i < pieces.length; i++ ) {
var j = pieces[i].charAt(0).toUpperCase();
pieces[i] = j + pieces[i].substr(1);
}
return pieces.join(" ");
}
//get search term from php
var searhTerm = <?php echo json_encode($user); ?>;
//capitalize keyword for accurate results
var keyword = ".*"+capitalize(searhTerm);+".*";
//start search
var searchUser = Parse.Object.extend("_User");
//queries
var query1 = new Parse.Query(searchUser);
query1.matches("s_first_name", keyword.toLowerCase());
query1.equalTo("type", "seaman");
.
.
.
//do query find
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;
}
I have a array stored in a PHP file in which I am storing all the values.
I am trying to loop through the entire array in JavaScript. How should I do that?
The following does not work:
var index = 0;
var info = 1;
while(index<4) {
info = <?php echo $a[?>index<?php];?>
index++;
}
You can copy array from php to JavaScript and then process it.
var array = <?php echo json_encode($a); ?>
var index = 0;
var info = 1;
while(index<4) {
info = array[index];
index++;
}
I don't know what version of php you're using, but try something like this:
var info = null;
var a = <?php echo json_encode($a); ?>;
for(var index=0;index<a.length;index++) {
info = a[index];
}
You need to process the PHP into Javascript first. You can use json_encode to do this.
var index = 0;
var info = 1;
var a = <?php echo json_encode($a); ?>;
while(index < 4) {
info = a[index];
index++;
}
PHP runs on the server side, before the final page is served to the client.
Javascript runs on the client side (on the browser).
Therefore, what you are trying to achieve won't work. What you can do is use PHP to print the javascript code dynamically.
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>