Convert PHP objects array to javascript array - javascript

I retrieve image paths with the function get_all();. This get_all function retrieves images as an object. This object has the attributes name, source_path and date. I want my javascript to add images to a div. I have the following:
The instantiate.php includes files like Jquery and another JS file.
<?php
require_once("../../include/instantiate.php");
$photos = Photos::get_all();
$JSPhotos;
foreach($photos as $photo) { $JSPhotos + $photo->source_path; }
?>
<script type="text/javascript">
$(document).ready(function() {
var photos = <?php echo json_encode($JSPhotos); ?>;
for(var i = 0; i <= 10; i++)
{
create_image("../"+photos[i]);
}
});
This does not work. Anyone got a solution?
Solution in Jeroen's Post!
New Problem;
In the create_image function I set the class and src of the image element. When you click such an image I want an alert box to show up. I have checked if the class is set correctly, and I concluded that all images did have the classname "imgid". So, any idea why this dont work?
Script in the javascript part:
$(".imgid").click(function() {
alert("hey");
});

You are not assigning anything to your variable.
You probably want:
$JSPhotos = array();
foreach($photos as $photo) {
$JSPhotos[] = $photo->source_path;
}
Or something similar.

Related

Want to Click on a Website Button Programatically

I want to Click on a Website button that are already going on.
For example:
like url: www.google.com..
I want to Click Google Search button programmatically by using any method in PHP, Javascript, Jquery and Ajax.
if Anyone know Solution. Please tell my and provide the source code.
Note: We dn't need to create own button we want to click on a website button by using class and id.
I want to try this..look like this but not success..I want to click Learn HTML button that are show on iframe...in w3school website..
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<iframe src="http://www.w3schools.com" width="800" height="400"></iframe>
<script>
//setInterval(function () {$("#hand_1151079882").click();}, 3000);
function clime(){
setInterval(function () {document.getElementById("#w3-btn").click();}, 3000);
alert();
}
//using javascript
$(document).ready(function () {
$(".cli").on('click', function(event){
$("#w3-btn").trigger('click');
});
});
</script>
<input type="button" class="cli" name="clime" value="submit" onclick="clime()">
you need set id for iframe
var iframe = document.getElementById('w3schools-home');
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
innerDoc.getElementsByClassName('w3-btn')[0].click();
[0] is for button Learn HTML, there 19 element have class w3-btn
Tested and Work on w3schools Try it Yourself »
IMPORTANT: Make sure that the iframe is on the same domain, otherwise you can't get access to its internals. That would be cross-site scripting.
as Requested, here example PHP for get Element and Recreated to your own sites.
<?php
$url='http://www.w3schools.com/css/default.asp'; // or use $_GET['url']
$scheme=parse_url($url)['scheme'];
$host=parse_url($url)['host'];
$domain=$scheme.'://'.$host;
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_HEADER, 0);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_TIMEOUT,30);
curl_setopt($ch,CURLOPT_POST, 0);
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML(substr(curl_exec($ch), curl_getinfo($ch, CURLINFO_HEADER_SIZE)));
$xpath = new DOMXpath($dom);
$aElement = $xpath->query('//a');
$length = $aElement->length;
$links=array();
for ($i = 0; $i < $length; $i++) {
$element = $aElement->item($i);
if ($element->tagName=='a' && trim($element->textContent)<>'') {
foreach ($element->attributes as $attr) {
$attrName = $attr->nodeName;
$attrVal = $attr->nodeValue;
if($attrName=='href' && str_replace(';','',$attrVal)<>'javascript:void(0)'){
if(substr($attrVal, 0, 1)=='/'){
$links[trim($element->textContent)]=$domain.$attrVal;
}else if(substr($attrVal, 0, 4)=='http'){
$links[trim($element->textContent)]=$attrVal;
}
}
}
}
}
foreach ($links as $key=>$value) {
echo ''.$key.' | ';
}
You can create a javascript function to get URL from iframe and than request AJAX to PHP that have script ABOVE, you can use echo(but need foreach as example from my script) or json_encode to array $links, then reCREATED button from other url/website to your sites.
or just echo to your sites.
My script still need improvement to handle value of attribut href that use '../' or 'foldername/'
just reminder, for get access ELEMENTS on iframe that pointing to different domain is impossible.
You seem to be missing the element with the id w3-btn which gets clicked programmatically.
Also, it seems both of these are doing the same thing ...
function clime(){
setInterval(function () {document.getElementById("#w3-btn").click();}, 3000);
alert();
}
and
$(document).ready(function () {
$(".cli").on('click', function(event){
$("#w3-btn").trigger('click');
});
});
both are trying to click an element with id w3-btn, just in different ways. You only need one of them.
This might help:
<script>
jQuery(function(){
jQuery('#modal').click();
});
</script>
I got this answer from here.

How to use explode function to delimit and display different values

I’m making a random sentence generator for my English class. I’m close but because of my limited php and javascript knowledge I need to ask for help. I’m not bad at reading the code, I just get stuck writing it.
I want to use explode to break up a string of comma seperated values. The string is a mix of English and Spanish, on the .txt file they would seperated like:
The book, El libro
The man, El hombre
The woman, La mujer
etc.
I would like to break these two values into an array and display them in separate places on my web page.
I`m going to use a random text generator script that I found, it’s working great with no problems. I just need to modify it using explode to read, separate the values into an array, and be able to display the separate values of the array.
<?php
/* File, where the random text/quotes are stored one per line */
$settings['text_from_file'] = 'quotes.txt';
/*
How to display the text?
0 = raw mode: print the text as it is, when using RanTex as an include
1 = Javascript mode: when using Javascript to display the quote
*/
$settings['display_type'] = 1;
/* Allow on-the-fly settings override? 0 = NO, 1 = YES */
$settings['allow_otf'] = 1;
// Override type?
if ($settings['allow_otf'] && isset($_GET['type']))
{
$type = intval($_GET['type']);
}
else
{
$type = $settings['display_type'];
}
// Get a list of all text options
if ($settings['text_from_file'])
{
$settings['quotes'] = file($settings['text_from_file']);
}
// If we have any text choose a random one, otherwise show 'No text to choose from'
if (count($settings['quotes']))
{
$txt = $settings['quotes'][array_rand($settings['quotes'])];
}
else
{
$txt = 'No text to choose from';
}
// Output the image according to the selected type
if ($type)
{
// New lines will break Javascript, remove any and replace them with <br />
$txt = nl2br(trim($txt));
$txt = str_replace(array("\n","\r"),'',$txt);
// Set the correct MIME type
header("Content-type: text/javascript");
// Print the Javascript code
echo 'document.write(\''.addslashes($txt).'\')';
}
else
{
echo $txt;
}
?>
The script that displays the result:
<script type="text/javascript" src="rantex.php?type=1"></script>
Can someone please help me modify the rantex.php file so that I can use explode to separate the different comma separated values, and use a different script to call them in different places on my web page?
Thank you, and please excuse my noobness.
The following seems unnecessary, since file() will have already removed new line characters:
// New lines will break Javascript, remove any and replace them with <br />
$txt = nl2br(trim($txt));
$txt = str_replace(array("\n","\r"),'',$txt);
To break your line, you may instead use:
list($english, $spanish) = explode(', ', trim($txt));
It seems you are trying to use PHP to serve a static page with some random sentences, right? So why not use PHP to serve valid JSON, and handle to display logic on the client?
Heres a quick implementation.
// Get the data from the text file
$source = file_get_contents('./quotes.txt', true);
// Build an array (break on every line break)
$sentences = explode("\n", $source);
// Filter out empty values (if there is any)
$filtered = array_filter($sentences, function($item) {
return $item !== "";
});
// Build a hashmap of the array
$pairs = array_map(function($item) {
return ['sentence' => $item];
}, $filtered);
// Encode the hashmap to JSON, and return this to the client.
$json = json_encode($pairs);
Now you can let the client handle the rest, with some basic JavaScript.
// Return a random sentence from your list.
var random = sentences[Math.floor(Math.random() * sentences.length)];
// Finally display it
random.sentence
[edit]
You can get the JSON data to client in many ways, but if you don't want to use something like Ajax, you could simply just dump the contents on your webpage, then use JavaScript to update the random sentence, from the global window object.
// Inside your php page
<p>English: <span id="english"></span></p>
<p>Spanish: <span id="spanish"></span></p>
<script>
var sentences = <?= json_encode($pairs); ?>;
var random = sentences[Math.floor(Math.random() * sentences.length)];
var elspa = document.getElementById('spanish');
var eleng = document.getElementById('english');
elspa.innerText = random.sentence.split(',')[1];
eleng.innerText = random.sentence.split(',')[0];
</script>
Ok, so I have this figured out, I take 0 credit because I paid someone to do it. Special thanks to #stormpat for sending me in the right direction, if not for him I wouldn't have looked at this from a JSON point of view.
The .PHP file is like so:
<?php
$f_contents = file('quotes.txt');
$line = trim($f_contents[rand(0, count($f_contents) - 1)]);
$data = explode(',', $line);
$data['eng'] = $data[0];
$data['esp'] = $data[1];
echo json_encode($data);
?>
On the .HTML page in the header:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
(function ($) {
$(function()
{
function load_random_data() {
$.get('random_line.php', function(data) {
var data = $.parseJSON(data);
$('#random_english').text(data.eng);
$('#random_spanish').text(data.esp);
});
}
load_random_data();
$('#get_random').click(function(e){
e.preventDefault();
load_random_data();
});
});
})(jQuery);
</script>
This splits the different variables into classes, so to call them into my html page I call them by their class, for instance I wanted to drop the variable into a table cell so I gave the individual td cell a class:
<td id="random_spanish"></td>
<td id="random_english"></td>
Plus as a bonus the coder threw in a nifty button to refresh the json classes:
<input type="button" value="Get random" id="get_random" />
So now I don`t have to have my students refresh the whole web page, they can just hit the button and refresh the random variables.
Thanks again everyone!

populate dropdown onload by passing php array to javascript function

im trying to pass a php array to javascript function onload that will display the js array in a drop down list but now im already doing it for sometime i guess i need to pop it again
first i pass it from one php file to another using this code
header("location: Rules.php?varFields=".serialize($varFields));
secondly i transfer to another variable as it had been passed to the said php file
<?php
$varArray = unserialize($_GET['varFields']);
?>
third part is im tyring to pass it into a jS functon that will then display it to a drop down list
<body id="body" onclick="cmbRuleField(\'' + <?php echo json_encode($varArray);?> + '\');" >
and here is the external javascript code
function cmbRuleField(varArray)//ruleField
{
var varDisplay = JSON.stringify(varArray);
var sel = document.getElementById("ruleField") // find the drop down
for (var i in varDisplay)
{ // loop through all elements
var opt = document.createElement("option"); // Create the new element
opt.value = varDisplay [i]; // set the value
opt.text = varDisplay [i]; // set the text
sel.appendChild(opt); // add it to the select
}
}
for the first two part i already tested it and it is working but for the last parts i cant make it work
I think this part looks suspicious
<body id="body" onclick="cmbRuleField(\'' + <?php echo json_encode($varArray);?> + '\');" >
maybe
<body id="body" onclick="cmbRuleField(<?php echo json_encode($varArray);?>)">
is more like it.
One more tip, you can see the output on the rendered page to determine what the written out code looks like. So if you see something like:
<body id="body" onclick="cmbRuleField('['a', 'b']')">
you know there is a problem. You want a native Javascript array to be passed like this
<body id="body" onclick="cmbRuleField(['a', 'b'])">
EDIT
After talking on chat it became clear the top portion of OP's code needed a tweak as well.
header("location: Rules.php?varFields=".http_build_query($varFields));
The problem has to do with quotes not being terminated here:
...
<body id="body" onclick="cmbRuleField(\'' + <?php echo json_encode($varArray);?> + '\');" >
...
The JSON created using json_encode will have a lot of double quotes. Try this:
<script>
var array = <?php echo json_encode($varArray);?>;
</script>
<body id="body" onclick="cmbRuleField(array);">
There is a much easier way. Encode the $varArray as direct HTML options before sending to the browser. For instance:
<select id="ruleField">
<?php for ($i = 0; $i < count($varArray); $i++) { ?>
<option value="<?php= $varArray[$i].val ?>"><?php= $varArray[$i].name ?></option>
<?php } ?>
</select>
Might be because you are calling JSON.stringify on something that is already a string?
Also what is myCars?
..
for (var i in myCars)
..
Possibly rename it to varArray.
or rename varDisplay to varArray.
and lastly try calling JSON.parse instead:
function cmbRuleField(varArray)//ruleField
{
var varDisplay = JSON.parse(varArray);
var sel = document.getElementById("ruleField") // find the drop down
for (var i in myCars)
{ // loop through all elements
var opt = document.createElement("option"); // Create the new element
opt.value = varDisplay [i]; // set the value
opt.text = varDisplay [i]; // set the text
sel.appendChild(opt); // add it to the select
}
}
If that didn't work post the html output here so peeps can create a fiddle :)

jQuery $.post() using output data as selector

I am trying to build a quiz environment. The user selects an answer and then clicks submit. Upon submit, the following jquery is called:
$(document).ready(function() {
$('.btn-large').click(function() {
$.post("correct_quiz.php",
{
choices : $('input[name=choice][type=radio]:checked').serialize()
},
function(data) {
var temp = '#correct' + data;
var temp2 = '#correct3';
$(temp).show(); // Make the wrong/right icons visible
});
});
});
This jquery makes a green or red icon appear, based on whether the answer was correct or not. The correct_quiz.php script contains:
<?php
$root = "/users/stadius/maapc/public_html/";
include($root . "connect_to_database.php");
$choices = $_POST['choices']; // This will for example output "choice=3"
echo substr($choices,7,7); // This will then output "3"
?>
I ran into a problem, when I try the above jquery code with variable temp2 the script works like I want. But when I try it with variable temp it doesn't. When I debug, I see that they contain exactly the same string though: both are '#correct3' (when I choose the 3rd answer).
So why is this not working when I use variable temp, and is working when using temp2?
I think your problem is in this line:
echo substr($choices,7,7);
Try to use:
$list = explode('=', $choices);
echo $list[1];
instead of substr

Drupal 6 javascript in module block for front page

I'm trying to create a simple image slider on the front page of my drupal website. I wrote a module with the basic outline as follows
<?php
function slider_init(){
drupal_add_js(drupal_get_path('module', 'slider') .'/slider.js');
}
function slider_block($op = 'list', $delta = 0, $edit = array()) {
$block = array();
switch ($op) {
case "list":
// Generate listing of blocks from this module, for the admin/block page
$block[0]["info"] = t("slider");
break;
case "view":
// Generate content for blocks from this module
$block_content = "";
$block_content .= "hello";
//Query for the projects
$icons = db_query("SELECT * FROM {alumni_frontpage_projects}");
//Initiation arrays from each table column: title, description, url, icon link
$links = array();
$title = array();
$description = array();
$url = array();
//Generate arrays from each table column: title, description, url, icon link
while($icon_data = db_fetch_array($icons)){
$links[] = $icon_data['slider_image_location'];
$title[] = $icon_data['title'];
$description[]= $icon_data['description'];
$url[] = $icon_data['url'];
}
//Count elements in array and randomly choose one
$res = count($links)-1;
$seed = rand(0,$res);
//Generate HTML and Javascript of Slider
//Check that content isn't empty
if ($block_content == "") {
$block_content = t("Sorry No Content");
}
$block["content"] = $block_content;
break;
case "save":
break;
case "configure":
break;
}
return $block;
}
Now, everything is fine. I generate a block and I can place it wherever I want. Great. But I would really like to use javascript in this block so that I can pass the arrays and use onclick events to slide through some images from the arrays i queried. So I found out that I will have to pass the variables into javascript and I'll have to identify the javascript file i want to use in the module.
//add variable to the Javascript
drupal_add_js(array('slider_settings' => array('variable_name' => $variable_name)), 'setting');
//add Javascript file to module
drupal_add_js(drupal_get_path('module', 'slider') .'/slider.js');<br>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
I put these in the hook_init BUT NOTHING HAPPENS!!!!! I tested to see basic alerts. If I put hard code into the _block, such as:
$block_content .= '
<script type="text/javascript">
var x
x = 50;
document.write(x); //prints the value of x
</script>';
Then I see '50' prints.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If I try to pass a variable to the hard coded script. That DOES NOT WORK either.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If I try to write 50 through the previous code, but from a separate file called slider.js which is in the same folder using "drupal_add_js(drupal_get_path('module', 'slider') .'/slider.js');", That DOES NOT WORK either (even though I'm not passing a variable)
So what the heck is going on!! Is it possible I'm missing some important core drupal files? Is there a way to trouble shoot this further?
Thanks!
drupal_add_js should work in hook_init().First Check whether your hook function is correctly named as ModuleName_init() or not.

Categories