On Click not working with JS - javascript

The code shown here is meant to take me to the next part of checkout process however I encounter the error that billing is not defined? I've tried to put a function and call that function via the onclick but this has no effect.
The code that isn't working shall be the bottom section of the code which is the JS along with the button just above
Below is the where you can see the button and the onclick callout
<div class="buttons-set form-buttons btn-only" id="billing-buttons-container">
<button type="button" class="btn" onclick="billing.save()"><span><span><?php echo $this->__('Continue') ?></span></span></button>
<span id="billing-please-wait" class="please-wait" style="display:none;">
<img src="<?php echo $this->getSkinUrl('images/opc-ajax-loader.gif') ?>" alt="" class="v-middle" /> <?php echo $this->__('Loading next step...') ?>
</span>
</div>
<p class="required"><?php echo $this->__('* Required Fields') ?></p>
<?php echo $this->getBlockHtml('formkey') ?>
</form>
The JS below is not working correctly
<script type="text/javascript">
//<![CDATA[
var billing = new Billing('co-billing-form', '<?php echo $this->getUrl('checkout/onepage/getAddress') ?>address/', '<?php echo $this->getUrl('checkout/onepage/saveBilling') ?>');
var billingForm = new VarienForm('co-billing-form');
//billingForm.setElementsRelation('billing:country_id', 'billing:region', '<?php echo $this->getUrl('directory/json/childRegion') ?>', '<?php echo $this->__('Select State/Province...') ?>');
$('billing-address-select') && billing.newAddress(!$('billing-address-select').value);
var billingRegionUpdater = new RegionUpdater('billing:country_id', 'billing:region', 'billing:region_id', <?php echo $this->helper('directory')->getRegionJson() ?>, undefined, 'billing:postcode');
if ($('onepage-guest-register-button')) {
Event.observe($('onepage-guest-register-button'), 'click', function(event) {
var billingRememberMe = $('co-billing-form').select('#remember-me-box');
if (billingRememberMe.length > 0) {
if ($('login:guest') && $('login:guest').checked) {
billingRememberMe[0].hide();
} else if ($('login:register') && ($('login:register').checked || $('login:register').type == 'hidden')) {
billingRememberMe[0].show();
}
}
});
}
//]]>
</script>

jQuery was blocking another jQuery file and therefore it wasn't working correctly as intended, but since removing one of jQuery files it now works :D

Related

How to call js function from php?

I have a php page, a html button on it and there I should call a JS function with a php variable. And I get the error
the variable is not defined
Here is the code:
<body>
<form class="form">
<?php
if(file_exists('megjelenitendo.txt')){
$mappak=array();
$mappakdb=0;
$megjelenitendo = fopen("megjelenitendo.txt", "r") or die("Unable to open file!");
while(!feof($megjelenitendo)) {
$mappak[$mappakdb]=fgets($megjelenitendo) ;
$mappakdb++;
}
fclose($megjelenitendo);
$j=0;
foreach(glob('*') as $filename){
for($i=0; $i<$mappakdb;++$i){
//echo $filename."==".$mappak[$i];echo "<br>";
if(strtoupper($filename)==strtoupper(trim($mappak[$i]))){
//echo '<button type="submit" id='.$i.' class="button" formaction='.$filename.' />'.$filename;//substr($filename, 3,strlen($filename));
echo '<button type="button" id='.$i.' class="button" OnClick=mappanyitas('.trim($mappak[$i]).')>'.trim($filename).'</button>';
echo '<br>';
}
else{}
}
}}
else{
echo "A mappa elemei:<br>";
}
?>
</form>
<script type="text/javascript">
function mappanyitas(filename){
alert(filename);
}
</script>
</body>
You can call javascript function like this :
<?php
echo "<script>functionName();</script>";
?>
But function should be defined already.
The way to get PHP variables to javascript that I tend to use is just set the variable :)
<script type="text/javascript">
var fromPHP = '<?= $phpVariable; ?>';
</script>
Ti's as simple as that.
echo '<button type="button" id='.$i.' class="button" OnClick=mappanyitas("'.trim($mappak[$i]).'")>'.trim($filename).'</button>';
try this line
echo '<button type="button" id='.$i.' class="button" onclick="mappanyitas('.trim($mappak[$i]).')">'.trim($filename).'</button>'
Let me know if this solved your problem!
P.S.
Check the rendered page's HTML and check the button's code, to check if the variable's value was successfully injected into the code

Ajax comment system into a do-while loop

I have a comment system that is working fine. But now I wanna make it work into a loop, so it needs is add an id to identify as unique every "comment box", "submit buttom", so on. Due to there are many classes involved I got lost adding the index to the js function ... and actually everything.
This is my code:
<?php
$sql = mysql_query("SELECT * FROM tblopiniones_persopoli WHERE id_post = '$id_post' AND intActivo = '1' LIMIT 0,10") or die(mysql_error());
while($affcom = mysql_fetch_assoc($sql)){
$name = $affcom['intName'];
$email = $affcom['email'];
$comment = $affcom['strComment'];
$date = $affcom['date'];
// Get gravatar Image
// https://fr.gravatar.com/site/implement/images/php/
$default = "mm";
$size = 35;
$grav_url = "http://www.gravatar.com/avatar/".md5(strtolower(trim($email)))."?d=".$default."&s=".$size;
?>
<div class="cmt-cnt">
<img src="<?php echo $grav_url; ?>" />
<div class="thecom">
<h5><?php echo ObtenerNombreFull_Usuario($name); ?></h5><span data-utime="1371248446" class="com-dt"></span>
<br/>
<p>
<?php echo $comment; ?>
</p>
</div>
</div><!-- end "cmt-cnt" -->
<?php } ?>
<div class="new-com-bt" id="<?php echo $m; ?>">
<span id="">Escribe un comentario ...</span>
</div>
<div class="new-com-cnt">
<a name="coment_box" id="coment_box">
<input type="hidden" id="name-com" name="name-com" value="<?php echo $_SESSION['MM_IdUser']; ?>" />
<input type="hidden" id="mail-com" name="mail-com" value="<?php echo 'xxxxxxx#gmail.com'; ?>" />
<input type="hidden" id="pic-com" name="pic-com" value="<?php echo ObtenerNombreFoto_Usuario($_SESSION['MM_IdUser']); ?>" />
<textarea class="the-new-com" placeholder="Ingresa tu comentario"></textarea>
<div class="bt-add-com">Publicar comentario</div>
<div class="bt-cancel-com">Cancelar</div>
</a>
</div>
My Js code:
<script type="text/javascript">
$(function(){
//alert(event.timeStamp);
$('.new-com-bt').click(function(event){
$(this).hide();
$('.new-com-cnt').show();
$('#coment_box').focus();
});
/* when start writing the comment activate the "add" button */
$('.the-new-com').bind('input propertychange', function() {
$(".bt-add-com").css({opacity:0.6});
var checklength = $(this).val().length;
if(checklength){ $(".bt-add-com").css({opacity:1}); }
});
/* on clic on the cancel button */
$('.bt-cancel-com').click(function(){
$('.the-new-com').val('');
$('.new-com-cnt').fadeOut('fast', function(){
$('.new-com-bt').fadeIn('fast');
});
});
// on post comment click
$('.bt-add-com').click(function(){
var theCom = $('.the-new-com');
var theName = $('#name-com');
var theMail = $('#mail-com');
var thePic = $('#pic-com');
if( !theCom.val()){
alert('¡Por favor escribe un comentario!');
}else{
$.ajax({
type: "POST",
url: "add-comment.php",
data: 'act=add-com&id_post='+<?php echo $id_post; ?>+'&name='+theName.val()+'&email='+theMail.val()+'&comment='+theCom.val()+'&pic='+thePic.val(),
success: function(html){
theCom.val('');
/*theMail.val('');
theName.val('');*/
$('.new-com-cnt').hide('fast', function(){
$('.new-com-bt').show('fast');
$('.new-com-bt').before(html);
})
}
});
}
});
});
I'll highly appreciate any help with this lack of knowledge & expertise.
Many thanks in advance.

'Click' action conflict with `submit` action

So, I have the following setup with a Submit button that saves any changes.
<div class="mysite-body">
<?php do_action('mysite_pre_form_message'); ?>
<form action="" method="post" data-action="<?php echo $template; ?>">
<input type="hidden" name="user_id-<?php echo $i; ?>" id="user_id-<?php echo $i; ?>" value="<?php echo $user_id; ?>" />
<?php
if (!isset($user_id)) $user_id = 0;
$hook_args = array_merge($args, array('user_id' => $user_id, 'unique_id' => $i));
do_action('mysite_before_fields', $hook_args);
?>
<?php foreach( mysite_fields_group_by_template( $template, $args["{$template}_group"] ) as $key => $array ) { ?>
<?php if ($array) echo mysite_edit_field( $key, $array, $i, $args, $user_id ) ?>
<?php } ?>
<?php
if (!isset($user_id)) $user_id = 0;
$hook_args = array_merge($args, array('user_id' => $user_id, 'unique_id' => $i));
do_action('mysite_after_fields', $hook_args);
?>
<?php
if (!isset($user_id)) $user_id = 0;
$hook_args = array_merge($args, array('user_id' => $user_id, 'unique_id' => $i));
do_action('mysite_before_form_submit', $hook_args);
?>
<?php if ( mysite_can_delete_user($user_id) || $mysite->request_verification($user_id) || isset( $args["{$template}_button_primary"] ) || isset( $args["{$template}_button_secondary"] ) ) { ?>
<div class="mysite-field mysite-submit mysite-column" id="A">
<?php if (isset($args["{$template}_button_primary"]) ) { ?>
<input type="submit" value="<?php echo $args["{$template}_button_primary"]; ?>" class="mysite-button" />
<?php } ?>
<?php if (isset( $args["{$template}_button_mysite"] )) { ?>
<input type="button" value="<?php echo $args["{$template}_button_secondary"]; ?>" class="mysite-button secondary" data-template="<?php echo $args["{$template}_button_action"]; ?>" />
<?php } ?>
<?php if ( $mysite->request_verification($user_id) ) { ?>
<input type="button" value="<?php _e('Request Verification','mysite'); ?>" class="popup-request_verify mysite-button secondary" data-up_username="<?php echo $mysite->id_to_member($user_id); ?>" />
<?php } ?>
<?php if ( mysite_can_delete_user($user_id) ) { ?>
<input type="button" value="<?php _e('Delete Profile','mysite'); ?>" class="mysite-button red" data-template="delete" data-up_username="<?php echo $mysite->id_to_member($user_id); ?>" />
<?php } ?>
<img src="<?php echo $mysite->skin_url(); ?>loading.gif" alt="" class="mysite-loading" />
<div class="mysite-clear"></div>
</div>
<?php } ?>
</form>
</div>
<?php } ?>
Then following javascript:
<script>// <![CDATA[
jQuery("#A").click(function(){
jQuery("#B").trigger('click');
return false; });
// ]]></script>
And id="B" is on a header as a simple anchor button:
<div class="startskip"><a id="B" href="http://mysite/start/item">Skip</a></div>
What I want to achieve is that when a submit button is clicked, then the skip button is also triggered and the user will be redirected to the next page.
Of course, I am going to put setTimeoutso there is enough time to save instead of instant redirect.
However, the submit button becomes not-responsive when I add the javascript.
So, it seems that there is a javascript conflict between the click function and submit function. (Without the javascript, the submit button works).
By looking the code, could you guys figure out what the problem is and how to solve it?
Thanks!
I read an article on this previously which explains why it doesn't work - but have lost the link, I'll see if I can find it an update this post tomorrow. But the summary would be to say that the jQuery trigger click method triggers the event handler for the element, it does not trigger the browsers default behaviour i.e. following a link.
You have two choices, if you must use jQuery, then you can use this:
window.location = $('#B').attr('href');
Another option is to use pure JS:
document.getElementById("a_link").click();
In this case, I would go for the second option since I think it is more clear and readable - but that's subjective!
The return false inside the click handler cancels the original click and that is why the form doesn't get submitted.
I don't think it's possible to run any script after the form submission though. You could try submitting the form with ajax and on success do the redirect.

Passing a Variable from PHP to Javascript for Image file

I have a gallery of images. When a user clicks on an image, the page scrolls and displays the image along with a Title, Description, and a "Go to" button. All works great except passing a variable for the Go To button. I need to pass the user ID to the JS script. Here is the partial PHP code:
<img src=<?php echo $image_finder?>
height=<?php echo $img_height?>
width=<?php echo $img_width?>
class="superbox-img"
data-img="<?php echo $image_finder?>"
title="<?php echo $artist_name?>"
alt="<?php echo $artist_about ?>"
location="<?php echo $artist_id?>" >
The PHP code is in a foreach loop. There may be a hundred images but I need to get the ID (in the location parameter) for the selected image.
At the bottom of the PHP page, I include the JS file and the following call to the JS file and function.
var pagefunction = function() {
$('.superbox').SuperBox();
};
loadScript("js/plugin/superbox/superbox.min.js", pagefunction);
In the JS file, I need to get the location parameter and pass into the HREF. I have marked where the variable need to go about 8 lines down after the main.php?location=(variable). Any help is appreciated. Thanks, Grant
function(a) {
a.fn.SuperBox = function() {
var b = a('<div class="superbox-show"></div>'),
c = a('<img src="" class="superbox-current-img">
<div id="imgInfoBox" class="superbox-imageinfo inline-block">
<h1>Image Title</h1>
<span><p><em>http://imagelink.com/thisimage.jpg</em></p>
<p class="superbox-img-description">Image description</p>
<p><a **href="main.php?location=' + location + '**" class="btn btn-primary btn-sm">Go to Artist</a>
Delete</p></span> </div>'),
d = a('<div class="superbox-close txt-color-white"><i class="fa fa-times fa-lg"></i></div>');
b.append(c).append(d);
a(".superbox-imageinfo");
return this.each(function() {
a(".superbox-list").click(function() {
$this = a(this);
var d = $this.find(".superbox-img"),
e = d.data("img"),
f = d.attr("alt") || "No description",
g = e,
h = d.attr("title") || "No Title";
l = d.attr("location") || "No Location";
c.attr("src", e), a(".superbox-list").removeClass("active"), $this.addClass("active"), c.find("em").text(g), c.find(">:first-child").text(h), c.find(".superbox-img-description").text(f), 0 == a(".superbox-current-img").css("opacity") && a(".superbox-current-img").animate({
opacity: 1
}), a(this).next().hasClass("superbox-show") ? (a(".superbox-list").removeClass("active"), b.toggle()) : (b.insertAfter(this).css("display", "block"), $this.addClass("active")), a("html, body").animate({
scrollTop: b.position().top - d.width()
}, "medium")
}), a(".superbox").on("click", ".superbox-close", function() {
a(".superbox-list").removeClass("active"), a(".superbox-current-img").animate({
opacity: 0
}, 200, function() {
a(".superbox-show").slideUp()
})
})
})
}
}(jQuery);
SEMICOLONS!
<img src=<?php echo $image_finder; ?> height=<?php echo $img_height; ?> width=<?php echo $img_width; ?> class="superbox-img" data-img="<?php echo $image_finder; ?>" title="<?php echo $artist_name; ?>" alt="<?php echo $artist_about; ?>" location="<?php echo $artist_id; ?>" >
EDIT
QUOTES!
<img src="<?php echo $image_finder; ?>" height="<?php echo $img_height; ?>" width="<?php echo $img_width; ?>" class="superbox-img" data-img="<?php echo $image_finder; ?>" title="<?php echo $artist_name; ?>" alt="<?php echo $artist_about; ?>" location="<?php echo $artist_id; ?>" >
Solution 1
Put your javascript code in the PHP page and echo the variable value, ie:
c = a('<img src="" class="superbox-current-img">
<div id="imgInfoBox" class="superbox-imageinfo inline-block">
<h1>Image Title</h1>
<span><p><em>http://imagelink.com/thisimage.jpg</em></p>
<p class="superbox-img-description">Image description</p>
<p>Go to Artist
Delete</p></span> </div>'),
d = a('<div class="superbox-close txt-color-white"><i class="fa fa-times fa-lg"></i></div>');
Solution 2:
In you JS file do something like
var MYAPP = MYAPP || (function(){
var _vars = {};
return {
init : function(variables) {
_vars = variables;
// ... you other code
},
superBox : function() {
//.. your other code
c = a('<img src="" class="superbox-current-img">
<div id="imgInfoBox" class="superbox-imageinfo inline-block">
<h1>Image Title</h1>
<span><p><em>http://imagelink.com/thisimage.jpg</em></p>
<p class="superbox-img-description">Image description</p>
<p>Go to Artist
Delete</p></span> </div>'),
d = a('<div class="superbox-close txt-color-white"><i class="fa fa-times fa-lg"></i></div>');
//.. your other code
}
};
}());
then in your php file:
<script type="text/javascript" src="myfile.js"></script>
<script type="text/javascript">
MYAPP.init({myVariable: "<?php echo urlencode($myVariable) ?>"});
MYAPP.superBox();
</script>

AJAX improvement for validation

SO i have this piece of AJAX that work as it should be but i want to add some validation to it.I dont want it to send empty information.The AJAX is done for a comment system.It takes the value from the form and then with php it inserts it to the databse. The Problem i am haveing is that it just insert empty comment to the database
index.php
<?php
require_once("menu.php");
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script src="comments.js" type="text/javascript" ></script>
<script type="text/javascript">
function validateForm()
{
var comment = document.getElementsByName('comment').value;
if (comment == "" )
{
alert("Please fill in all the fields");
return false;
}
else
{
return true;
}
}
</script>
<?php
$connection = connectToMySQL();
$selectPostQuery = "SELECT * FROM (SELECT * FROM `tblposts` ORDER BY id DESC LIMIT 3) t ORDER BY id DESC";
$result = mysqli_query($connection,$selectPostQuery)
or die("Error in the query: ". mysqli_error($connection));
while ($row = mysqli_fetch_assoc($result))
{
$postid = $row['ID'];
?>
<div class="wrapper">
<div class="titlecontainer">
<h1><?php echo $row['Title']?></h1>
</div>
<div class="textcontainer">
<?php echo $row['Content']?>
</div>
<?php
if (!empty($row['ImagePath'])) #This will check if there is an path in the textfield
{
?>
<div class="imagecontainer">
<img src="images/<?php echo "$row[ImagePath]"; ?>" alt="Article Image">
</div>
<?php
}
?>
<div class="timestampcontainer">
<b>Date posted :</b><?php echo $row['TimeStamp']?>
<b>Author :</b> Admin
</div>
<?php
#Selecting comments corresponding to the post
$selectCommentQuery = "SELECT * FROM `tblcomments` LEFT JOIN `tblusers` ON tblcomments.userID = tblusers.ID WHERE tblcomments.PostID ='$postid'";
$commentResult = mysqli_query($connection,$selectCommentQuery)
or die ("Error in the query: ". mysqli_error($connection));
#renderinf the comments
echo '<div class="comment-block_' . $postid .'">';
while ($commentRow = mysqli_fetch_assoc($commentResult))
{
?>
<div class="commentcontainer">
<div class="commentusername"><h1>Username :<?php echo $commentRow['Username']?></h1></div>
<div class="commentcontent"><?php echo $commentRow['Content']?></div>
<div class="commenttimestamp"><?php echo $commentRow['Timestamp']?></div>
</div>
<?php
}
?>
</div>
<?php
if (!empty($_SESSION['userID']) )
{
?>
<form method="POST" class="post-frm" action="index.php" onsubmit="return validateForm();">
<label>New Comment</label>
<textarea name="comment" class="comment"> </textarea>
<input type="hidden" name="postid" value="<?php echo $postid ?>">
<input type="submit" name ="submit" class="submitComment"/>
</form>
<?php
}
echo "</div>";
echo "<br /> <br /><br />";
}
require_once("footer.php") ?>
My AJAX code.I have tried to do some validation but it doesnt work properly and i dont know what is wrong with it.I am quite new to AJAX so not rlealy able to debug it myself.
$(document).ready(function(){
$(document).on('click','.submitComment',function(e) {
e.preventDefault();
//send ajax request
var form = $(this).closest('form');
var comment = $('.comment');
if (!comment.val()){
alert('You need to write a comment!');
}
else{
$.ajax({
url: 'ajax_comment.php',
type: 'POST',
cache: false,
dataType: 'json',
data: $(form).serialize(), //form serialize data
beforeSend: function(){
//Changeing submit button value text and disableing it
$(this).val('Submiting ....').attr('disabled', 'disabled');
},
success: function(data)
{
var item = $(data.html).hide().fadeIn(800);
$('.comment-block_' + data.id).append(item);
// reset form and button
$(form).trigger('reset');
$(this).val('Submit').removeAttr('disabled');
},
error: function(e)
{
alert(e);
}
});
}
});
});
My php code to insert into the database.
<?php
if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])):
session_start();
include('connection.php');
$connection = connectToMySQL();
$userId = $_SESSION['userID'];
$username = $_SESSION['username'];
$postId = $_POST['postid'];
$comment = $_POST['comment'];
$date_format = " Y-m-d g : i : s";
$time = date ($date_format);
$insertCommentQuery = "INSERT INTO `tblcomments`
(`Content`,`UserID`,`PostID`,`Timestamp`)
VALUES (
'$comment','$userId','$postId',
CURRENT_TIMESTAMP)";
$result = mysqli_query($connection,$insertCommentQuery);
$obj = array();
$obj['id'] = $postId;
$obj['html'] = '<div class="commentcontainer">
<div class="commentusername"><h1> Username :'.$username.'</h1></div>
<div class="commentcontent">'.$comment.'</div>
<div class="commenttimestamp">'.$time.'</div>
</div>';
echo json_encode($obj);
connectToMySQL(0);
endif?>
You never call the function validateForm()
And this part
if (!comment.val()){
alert('You need to write a comment!');
}
will always pass if there is a input field with the class comment, even if it's empty. You could do something like:
//send ajax request
if(validateForm()===false){
alert('You need to write a comment!');
return false;
}
else{
....
You could try to change the comment.val() to comment.text() since you are using a textarea and see if that solves your problem. The change is to be modified in your js code

Categories

Resources