Show Lightbox based on a condition AMP for EMAIL - php

I have 2 lightboxes. 1 for showing error lightbox and 1 for showing success lightbox.
I have a amp form and a input textfield where user enters a text.
I need to compare the value entered by the user and based on the value show either 1 of the 2 lightbox.
If value matches the text to compare then show success lightbox else show error lightbox.
My question is how can I show 1 of the 2 lightboxes if a condition is met either true or false.
if true then show success lightbox and if false then show error lightbox.
I am using action-xhr = submitform.php and method="POST"
Also I would like to know what server side code do I need to write (if I am using php to test for matching text entered by user and how to retrieve the data sent back from the server in the form).
I am new to AMP for EMAIL and trying to do this for the first time.
If anybody can help I will really appreciate that.
If you need anymore details let me know.
How can I do it.
Regards,
iceheros
I tried a lot of sample demos on the official website but could not find a concreate solution to the problem.

To show one of two lightboxes based on a condition being met, you can use the amp-state component to store the state of the condition, and then use amp-bind to bind the visibility of the lightboxes to the state.
For example, you can use the amp-state component to set an initial state for the condition:
<amp-state id="myState">
<script type="application/json">
{
"showSuccess": false,
"showError": false
}
</script>
</amp-state>
Then, you can bind the visibility of the success and error lightboxes to the state using the [hidden] attribute and the amp-bind component:
<div id="successLightbox" [hidden]="!myState.showSuccess">Success Lightbox</div>
<div id="errorLightbox" [hidden]="!myState.showError">Error Lightbox</div>
To compare the value entered by the user to the text you want to compare it to, you can use the amp-form component to submit the form data to a server-side script (e.g. submitform.php) and then use server-side code (e.g. PHP) to compare the values and set the state accordingly.
For example, in your submitform.php file, you can retrieve the input value using the $_POST variable, compare it to the text you want to compare it to, and then return the appropriate state to the client.
$inputValue = $_POST['inputValue'];
$textToCompare = "textToCompare";
if ($inputValue == $textToCompare) {
$response = array("showSuccess" => true, "showError" => false);
} else {
$response = array("showSuccess" => false, "showError" => true);
}
echo json_encode($response);
On the client side, you can use the amp-form component's on="submit-success" attribute to update the state with the response from the server:
Please adjust code to your needs and requirements

Related

how to check if bookmarks exist in html document

I've just designed my first form in HTML and a PHP page to display the results. In the form the user inputs some codes in response to some questions, a bit like a multiple choice, so for example, these are "ABC". The PHP page displays the code to the user as a link, which when clicked will go to a bookmark (a link within the same page) with the ID #ABC. This was achieved with simple manipulation of the PHP variable as follows:
<?php
$code = "ABC"
$part1 = '<a href="mywebpage.php#';
$part2 = '">Go to this code</a>';
$string = $part1.$code.$part2;
echo $string;
?>
(i.e. Link in the page says "go to this code" and when clicked will go to section with bookmark ABC)
This all works fine, but I simply need to know if there is a way of error trapping so that if a bookmark does not exist for the code entered, a message can be displayed to the user instead? Can this be done using the PHP variable, or do I need to use JavaScript? One work around may be to search the web page for the ID "#ABC'. Is it possible to do this? Another option would be to store an array of valid codes on the server then query this before setting the bookmark, but I want to keep it as simple as possible. Any help appreciated, thanks.
What you call a "bookmark" we call a hash. And when you say "go to a bookmark" you mean a hash change. Hash changes do not make an additional request to the server, it is all handled on the client-side, therefore this must be done with JavaScript and not PHP.
So let's just do some simple JavaScript on hash change window.onhashchange that will search for an element with that ID and if it's not found alert something.
window.onhashchange = function(){
if(!document.getElementById(location.hash){
alert("not found");
}
}

Notification bubble on admin panel menu if new user added using php ajax?

How can i add notification bubble like Facebook in my admin menu (when new user is signup) by using Ajax php also after viewing/clicking the menu bubble disappear.Anybody help???
When a user signs up, I guess you add him/her in your database? If so, I would add a field in your users database called "notificationViewed", which would be false by default when you put that user in the database.
When you connect or refresh you admin menu page, your php that serves the page should check the database if any user has a field notificationViewed == false, and COUNT the number of such returned users. In your html tag that represents the buble, add an attribute data-newUsers="<?= COUNT_OF_NEW_USERS ?>".
Now on the client-side...
Have, let's say, id="bubble" hidden by default with CSS:
#bubble {
display:none;
}
With JavaScript, you can access the data-* attributes easily:
var newUsers = document.getElementById('bubble').dataset.newUsers; // holds the number
or with jQuery:
var newUsers = $('#bubble').data('newUsers'); // same thing
At this point, you can check if newUsers > 0. If so, populate the bubble with the number (if you want), and do a nice fadeIn animation. Example in jQuery:
if (newUsers > 0) {
$('bubble').text(newUsers).fadeIn();
}
Now, we want to be able to detect when the bubble is clicked, in order to hide the bubble and discard the new users signed up. Again, with jQuery:
$('#bubble').click(function() {
$.post('discardNotifications.php', {usersNotified: newUsers}, function(data) {
if (data === "ok") { // php script returns this string if all went right
$('#bubble').fadeOut(function() {
$('#bubble').remove(); // remove the element from the DOM, to prevent further clicks of the element
}); // nice fadeOut animation of the bubble
}
}
});
The function will only be called if the POST request was successful. The POST request is directed to discardNotifications.php, which must be in the same directory as your admin-menu html file (if not, just change the relative path). The second parameter of the call is a litteral object containing the number of new users notified, which is sent to your back-end.
Back on the back-end, inside discardNotifications.php...
You must check if there's a POST parameter called "usersNotified", then query your users database and update at most the number given by "usersNotified". This takes into account that maybe new users subscribed since you refreshed your admin page, and you want the notification of these new users. Not selecting a maximum of "usersNotified" would possibly ignore them. Example (but not complete):
if (isset($_POST['usersNotified']))
{
$number = $_POST['usersNotified'];
// update the "notificationViewed" field to TRUE for at most $number different users
echo "ok"; // everything went right
} else {
echo "bad";
}
There are obviously changes you can make, and you have to implement some of the database handling. Tell me if it works!
Ps: there might be little errors in my code snippets, I didn't test everything.

PHP Codeigniter: Passing dynamic form data to a view without having to refetch from the database upon validation errors

I am making a basic signup page using PHP Codeigniter.
On the signup page, I ask the user to select from a selection of categories (via a <select> html element). These categories are stored in a list in my MySQL Database.
My current method is to fetch this list from the DB when the user calls the function to load the page and then display it to them. However, if the user enter's incorrect data and the page must be reloaded with the validation errors, the variable that holds the data in the list seems to be cleared, and I must refetch the list data from the database before redisplaying the page.
I believe there's something in the documentation about how to set this variable to be permanently available but upon looking again, I had no luck in finding it.
Could anyone possibly point me in the right direction? It seems silly to me to have to need to refetch this data every time (I know that people won't be putting in wrong info often, but this will come in handy in a few situations).
NOTE: This is not an issue regarding remembering user selections.
this example is for a select drop down list using ci form helper
(i'm modifying this from another form so hopefully its all correct)
the Array of select values is: $categoryarray
the drop down field name is 'category'
the default value is $defaultcategory
a css class to style (bootstrap etc): $dropclass = 'class="input-medium"';
the line of code is:
form_dropdown('category',$categoryarray,set_value('category',$defaultcategory),$dropclass).form_error('category');
the form_error('category'); at the end is for showing a validation error message
and even though there is a default value - if the form fails validation from another field in the form - this will 'remember' what the user selected.
EDIT !
ok there is good and bad news.
bad news - if the categories are coming from a database then you need to get them again.
good news - CI remembers what category the user selected from the drop down list.
and the bad news actually isn't that big a deal - if you create the category array in your model. then its just one line of code to add to the validation.
// In the Model
function makedropdown() {
// get your category list
$cats = $this->getAllCategories() ;
$categoryarray = array();
// make the array
foreach ( $cats->result() as $row ) {
$categoryarray[$row->category] = $row->category ; }
return $categoryarray ;
}
someone has filled out the form, we run validation, validation fails. in the controller:
if ( $this->form_validation->run($formrules) == FALSE ) {
// get the categoryarray
$data['categoryarray'] = $this->categorymodel->makedropdown() ;
// load form again
$this->load->view( 'myform', $data ); }
So even though we are getting the categories again from the db to dynamically populate the select list - CI still remembers the users choice from the first time they did the form.
And what about a default category for the drop down? if its not going to change then it can be set as a config. if the category values are coming from a database and they can change - then the default category could be created in the model.
EDIT 2
gosh i always do this anyway so why didnt i think of it for this. so yeah this is yet another reason to make a specific method for showing your view
function _showCategoryForm(){
// get the categoryarray
$data['categoryarray'] = $this->categorymodel->makedropdown() ;
// anything else thats needed for the view
// load form view
$this->load->view( 'myform', $data ); }
NOW we dont have any repeated code, and its easy to customize the validation failure with an error message if needed.
// since i'm grinding on this - the validation should happen in a model
// and that method returns true or false
if ( $this->somemodel->validateCategoryForm() == FALSE ) {
// custom obnoxious error message
$this->formerrormessage = "What part of required is eluding you?" ;
$this->_showCategoryForm() ; }
This is much better because if the needs of your form changes - the change is only in one place. Also i added an underscore to remind us all that private methods are a good practice. And the form validation should be separate in a model, that is called by the controller.
You just need to set it as the default value, for example
<input type="text" name="username" value="<?php isset($_POST['username']) echo $username;?>" />
That way, $_POST['username'] will always be available.

Updating multiple page elements without refreshing the page using PHP & jQuery

I have a PHP page that uses jQuery to let a user update a particular item without needing to refresh the page. It is an availability update where they can change their availability for an event to Yes, No, or Maybe. Each time they click on the link the appropriate jQuery function is called to send data to a separate PHP file (update_avail.php) and the appropriate data is returned.
Yes
Then when clicked the params are sent to a PHP file which returns back:
No
Then, if clicked again the PHP will return:
Maybe
It all works fine and I'm loving it.
BUT--
I also have a total count at the bottom of the page that is PHP code to count the total number of users that have selected Yes as their availability by simply using:
<?php count($event1_accepted); ?>
How can I make it so that if a user changes their availability it will also update the count without needing to refresh the page?
My thoughts so far are:
$var = 1;
while ($var > 0) {
count($day1_accepted);
$var = 0;
exit;
}
Then add a line to my 'update_avail.php' (which gets sent data from the jQuery function) to make $var = 1
Any help would be great. I would like to stress that my main strength is PHP, not jQuery, so a PHP solution would be preferred, but if necessary I can tackle some simple jQuery.
Thanks!
In the response from update_avail.php return a JSON object with both your replacement html and your new counter value.
Or to keep it simple, if they click "yes" incriment the counter, if they click No or maybe and their previous action wasn't No or Maybe decrease the counter.
Assuming your users are logged into the system I'd recommend having a status field in the user table, perhaps as an enum with "offline", "available", "busy", "unavailable" or something similar and use the query the number of available users whilst updating the users status.
If you were to do this you'd need to include in extend your methods containing session)start() and session_destroy() to change the availability of the user to available / offline respectively
The best way is the one suggested by Scuzzy with some improvements.
In your php, get the count from the database and return a JSON object like:
{ count: 123, html: 'Yes' }
In your page, in the ajax response you get the values and update the elements:
...
success: function(data) {
$("#linkPlaceholder").html(data.html);
$("#countPlaceholder").html(data.count);
}
...

Symfony forms question (restoring selected value of a dynamically populated sfWidgetFormSelect widget)

I am using Symfony 1.3.2 with Propel ORM on Ubuntu 9.10.
I have developed a form that dynamically populates a select widget with cities in a selected country, using AJAX.
Before the data entered on the form is saved, I validate the form. If validation fails, the form is presented back to the user for correction. However, because the country list is dynamically generated, the form that is presented for correction does not have a valid city selected (it is empty, since the country widget has not changed yet).
This is inconvenient for the user, because it means they have to select ANOTHER country (so the change event is fired), and then change back to the original country they selected, then FINALLY select the city which they had last selected.
All of this is forced on the user because another (possibly unrelated) field did not vaildate.
I tried $form->getValue('widget_name'), called immediately after $form->bind(), but it seems (infact, IIRC, if form fails to validate, all the values are reset to null) - so that does not work.
I am currently trying a nasty hack which involves the use of directly accesing the input (i.e. tainted) data via $_POST, and setting them into a flash variable - but I feel its a very nasty hack)
What I'm trying to do is a common use case scenario - is there a better way to do this, than hacking around with $_POST etc?
What I do for this exact issue is that I post the form to the same action that generated it, and in that action, I grab any selected countries/regions/cities as POST variables and pass them back to the template (regardless of validation). In the template, I then use JQuery to set the select values to what they were. When validation passes, they get used. When not, they get passed back to template.
If you can tolerate a little PHP in your JQuery, you could do this in the template:
$(document).ready(function()
{
$("#country-select").val('<?php echo $posted_country; ?>');
});
If you use this approach, don't forget to initialise $this->posted_country in your template the first time around or Jquery will get confused.
I guess you could also use $this->form->setWidget(...)->setDefault(...) or something similar, but I havent found a way around using $_POST as accessing the elements seems to need binding the form otherwise.
UPDATED CODE IN RESPONSE TO COMMENTS BELOW:
if($_POST['profile']['country_id'] != '')
{
$this->posted_country = $_POST['profile']['country_id'];
$q = Doctrine_Query::create()
->select('c.city_id, c.city_name')
->from('City c')
->where('c.country_id = ?', $this->posted_country);
$cities = $q->execute(array(), Doctrine_Core::HYDRATE_NONE);
foreach($cities as $city) $list[$city[0]] = $city[1];
$this->form->setWidget('city_id', new sfWidgetFormChoice(array('choices' => array('' => 'Please select') + $list)));
}
So... I get the country from the post, I query db with that, get cities, and craft cities back into a dropdown. Then in the template, you can set a default selected city with something like $this->posted_city (which would be a POST variable too, if exists).

Categories