How can I call a function when page loads with jQuery? - javascript

I want to trigger a JavaScript function after the page loads all the elements and I have to echo some HTTP request data into the page somewhere and use JavaScript to get the information from the DOM.
Therefore, I create the function and fire it on page load using jQuery but it didn't call the javascript (I think the DOM hasn't loaded) so how can I fix this?
<script>
$( document ).ready(function(){
myFunction(); // firing the function
});
</script>
<script>
function myFunction(){
var target = document.getElementById("target");
var formscount = target.textContent(); // the number of items from [#target]
alert(target);
if (formscount > 0) {
active="";
for (i=0; i < formscount; i++) {
var str='active'
if (i > 0){
str = ''
}
$('#DOM').append($('SOME HTML ELEMENTS');
event.preventDefault()
}
}
}
</script>
DOM Called (target) for passing the data ($_POST['itemscount']):
<?
$count = $_POST['itemscount'];
?>
<div id="target" style="display:none;">
<? $output = $_POST['productscount']; // or $Count //
echo htmlspecialchars($output);
?>
</div>

First, textContent is not a function.
So it should be written like this:
var formscount = target.textContent;
Second thing, you are missing the closing bracket ) in line $('#DOM').append($('SOME HTML ELEMENTS');
$('#DOM').append($('SOME HTML ELEMENTS'));
Third thing, event.preventDefault() will not work, as event is undefined. You may remove it.
and lastly, php tags begins with <?php and not with only <?.
<?php
$count = $_POST['itemscount'];
?>
<div id="target" style="display:none;">
<?php
$output = $_POST['productscount']; // or $Count //
echo htmlspecialchars($output);
?>
</div>

Related

Populate DIV with an PHP arrayelement based on a click on a link

What I want:
A list of links show events - a click on such a link shall show further details in a special DIV on the same page.
Idea:
I read from the database all events:
$queryEventString = 'Match (e:Event) WHERE e.eventStatus = "not_processed"
RETURN e.UUID as eventUUID,
e.eventFrom as eventFrom,
e.eventType as eventType,
e.eventTime as eventTime,
e.eventSubject as eventSubject,
e.eventBody as eventBody';
$resultEvent = $client->run($queryEventString);
This gives me all available events in the DB that are not yet processed.
I assgin all found events identified by their UUID into a PHP array for further processing
foreach ($resultEvent as $eventDetail)
{
$eventInfo[$eventDetail['eventUUID']]['eventBody'] = html_entity_decode($eventDetail['eventBody']);
$eventInfo[$eventDetail['eventUUID']]['eventForm'] = $eventDetail['eventFrom'];
$eventInfo[$eventDetail['eventUUID']]['eventDate'] = date("d.m.Y H:i",
$eventDetail['eventTime']);
$eventInfo[$eventDetail['eventUUID']]['eventSubject'] = $eventDetail['eventSubject'];
}
Having that 2-dimensional array "eventInfo" I build the list
echo '<div class="event-panel">';
echo '<ul id="event-column" style="list-style: none;">';
foreach($eventInfo AS $eventKey => $eventDetail)
{
echo '<eventlink data-id="'.$eventKey.'">'.$eventKey.'</eventlink><br>';
}
echo '</ul>';
echo '</div>';
Last but not least I create a DIV to store the desired eventBody-Information:
echo <<<EOT
<div id="info-div">
<div id="info"></div>
</div>
EOT;
To populate now the DIV when a link is clicked I tried this:
$(document).ready(function (){
var passedArray = <?php echo json_encode($eventInfo); ?>;
$('#event-column eventlink').click(function (){
var p = $(this).attr('data-id');
$('#info').html().passedArray[p];
});
});
I wanted to pass the php-Array with JSON to make it available inside the function.
With the click-effect I wanted to load from this php-array the related array-element ['eventBody'] with the UUID given by the link-click.
Somehow I am stuck. I am able to pass the UUDI key to the javascript area and can write it into the DIV but I cannot identify a php-element by the given UUID and put the content into the DIV.
Any hint is appreciated, thank you.
As requested here is the code in total:
<?php
// Including jQuery
echo '<script src="http://code.jquery.com/jquery-1.11.3.min.js">/script>';
// Querying the Neo4J DB
$queryEventString = 'Match (e:Event) WHERE e.eventStatus = "not_processed"
RETURN e.UUID as eventUUID,
e.eventFrom as eventFrom,
e.eventType as eventType,
e.eventTime as eventTime,
e.eventSubject as eventSubject,
e.eventBody as eventBody';
$resultEvent = $client->run($queryEventString);
// Parsing result and build the 2-dimensional array $eventInfo
foreach ($resultEvent as $eventDetail)
{
$eventInfo[$eventDetail['eventUUID']]['eventBody'] = html_entity_decode($eventDetail['eventBody']);
$eventInfo[$eventDetail['eventUUID']]['eventForm'] = $eventDetail['eventFrom'];
$eventInfo[$eventDetail['eventUUID']]['eventDate'] = date("d.m.Y H:i", $eventDetail['eventTime']);
$eventInfo[$eventDetail['eventUUID']]['eventSubject'] = $eventDetail['eventSubject'];
}
// Displaying list of events with UUID as forwarded parameter (-> JS)
echo '<div class="event-panel">';
echo '<ul id="event-column" style="list-style: none;">';
foreach($eventInfo AS $eventKey => $eventDetail)
{
echo '<eventlink data-id="'.$eventKey.'">'.$eventKey.'</eventlink><br>';
}
echo '</ul>';
echo '</div>';
// Creating a DIV Container to hold $eventInfo[eventUUID][eventBody]
echo <<<EOT
<div id="info-div">
<div id="info"></div>
</div>
EOT;
// JavaScript Part
echo <<<EOT
<script type="text/javascript">
$(document).ready(function (){
var passedArray = <?php echo json_encode($eventInfo); ?>;
console.log(passedArray);
$('#event-column eventlink').click(function (){
var p = $(this).attr('data-id');
$('#info').html().passedArray[p];
});
});
</script>
EOT;
?>
2nd EDIT:
I have stripped down everything to this functioncode, which is at the end of the php-file and no longer wrapped in the php-tags. So its like standard html. This way I avoid the uncaught syntax error.
<script type='text/javascript'>
$(document).ready(function (){
var passedArray = '<?php echo json_encode(array($test_array)); ?>';
console.log(passedArray);
$('#event-column eventlink').click(function (){
var p = $(this).attr('data-id');
console.log(p);
console.log(passedArray[p]['eventBody']);
$('#info').text(passedArray[p]);
});
});
</script>
Outcome:
I can console.log the array, which shows as a test:
[[{"UUID":"60762d3eb9949596701a2dfb700cd2c9","eventBody":"Hallo"},{"UUID":"620c16ced5097bf60f718abca7d979f8","eventBody":"Ciao"}]]
I see also that when I click a link that the UUID key is passed to the Javascript-Script:
60762d3eb9949596701a2dfb700cd2c9
But when I want to assign the related eventBody-element I receive this error:
Uncaught TypeError: passedArray[p] is undefined
As I have the array and the key I assume it must be a syntax error in this line:
console.log(passedArray[p]['eventBody']);
So two questions left:
How would I access one element of the given array?
How can I then populate the DIV with the element ['UUID']['eventBody']? Not sure if this is the way to go: $('#info').html().passedArray[p];
Resolution (with Uwe's help):
function findme(p) {
var passedArray = '<?php echo json_encode($test_array); ?>';
passedArray = JSON.parse(passedArray);
// here we search that object in your array which has the key value pair of
// UUID : p
var result = passedArray.find((obj) => {
return obj.UUID === p;
});
document.getElementById("result").innerHTML = result.eventBody;
}
thanks to your support here (Kudos to Uwe) here is the solution:
As we use jQuery we need to include this in the head:
echo '<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.min.js"></script>';
The Javascript-Function (written in HTML, not in PHP tags):
function findme(p) {
var passedArray = '<?php echo json_encode($eventInfo); ?>';
passedArray = JSON.parse(passedArray);
// here we search that object in your array which has the key value pair of
// UUID : p
var result = passedArray.find((obj) => {
return obj.UUID === p;
});
document.getElementById("result").innerHTML = result.eventBody;
}
I was not able to find a way to write the whole code within PHP tags, as the double echo (Start and inside the array handover) and the additional PHP?-tags always generates syntax errors - thus the JS function is written as HTML-code outside the PHP code.
In the PHP the UUID of the array is passed onClick to the JS function - looks like
echo ' Find the element by UUID Brackets -- '.$UUID.'';
Please pay attention to the escaped quotation marks - important to avoid an error in JS that allows no identifiers starting with a number.
The DIV is marked by
echo '<p id="result"></p>';
For testing I made an array like this:
$eventInfo= array();
$eventInfo[] = array('UUID' => '60762d3', 'eventBody' => 'Text 1');
$eventInfo[] = array('UUID' => '620c16c', 'eventBody' => 'Text 2');
$eventInfo[] = array('UUID' => '6076299', 'eventBody' => 'Text 3');
$eventInfo[] = array('UUID' => '620c16c', 'eventBody' => 'Text 4');

JavaScript function stops working when page is fully loaded

I have a wordpress site, and one of the functions has started working.
On my agenda page here: http://staging.chinahiking.cn/agenda/
it used to be that when you clicked the tabs, the upcoming trip would change. I just realized now it has stopped working, and I'm not sure why. What's even weirder is sometimes when I do a hard refresh, and while the page is still loading and I click the tabs, its working again, but when the page is fully loaded it stops working. Here is the JS function:
<?php get_header();
$cur_month = date('n');
$month = array(1=>"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
$agenda = get_agenda_by_month();
?>
var $=function(objectId){
if(document.getElementById&&document.getElementById(objectId)){
return document.getElementById(objectId)
}
else if(document.all&&document.all(objectId)){
return document.all(objectId)
}
else if(document.layers&&document.layers[objectId]){
return document.layers[objectId];
}
else{
return false;
}
};
function tabTurn(presObj, classon, showdiv){
var pObj = presObj.parentNode;
var items = pObj.getElementsByTagName('li');
for(var i=0; i<items.length; i++){
var n = i + 1;
var cntDiv = $('location_desc_' + n);
if(items[i] == presObj){
items[i].className=classon;
cntDiv.className = showdiv;
}
else{
items[i].className='off';
cntDiv.className = 'undis';
}
}
};
And here is the html:
<div class="monthes">
<div class="month_list">
<ul class="month">
<?php for($i=1; $i<=12; $i++){
if($i!=$cur_month)
echo "<li onclick=\"tabTurn(this, 'on', 'month_desc');\" class=\"off\">$month[$i]</li>";
else
echo "<li onclick=\"tabTurn(this, 'on', 'month_desc');\" class=\"on\">$month[$i]</li>";
}?>
</ul>
</div>
</div>
<?php
for($i=1; $i<=12; $i++):
if((isset($agenda[$i]))):
?>
<div id="location_desc_<?php echo $i;?>" class="month_desc <?php if($i!=$cur_month) echo "undis";?>">
Does anyone know why this would all of a sudden stop working? And only sometimes work while the page is still loading, but then stop once it's fully loaded?
I don't think you're using jquery properly. You should be using the addClass and removeClass functions.
Opening devtools on your site, I can make the page change by running:
$('#location_desc_6').addClass("undis")
$('#location_desc_8').removeClass("undis")
As a side note, the selectors need to start with # if you are wanting to select elements by id.
If you really wanted to use className = whatever then you would need to specify that you want to run on the first item returned by the selector, like:
$('#location_desc_6')[0].className = "undis"

Can I have a php if statement inside a jquery script in Drupal 7?

I have a jquery script that loads on document ready and I want to display a hidden popup if a user has already clicked a button (button field). But the condition I check is with php code.
<script>
$( document ).ready(function() {
if (<?php $user_fields->field_button['und'][0]['value'] = 1 ?>) {
var popup = document.getElementById("testpopup1").style.visibility = "visible";
alert("x");
}
});
</script>
But this way doesn't work. Is there a way to put the php code inside the if statement of my jquery code or I have to try something else?
You don't need Javascript to do an if and all.
In your HTML
<?php if ($user_fields->field_button['und'][0]['value'] === 1) { ?>
<div id="testpopup1">Your content</div>
<script>alert('x');</script>
<?php } ?>
Save the value of the PHP value in a Javascript variable.
$(document).ready(function() {
var undValue = <?= $user_fields->field_button['und'][0]['value'] ?>;
if (undValue === 1) {
document.getElementById('testpopup1').style.visiblity = 'visible';
alert('x');
}
});

How to change a link pointing to JavaScript to run automatically?

If I have JavaScript function which is called only when I click on a link.
How can I run that JavaScript automatically?
Please note that I've tried many methods, but they are not working.
The code is:
<div align="left"><a href="javascript:show_desc(document.getElementById('d_<?php echo $item->id;?>'));" class="tablchet" ><?php echo $item->name;?></span></a></div>
In order to properly separate presentation (HTML) and behavior (JS) we will not include any JS into HTML markup. We will also not create dependencies between type of tag and JS function so our code will be
<div align="left">
<a href="" data-id="<?php echo $item->id; ?>" class="tablchet">
<span><?php echo $item->name; ?></span>
</a>
</div>
or even the following
<div align="left">
<span data-id="<?php echo $item->id; ?>" class="tablchet"><?php echo $item->name; ?></span>
</div>
For the presentation, it's ok. Now, use some JS into a separate file included after the presentation HTML with <script src="behavior.js"></script> or directly into HTML document between <script></script>.
The JS could be as following:
// Create a function allow you to manipulate the item clicked and the item targeted (with the id).
var showDesc = function (sender, target) {
// When the sender is clicked...
sender.addEventListener("click", function (e) {
e.preventDefault();
// Do Something with the target...
console.log(target);
});
};
// This part will be executed when all HTML presentation from server will be parse.
document.addEventListener("load", function () {
// Our sender is our `class="tablchet"` markup.
var sender = document.getElementsByClassName("tablchet")[0],
// create the id name with the `data-id` information.
id = "d_" + sender.getAttribute("data-id"),
// and our target is finded with its id.
target = document.getElementById(id);
// Use our showDesc with sender and target wished.
showDesc(sender, target);
});
The way you run the javascript on page is to use the script tag.
Your example would look like this:
<script type="text/javascript">
show_desc(document.getElementById('d_<?php echo $item->id;?>'));
</script>
Well,you are document.getElementById,So,one thing is clear you want to call method after complete page is load as you get the element after DOM is ready.
With JavaScript you can do like this.
window.onload = function() {
var show_desc = function(htmlEle) {
// do further processing.
}
var eleId = 'd_<?php echo $item->id;?>';
var htmlEle = document.getElementById(eleId);
show_desc(htmlEle);
}
If you are using jQuery lib then you can do like this.
$(document).ready(function() {
var show_desc = function(htmlEle) {
// do further processing.
}
var eleId = 'd_<?php echo $item->id;?>';
var htmlEle = $("#eleId");
show_desc(htmlEle);
})

Sending PHP array to Javascript

I have created an array in PHP. And I need to get that array into a javascript function. This is what I have tried.
$sql = "SELECT * FROM Questions WHERE Form_ID='$FormID' AND QuestionsDataHave='YES' ORDER BY Questions_ID+0, Questions_ID";
$GetTheValidationRule = mysqli_query($con, $sql);
$ValidatinArray = array();
$J = 0;
while($RowVal = mysqli_fetch_array($GetTheValidationRule)){
$ValidatinArray[$J] = $RowVal['Validation_Type'];
$J++;
}
And This is my javascript code.
$(document).ready(function() {
$("form").submit(function(){
var P= <?php echo json_encode($ValidatinArray); ?>;
var O = P.length;
alert(O);
return false;
});
});
But this gives me an error like this
SyntaxError: syntax error
var P= <br />
Isn't it possible to get the array in this way. Please someone help me.
UPDATE: This is the final out put of my error message
<script>
$(document).ready(function() {
$("form").submit(function(){
alert('AAAAAAAAAAAAAAAAAAA');
var IDsOfTheColumns = document.getElementsByName("DataColumnID[]");
var Data = document.getElementsByName("DataInputValue[]");
var A = IDsOfTheColumns.length;
alert(A);
<br />
<b>Notice</b>: Undefined variable: ValidatinArray in <b>C:\xampp\htdocs\PHIS\CreateTheForm.php</b> on line <b>16</b><br />
var P = null; return false;
});
});
</script>
Sorry for the late response...Try rewriting your document.ready as:
$(document).ready(function() {
$("form").submit(function(){
var P = JSON.parse('<?php echo json_encode($ValidatinArray); ?>');
var O = P.length;
alert(O);
return false;
});
});
The problem is, that in the variable $ValidatinArray is not available in the file, that prints the javascript code. Maybe this manual page helps you:
http://www.php.net/manual/en/language.variables.scope.php
Try this:
<?php
echo ' <script>
$(document).ready(function() {
$("form").submit(function(){
var P= '. json_encode($ValidatinArray) . ';
var O=P.length;
alert(O);
return false;
});
});
</script>';
?>
What you do is simply echo the js using php.
Your tag is coming from the form that you are submitting. check what your form data is before you encode it to verify the output. you can use console.log($("form));
Also using form is not a good idea since if you have more than one form and form is a global name. For forms you should give it a unique form name like "myForm" so that you can target that specific form.
Hope this helps
first of all I recommend that you verify that the variable $ValidatinArray exists and that it is being passed correctly to the file where you are doing the "echo".
the error you show indicates that from the beginning the variable that contains the array does not exist.
if the SQL query is inside a php function check that you are returning the variable.
example
<?php
function GetData(){
// ... here is the code to get the information from the database ...
return $ValidatinArray;
}
$ValidatinArray = GetData();
?>
once you have validated that this array exists we can now see the problem of passing the data to JavaScript:
It all depends on how the structure is, if you have the PHP code and the JavaScript function in the same file you can simply use this method inside the php fil:
// ... php file code
?>
<script>
$(document).ready(function() {
$("form").submit(function(){
// you can use any of the two methods that I leave you here
// Using only json_enconde
var P= <?= json_encode($ValidatinArray) ?>;
// Using json_enconde to pass the array as a string and using JSON.parse to have JavaScript convert it to an object
var P= JSON.parse('<?= json_encode($ValidatinArray) ?>');
var O = P.length;
alert(O);
return false;
});
});
</script>
In case the php file is executed at the moment of opening the page and the file that contains your function in JavaScript is in another file:
You can generate a "global" JavaScript variable from the php code as follows
// ... code php file
?>
<script>
window.variablename = <?= json_encode($ValidatinArray) ?>
</script>
<?php
inside your JS file you can receive the array like this
$(document).ready(function() {
$("form").submit(function(){
var P= window.variablename ;
var O = P.length;
alert(O);
return false;
});
});
PD: using <?= is equivalent to using echo
In php json_encode the array like this:
$inlinejs='';
$inlinejs.='var validatinArray=\''.addslashes(json_encode($ValidatinArray)).'\';'."\n";
$inlinejs.='var validatinArray=eval(\'(\' + validatinArray + \')\');'."\n";
and in javascript:
$(document).ready(function() {
$("form").submit(function(){
<?php echo $inlinejs; ?>
console.log(validatinArray);
});
});

Categories