How to Use PHP to Trigger a JS onClick Event - php

I have a signup form that has an input box hidden from view unless a link is clicked. Here's the code:
<a id="showCoupon" href="javascript:void(0);" onclick="toggleCoupon();">
<?php _e('Have a coupon?','mysite'); ?>
</a>
If the coupon GET variable is set, I want the input box to be visible and prefilled with the supplied data. I added PHP to check for the presence of a GET variable like this:
if(isset($_GET['coupon'])) {
$coupon = $_GET['coupon'];
}
?>
In addition, the input box has been modified to use the value of $coupon, if set. Now, I can't figure out how to trigger the JS event toggleCoupon();.
I modifying the PHP function to click the link like this:
if ( isset($_GET['coupon']) ) {
$coupon = $_GET['coupon'];
echo "<script>$('#showCoupon').trigger('click');</script>";
}
?>
So far, it doesn't work. What am I doing wrong?

have you tried:
<script>
$(document).ready(function(){
$('#showCoupon').trigger('click');
});
</script>
When the document loads, jQuery will trigger the click even of the element with the id of showCoupon

Don't use a kludge like that. That's awful.
Instead, on the server side, don't output the piece of code (CSS class, "display: none;", whatnot) that hides the element in the first place, if the URL parameter is provided.
If the element is hidden by JavaScript, pass it a value indicating that the initial state should be visible.

Related

in page jquery not firing

I have a page that's creating rows, which include checkboxes that have non-sequential ids. Depending on the data from the database, sometimes they need to be checked onLoad. The PHP is looping through the data, creating the page.
The problem: the jquery that I have within the loop is not working. It's not checking the checkbox or firing the change event. It's also not showing me the console.logs that I have there. If I check the checkbox inline, that IS working, but it doesn't fire the change event and it MUST to make the page function correctly.
here's some code:
<? foreach($weekly as $w){ ?>
// create the row
<input type="checkbox" id="slW_4" name="slW_4" <? if($w['current_sl_id']){echo 'checked';} ?>>
<? if($w['current_sl_id']){ ?>
<script language="text/javascript">
$(document).ready(function(){
$('#slW_4').prop('checked', true);
console.log('should have checked the checkbox: '+ $('#slW_4').is(':checked'));
$('#slW_4').trigger("change");
console.log('should have triggered change');
});
</script>
<? } ?>
<? } ?>
I highly recommend factoring your javascript outside of that loop. Worst case scenario is that you have to reloop $weekly later in code.
You do not have anything bound to listen to the change event and by default triggering a change doesn't do anything to the actual checkbox.
You would need a listener like:
$('#slW_4').on('change', function (event) {
// ...do something here
});
// Rest of your code underneath
Then the $('#slW_4').trigger("change"); would trigger that function
Also unrelated, but at the top, if you're calling $('#slW_4') a lot, I would store it in a variable like var $sl4 = $('#slW_4') and use that variable like $sl4.prop('checked', true)

Pass dynamic data from to div to another div on same page

I am stuck in a problem and in need of support from you guys.
My problem is I want to pass a php variable(dynamically called through database in loop) to another div on the same page without page refresh
//This is a loop
<td><a class="linkright" href="#existingcase?case_id=<?php echo $row_mycases['case_id']; ?>"><?php echo $row_mycases['case_id']; ?></a></td>
//The div which should get the above php variable
<div class="tabright" id="existingcase">
<?php
$c_id = $_GET['case_id'];
echo $c_id;
?>
</div>
//the javascript code for calling divs on the same page
<script>
$(".linkright").click(function(){
$(".tabright").hide();
theDiv = $(this).attr("href");
$(theDiv).slideToggle();
});
</script>
It shows in the url like this index.php#existingcase?case_id=2012001 but never passes the case id to #existingcase. And also #existingcase div does not load either but without passing caseid value, #existingcase loads.
Any suggestions would be great.
I think you want to print clicked case_id in div without page load. To do this, you don't want to pass it using url. you can simply achieve it using javascript.
If your div id existingcase is just change your code like this below.
you are printing that same case_id as a text of anchor tag using $row_mycases['case_id'];. So, you can easily get that text using javascript and you can easily print it in your #existingcasediv.
<td><a class="linkright" href="#existingcase"><?php echo $row_mycases['case_id']; ?></a></td>
I don't know about your other scripts. in .linkright click function place this code like this
$(".linkright").click(function(){
$('#existingcase').text($(this).text()); //if your div id is existingcase it will print your case id.
});
try this code. And let me know the result.
SEE THIS FIDDLE DEMO
UPDATED:
To pass client side value to serverside without page reload, you can use jquery.post() method.
Place this PHP code at the top of your page.
<?php
if (isset($_POST['id'])) {
$caseid = $_POST['id'];
return print_r($caseid);
}
?>
$caseid will contain currently clicked case_id value. So, you can use this $caseid wherever you want in this page. If you click on the another case id, it will update with respect to currently clicked case_id
replace your js with below code,
$(".linkright").click(function () {
$(".tabright").hide();
theDiv = $(this).attr("href");
$(theDiv).slideToggle();
$.post("yourPHPFile.php", { //use your current php file name instead of "yourPHPFile.php"
id: $(this).text()
}, function (caseid) {
$('#existingcase').text(caseid);
});
});
id : $(this).text() means, get the current element .text() and assign it to $_POST variable name of id. It will post to yourPHPFile.php. And you can retrieve that value like $caseid = $_POST['id'];.
In function (caseid) {, caseid contains the value of $caseid. So, only in this code, I assigned $caseid = $_POST['id'];
By this you can directly print clicked case_id text to your #exixtingcase div.
Any values after # are not sent to the server. Since PHP is a server technology you php code will never see the values after #
<a class="linkright" href="#existingcase?case_id=<?php echo $row_mycases['case_id']; ?>">
try doing
<a class="linkright" href="existingcase?case_id=<?php echo $row_mycases['case_id']; ?>">
instead and your php code should fill the div.
In my understanding of your explanation I think you are making a mistake. You are trying to mix Javascript and PHP with out page refresh. This is not possible through your code as PHP is server side and only works on the server. You can't do href within the same page and expect PHP code inside this div to be executed. The PHP code will not be there. You can try "view source" in your browser and check it out.
I think the only way to solve your problem is to make AJAX call using Javascript, get the response and put wherever you want (without refreshing the page)
Hope this helps and excuse my English
EDIT : Here is a working example for making a simple AJAX call using Jquery.
Your table should be some thing like this:
<td>
<a class="linkright" href="#" data-id="<?php echo $row_mycases['case_id']; ?>"><?php echo $row_mycases['case_id']; ?></a>
</td>
You will notice I added "data-id" attribute. We will use this id in our AJAX call. Put this in your JS :
// Create Jquery ajax request
$("a.linkright").click( function() {
$.get("example.php", // Put your php page here
{ case_id : $(this).attr("data-id") }, // Get data, taken from the a tag
function(data) { // Call back function displays the response
$(".tabright").html("<p>" + data + "</p>");
}); // Get
}); // click event
}); // Document Ready
I tested the code and it is working. You will need to customize it to work for you. If all of this AJAX is new to you I suggest these links for you :
http://www.w3schools.com/ajax/default.ASP
http://learn.jquery.com/ajax/

php : cannot see the hidden value submitted by Javascript

I'm pretty sure I'm missing something simple here, but it's driving me nuts !
This isn't the first form I'm using in PHP, but the first time submitting a hidden value.
When a menu item is clicked, I want to submit the page to itself - setting a simple parameter, so the php code does the processing.
The page gets submitted fine, but the hidden variable I set isn't available through _GET, _POST or _REQUEST. It should be _GET since that is what I've set as the method.
Here is the code if anyone can spot where I'm going wrong..
paramCustom is the one that I'm trying to set and work on.
The menu is a series of DIVs & anchors :
Option Xyz
The activateMenu javascript function is :
function activateMenu(optionTaken)
{
// Set the hidden variable
document.getElementById('paramCustom').value = optionTaken;
// Display it to confirm it is set correctly
var tt = document.getElementById('paramCustom').value;
console.log("paramCustom set to : " + tt);
// Submit the form
document.getElementById('linkSubmit').submit();
return false;
}
The form is coded this way :
<form method="get" action="showProducts.php" id="linkSubmit">
<input type="hidden" id="paramCustom" name="paramCustom" />
<input type="submit" tabindex="-1" style="display:none;" />
</form>
In the php of the same page I'm trying to spit them out but all of them show blank !!
echo "paramCustom get is : ".$_GET['paramCustom']."<br/>"; // This should work
echo "paramCustom request is : ".$_REQUEST['paramCustom']."<br/>";
echo "paramCustom post is : ".$_POST['paramCustom']."<br/>";
OK, problem is that you are not actually stopping the event from firing. So clicking on the link, the function gets called, form submitted but you are not actually stopping the event in the onclick. So form submits but is immediately redirected to the href of the link cancelling the form submit. When the href is blank, it defaults back to the page you are currently on.
The way you are adding the onclick to the link (using an inline attribute) is like wrapping the event in a closure. So when onclick fires, what is really fired is more like function(){ activateMenu('option-xyz'); }. Your call to activateMenu is returning false, but the closure around it is not. You can just add return in front of activateMenu to have the event itself return false and cancel. Change the link like so:
Option Xyz
And then the actual event itself will return false, not just the function.
Here is a simple example to illustrate what is happening.
Doing a little change to the HTML you can set the inline event via Javascript, which is a way better:
<a id="xyz" href="#">Option Xyz</a>
And this is the Javascript edited for your purpose:
function activateMenu(optionTaken)
{
var paramCustom = document.getElementById('paramCustom');
// Set the hidden variable
paramCustom.value = optionTaken;
// Display it to confirm it is set correctly
var tt = paramCustom.value;
console.log("paramCustom set to : " + tt);
// Submit the form
document.getElementById('linkSubmit').submit();
return false;
}
window.onload = (function() {
document.getElementById('xyz').onclick = function() {
activateMenu('option-xyz');
};
});
In PHP, as you know, $_GET gets the parameters of query string, $_POST of the POST data and $_REQUEST is a concat of the two arrays. In this case your method is GET so the value can be retrieved via _GET and _REQUEST, _POST is not going to work. Your code didn't worked to me probably because you had your function defined before DOM was loaded, so the event, when fired, probably throwed an exception.
This doesn't work because you haven't assigned a value. PHP won't recognize a field with a null value.
<input type="hidden" id="paramCustom" name="paramCustom" value="somevaluehere" />
[edit]
After testing this myself, it's because the onclick event is not behaving the way you anticipate. The easiest way to fix this is to use a HREF for you link. It's actually bad practice to rely solely on the onclick event anyway.
Option Xyz
This works perfectly.
The proper way to write an onclick looks like this:
Option Xyz
This works as well.
I've been using JQuery lately and it might be worth a shot.
Download the latest JQuery script and just link it to your page.
function activateMenu(optionTaken)
{
// Set the hidden variable
$("#paramCustom").val() = optionTaken;
// Display it to confirm it is set correctly
var tt = $("#paramCustom").val();
console.log("paramCustom set to : " + tt);
// Submit the form
document.getElementById('linkSubmit').submit();
return false;
}
This isn't that much different than what you had but maybe JQuery will do a better job of assigning the value to your hidden field...
Cheers,
K

Get the data from an iframe after form post has completed performing a file upload on target for

I have a form which uses the target attribute to target an iframe when the form is posted which posts to a PHP script. This part is working fine but I need to do something based on several results that the php script will put in the iframe.
What I am thinking of doing is when the PHP script has finished posting it echo's out some hidden input fields that contain various elements, such as the state of the post, whether it succeeded and what the final result was if it was successfully posted.
However, if I did this it would put it into the iframe so then the main web page wouldn't be able to access the hidden input fields.
How would the main web page be able to access these hidden input fields so that the main web page can perform some action, I.e. make a div within the web page show a specific error message or whatever.
The other thing is, once I know how I can get the data from the hidden input field, how would I know when I can go and get the values. I was thinking that when the form is posted via a JavaScript document.forms["myform"].submit() code I could then do a while loop and check to see if another hidden input field status is set to complete and once it says complete I can then get the values from the hidden input field.
I'm not sure if the way I suggested is the right way or doing what I want to achieve or if there is a better way of doing it.
UPDATE
I've tried what #lanzz suggested but it doesn't appear to have worked. Below is what I have tried.
$("iframe#image_upload_frame").on('load', function()
{
var iframeBody = this.contentDocument.body;
var data = $(iframeBody).find("#imageDirectory");
alert("data: " + data);
});
Below is how the iframe is defined
<iframe id="image_upload_frame" name="image_upload_frame"></iframe>
and I am echoing out a hidden input field in the php script that's within the iframe.
echo '<input type="hidden" id="imageDirectory" value="'.$imageDirectory.'" />';
The echo is definetly working as when I see view the iframe source I can see the hidden input however, the alert dialog is never shown as if something isn't working. There are no errors being reported either by the google chrome dev console.
If I understand correctly - you need a value from the iframe in the parent window, once the value is loaded into the iframe. I would add javascript to the iframe calling the parent and executing a function.
In the main frame:
function incomingValue(val) {
alert(val)
}
and somewhere in the generated iframe:
<script type="text/javascript">
parent.incomingValue("Hello world");
</script>
This should work assuming both frame sources share the same domain.
You can use postMessage for cross document communication between an iframe and it's parent.
See:
http://viget.com/extend/using-javascript-postmessage-to-talk-to-iframes
http://javascript.info/tutorial/cross-window-messaging-with-postmessage
Since you're running on the same domain, your main page's Javascript will have no trouble to access the contents of the <iframe> (example uses jQuery, you could rewrite into whatever libs you plan to use):
$('iframe#the-id-of-the-iframe').on('load', function() {
var iframeWin = this.contentWindow;
var iframeBody = this.contentDocument.body;
// access global JS vars defined in the iframe:
var someIframeVariable = iframeWin.globalIframeVariable;
// or, directly access elements in the iframe:
var someIframeElement = $(iframeBody).find('#element-id-inside-iframe');
});
A while ago I wrote a piece of code to upload a picture using some javascript and two iframes. The most important thing for me was to preview the pic. Maybe it will help you:
HTML:
<div id='fakebutton' onclick='select_pic()'>Just a button to select a pic</div>
<iframe src='uploadform.php' name'pic_frame'></iframe>
<iframe src='#' name='target_frame'></iframe>
both the iframes are hidden. The targetframe has no source (or an empty page, if you want to).
uploadform.php contains a form:
<form id='upload_form' action='dosomething.php' method='post' enctype='multipart/form-data' target='target_frame' onsubmit=''>
<input id='realfoto' name='realfoto' type='file' onchange='parent.foto_upload(window.frameElement.id)'>
</form>
and then some javascript:
First of all something to trigger the filebrowser when the user clicks the fake
function select_pic(){
b=window.frames['pic_frame'];
b.document.upload_form.realfoto.click();
}
And then a part to actually upload the pic, triggered by the onchange() in the input element:
function foto_upload(o){
var b=o;
o=getElementById(o);
if(o.contentDocument ) {o = o.contentDocument;}
else if(o.contentWindow ){o = o.contentWindow;}
else{return false;}
if(test_pic(o,b)){ //test if it is really a pic
getObj('foto_tmpdir').value=o.getElementById('tmp_dir').value;
o.getElementById('doctype_nr').value=b;
o.fotoform.submit();
}
else{
return false;}
}
In dosomething.php I perform actions on the uploaded pic (rename, resize etc). And it contains a few lines of javascript:
$a = 'upload was succes';
$b = 'my_image_name';
$c = 'whatever you want to put here';
?>
<script type="text/javascript">
window.top.window.smurf(<?php echo "'$a','$b','$c'" ?>);</script>
<?php
if you create in javascripty a function named smurf(a,b,c) you can pass along whatever you want form the php-script. One of the most important things for me was that I now can pass the filename of the uploaded pic to javascript, and use it to change an image.src for a preview.
Hope you can use something of it.
Your iframe source page should has a javascript call function instead of the hidden field. The function will call the opener window (your main page) and then it do any functionality you want. As blue print look at the following:
//in iframe src.php
<?php
if ($something){
?>
<script>
function doSomethingWithOpenerWindow(){
opener.document.write('hi);
}
doSomethingWithOpenerWindow()
</script>
<?php
}
else{
?>
<script>
function doAnotherSomethingWithOpenerWindow(){
opener.document.write('hi);
}
doAnotherSomethingWithOpenerWindow()
</script>
<?php
}
?>

PHP variable as part of a jQuery function doesn't work, but plain text does

I have the following jQuery code in my PHP file (edited Jan 19 2010 # 10:40 MST):
<?php
$count = 0;
foreach($attachments as $attachment) :
echo '<script type="text/javascript">
$(\'#a_'.$count.'\').click(function() {
$(\'#d_'.$count.'\').show(200);
});
// if "no" is clicked
$(\'#d_'.$count.' .no\').click(function() {
$(\'#d_'.$count.'\').hide(200);
});
// if "yes" is clicked
$(\'#d_'.$count.' .yes\').click(function() {
$(\'#d_'.$count.'\').hide(200);
// update database table -- this is why I need the script inside the for loop!
var jsonURL = \'http://path/to/update_db_script.php\';
$.getJSON(jsonURL, {\'post_id\' : '.$attachment->ID.'}, function(data) {
alert(\'Thank you. Your approval was received.\');
});
$(\'#a_'.$count.'\').replaceWith(\'<span>Approved</span>\');
});
</script>';
echo '<li>';
if($attachment->post_excerpt == 'approved') {
// Check the proof's status to see if it reads "approved"
echo '<span>Approved</span>';
} else { ?>
// If not yet approved, show options
<a class="approve" id="a_<?php echo $count; ?>" href="#">Click to Approve</a>
<div class="confirm-approval" id="d_<?php echo $count; ?>">
<p>Please confirm that you would like to approve this proof:</p>
<a class="yes" href="#">Yes, I approve</a>
<a class="no" href="#">No, not yet</a>
</div><?php
} ?>
</li>
<?php $count++;
endforeach; ?>
The page in question is available here. The "click to approve" links do not work (that's my problem).
When I view source, the PHP variables appear to have echoed properly inside the jQuery:
<script type="text/javascript">
$('#a_0').click(function() {
$('#d_0').show(200);
});
... etc ...
</script>
This looks correct, but nothing happens when I click any of the links. However, when I replace the PHP echo statements with plain numbers (0, 1, etc.) the click functions work as expected.
You may be asking: why on earth do you have this inside a for loop? The reason is that I need to retrieve the attachment->ID variable and pass it to an external PHP script. When someone clicks "approve" and confirms, the external script takes the attachment->ID and updates a database value to read "approved".
Why won't the click function fire when PHP is in place? Is there some kind of greater force at work here (e.g., hosting limitation), or am I missing a fundamental piece of how PHP and JavaScript interact?
Since you didn't post your HTML its a little hard to troubleshoot.
First, I am not sure why one is working and the other is not since the code it is outputting looks correct. Either way, I still would make some changes. Move your a_0,a_1, etc and d_0,d_1, etc into the id attribute instead of a class:
<div>Click Me</div>
<div class="confirm_approval" id="d_0">Show Me</div>
<div>Click Me</div>
<div class="confirm_approval" id="d_1">Show Me</div>
Now, instead of outputting your code in a loop in PHP, place this jQuery code once on your page:
$(document).ready(function(){
$("a.approve[id^='a_']").click(function(e){
var id = this.id.replace('a_',''); // Get the id for this link
$('#d_' + id + '.confirm-approval').show(200);
e.preventDefault();
});
});
This code finds any a element with the approve class that has an id that starts with a_. When this is clicked, it grabs the number off the id a_0 = 0 and uses that id to find the confirm-approval element and show it.
Since the javascript is run on the client and has no way of knowing whether the script was generated using PHP or not, I think that particular part is a wild goose chase...
When I replace the PHP echo statements
with plain numbers (0, 1, etc.) the
click function works as expected.
Do this again and compare the actual output using view-source in a browser. I'll bet you find that there is a difference between the working and failing scripts, other than one of them being generated by PHP.
It seems that the problem is in jQuery selectors. Instead of dynamically binding click() events on multiple objects with an output of PHP code, use just one class selector and bind to objects with this class. And you can specify an id attribute to make them unique.
Something strange too is to have the script tag and the
$(document).ready(function()
in the loop. I don't know if this causes any problems, but it's sure not very efficient, one time is enough.

Categories