How to dynamically show error messages through PHP - javascript

I am creating a PHP login script. So far I have only worked on the registration.
My question is, how can I handle validation in PHP without refreshing the page? I want to output the feedback that the user has entered information wrongly, but I don't want to refresh the page. This is because I am using AJAX, so I want it to output on the page.
Is this possible?
See here, if you "sign up" without filling in any of the boxes it shows you some error messages. The problem is that it reloads the page as it does it. Is there a way to not reload the page and still show this data?
http://marmiteontoast.co.uk/fyp/login-register/test/index.php
This is an example of the if statement for just the username. This is repeated with all the other fields too:
if(isset($_POST['username'])){
$username = mysql_real_escape_string(trim($_POST['username']));
if(strlen($username) > 3){
// passed
if(strlen($username) < 31){
// passed
} else {
$_SESSION['status']['register']['error'][] = 'The Username is greater than 30 characters.';
}
} else {
$_SESSION['status']['register']['error'][] = 'The username is less than 4 characters.';
}
} else {
$_SESSION['status']['register']['error'][] = 'The Username is not entered.';
}
Once it passes all the validation it does:
header('Location:index.php');
And the errors are output on the index page by:
<?php
if(isset($_SESSION['status']['register']['error'])){
?>
<div class="alert alert-error">
<p><strong>There's a problem!</strong><br /><br />
<?php
foreach($_SESSION['status']['register']['error'] as $error){
// Outputs list of all errors, breaks to new line
echo $error . '<br />';
}
?>
</p>
1. Is it possible to output these dynamically with PHP?
2. Could I do the validation on the front end, then just pass it to the PHP to pass to the database?
2a. How would I handle running a username exists check if I do it front end?

This is something I actually just made the other day!
I have a file called "register.js", a file called "register_process.php" and some html.
How my server is set up:
html_docs (www):
ajax:
register_process.php
js:
register.js
jquery-1.6.2.js
register.html
so within my register.html, my code looks like such:
<script type="text/javascript" src="js/md5.js"></script> <!-- this is in my head -->
<script type="text/javascript" src="js/jquery-1.6.2.js"></script>
<!-- everything else is in my body -->
<div id="error_message" style="display: none;">
</div>
<div id="register_div">
<input type="text" name="username" id="username"><br>
<input type="password" name="password" id="password"><br>
<input type="submit" name="submitbutton" id="reg_button" value="Register" onclick="AttemptRegisterAjax(); return false;"><br>
</div>
This calls the function inside of my register.js file. That functions looks like such:
function AttemptAjaxRegister(){
var url = "ajax/register_process.php?";
url += "time=" + (new Date().getTime()) + "&un=";
var username_ele = document.getElementById("reg_username");
var password_ele = document.getElementById("reg_password");
var error_ele = document.getElementById("error_message");
var username = username_ele.value;
var password = password_ele.value;
if((username.length >=4) && (password.length >= 4)){
url += encodeURIComponent(username) + "&pw=" + encodeURIComponent(password);
console.log(url);
$.get(url, function(data, status, xhr){
data = data.trim();
if(data != "true"){
error_ele.innerText = data;
error_ele.style = "display: block;";
}else{
window.location = "/profile.php";
}
});
}else{
error_ele.innerText = "Please make sure your password and username are both 4 characters long";
error_ele.style = "display: block;";
}
}
now, inside of your php, you'll want to set everything up just like how you had it to register, but you'll want to actually just call die($YourErrorMessage); or if the registration was successful, die("true");

Not directly, you will need to use another tool for that, most likely Javascript.
Yes but that would be a terible practice. the best way to validate on both.
2a. I believe you would need to use a database.
thsi tutorials might help you out.
Easy jQuery Ajax PHP Contact Form
How to create a Sign Up form registration with PHP and MySQL

Related

Echo HTML from PHP to display in ajax request on webpage

I have a list of scientific publications displayed on a website and would like to load additional content as the user arrives at the end of a list of 10 publications, and presses a button to load another 10 publications.
I make an Ajax call to load the next 10 publications
I am trying to display html code that is echo-ed from php script but I cannot appear to display the html. In the console, I am getting '1' as a value for my HTML. I do not understand:
1. why I am getting the value of '1';
2. Also, is it good practice to echo HTML to be displayed via javascript?
JS (AJAX call):
var resp = xmlhttp.responseText;
var respArray = resp.split('|');
var response = respArray[1];
var publicationList = respArray[0];
var currentHTML = document.getElementById('showPubs').innerHTML;
if(response == '1'){
console.log('more publications available');
var currentHTML = document.getElementById('showPubs').innerHTML;
document.getElementById('showPubs').innerHTML += publicationList;
}else{
document.getElementById('showPubs').innerHTML += '<div id="noMorePub">No more publications</div>';
}
PHP:
$recentPublications .= '
<div id="pub'.$articleID.'" class="pub20">
<div class="divImg">'.$avatarPathHTML.'</div>
<div class="contentPub">
<div class="datepub">
<div class="fullName"><a class="sfullNme" href="2profile.php?username='.$articleUsername.'">'.$fullname.'</a></div>
<div class="date">'.$submitDate.'</div>
</div>
<div class="divLink">
'.$articleTitle.'
</div>
<div class="authorString">'.$author_string.'</div>
</div>
<hr class="pubSeparator">
</div>
';
echo $recentPublications.'|1';
I guess better idea is not use this dirty hack
echo $recentPublications.'|1';
and
var respArray = resp.split('|');
var response = respArray[1];
var publicationList = respArray[0];
if(response == '1'){
You can just check length of response. if length of response is equal 0 bytes then other publications are not available.
The good practice is to separate concerns. Therefore, in your example, server-side script should only provide data to be displayed (ex. JSON via), and frontend should make AJAX call to specific endpoint.

Why won't this script load?

I have a contact us form:
<form id="contactus" name="contactus" action="html_form_send1.php" method="post">
<label for="name">Name:</label><br />
<input type="text" id="name" name="name" maxlength="50" size="59" autofocus required/><br /><br />
<label for="email">E-Mail Address:</label><br />
<input type="email" id="email" name="email" maxlength="50" size="59" required/><br /><br />
<label for="question">Question:</label><br />
<textarea id="question" name="question" maxlength="1000" cols="50" rows="6" required></textarea><br /><br />
<input class="c1_scButton" type="submit" id="submit" name="submit" value="Send" />
</form>
I want it to call my mail PHP script using this AJAX code:
var msg = "";
name = $("#name").val();
email = $("#email").val();
question = $("#question").val();
//validation phase
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([az]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
};
function validate(e) {
if (name == "") {
msg = " valid name";
}
if (!isValidEmailAddress(email)) {
msg = msg + " valid email address";
}
if (question == "") {
msg = msg + " valid question or comment";
}
}
// on submit, Validate then post to PHP mailer script
$(function() {
$("#contactus").on('submit', function(e) {
e.preventDefault();
validate(e);
if msg != "" {
e.preventDefault();
$("#alert").html "Please enter a" + msg;
} else {
$.post('/html_form_send1.php', $(this).serialize(), function(data) {
$('#alert').css(color: "black")
$('#alert').html("<h2>Thank you for contacting us!</h2>")
.append("<p>We will be in touch soon.</p>");
}).error(function() {
$('#alert').css(color: "red")
$('#alert').html("<h2>Something went wrong. Your Question was not submitted. /n</h2>").append("<p>Please try again later or email us at <a href=href="
mailto: support# allegroaffiliates.com ? Subject = Contact Us Form " target="
_top ">support#allegroaffiliates.com.</a> </p>");
});
};
});
});
The script is called at the bottom of the HTML page after another script, but it isn't loading. I suspect that it is due to a code error but I can't find the error. Can anybody give me an idea why it wont load?
Side note: I do know that HTML5 will validate the script, but I have the validation in place for when HTML5 is not available.
Thank you for your help.
A few troubleshooting suggestions:
(1) When specifying the ajax processor file, either this $.post('html_form_send1.php' or this $.post('./html_form_send1.php' but not this $.post('/html_form_send1.php'
(2) Instead of using the shortcut code $.post(), use the full form of the method until you are pretty good at it:
var varvalue = $('#first_name').val();
var nutherval = $('#last_name').val();
$.ajax({
type: 'post',
url: 'your_secondary_file.php',
data: 'varname=' +varvalue+ '&lname=' +nutherval,
success: function(d){
if (d.length) alert(d);
}
});
(3) Disable validation routine until the rest is working, then work on that when you know everything else is working correctly
(4) Change your ajax processor file html_form_send1.php to just echo back a response to make sure you've got the AJAX working. Then, once you get the response, change it to echo back the variable you are sending. Then build it into the final desired product. But initially, something dead simple, like this:
your_secondary_file.php:
<?php
$first_name = $_POST['varname'];
$last_name = $_POST['lname'];
echo 'Received: ' .$first_name .' '. $last_name;
die();
(5) Instead of using .serialize(), initially just grab one or two field values manually and get that working first. Note that .serialize() produces JSON data, while the simpler method is straight posted values, as in sample code in this answer. Get it working first, then optimize.
(6) Note that the dataType: parameter in the AJAX code block is for code coming back from the PHP side, not for code going to the PHP side. Also note that the default value is html, so if you aren't sending back a JSON object then just leave that param out.
(7) In my AJAX and PHP code samples above, note the correlation between the javascript variable name, how it is referenced in the AJAX code block, and how it is received on the PHP side. I was very deliberate in the names I chose to allow you to follow the var name => var value pairing all the way through.
For example, the input field with ID first_name is stored in a variable called varvalue (dumb name but intentional). That data is transmitted in the AJAX code block as a variable named varname, and received on the PHP side as $_POST['varname'], and finally stored in PHP as $first_name
Review some simple AJAX examples - copy them to your system and play with them a bit.

JQuery: Post variable to the second file, and when the enter key pressed, the web will direct me to the first search result page

I created an instant search similar to google search using JQuery.
Q1.
The post to search.php using search function searchq() then print out the returned result works fine, but the createq() function doesn't work at all, it didn't triggered when I using alert() to test, any ideas on how to fix it so the variable txt could be post to create_object.php (which has been post successfully to search.php).
Q2
I want to create a function that allow the user to direct to the first search result(which is anchored with an url) when the enter is pressed, any idea how to achieve this? I tried something but it messed up.
Note that I didn't include the connect to database function here. Coz I think the database username and password setting would be different to yours.So please create your own if you want to test it. The mysql is set with a table is called "objects", and it has one column named "name".
Thanks in advance!
<html>
<!-- google API reference -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<!-- my own script for search function -->
<center>
<form method="POST">
<input type="text" name="search" style="width:400px " placeholder="Search box" onkeyup="searchq();">
<input type="submit" value=">>">
<div id="output">
</div>
</form>
</center>
<!-- instant search function -->
<script type="text/javascript">
function searchq(){
// get the value
var txt = $("input").val();
// post the value
if(txt){
$.post("search.php", {searchVal: txt}, function(result){
$("#search_output").html(result+"<div id=\"create\" onclick=\"creatq()\"><br>Not found above? Create.</div>");
});
}
else{
$("#search_output").html("");
}
};
function createq(){
// allert for test purpose
alert("hi");
$.post( "create_object.php",{creatVal:txt} );
}
</script>
</html>
PHP file (search.php)
<?php
if(isset($_POST["searchVal"])){
//get the search
$search=$_POST["searchVal"];
//sort the search
$search=preg_replace("#[^0-9a-z]#i","",$search);
//query the search
echo "<br/>SELECT * from objects WHERE name LIKE '%$search%'<br/>";
$query=mysqli_query($conn,"SELECT * from objects WHERE name LIKE '%$search%'") or die("could not search!");
$count=mysqli_num_rows($query);
//sort the result
if($count==0){
$output="there was no search result";
}
else{
while($row=mysqli_fetch_assoc($query)){
$object_name=$row["name"];
$output.="<div><a href='##'".$object_name."</a></div>";
}
}
echo $output;
}
?>
php file (create_object.php)
<?php
if(isset($_POST["createVal"])){
$name=$_POST["createVal"];
var_dump($name);
}
?>
Two questions in one!
Q1: The problem appears to be a misspelling in the onclick function:
onclick=\"creatq()\"
should be
onclick=\"createq()\"
Q2: Pressing enter will submit the form, so you use the submit handler to catch the enter press then redirect:
$(function() { //shorthand document.ready function
$('form ').on('submit', function(e) { //use on if jQuery 1.7+
e.preventDefault(); //prevent form from submitting
$url = $('#search_output div:first a').attr('href'); // find first link
window.location.href = $url; // redirect
});
});
(credit to this answer for most of the work)

Automatically update another page without refreshing

I have this problem on how I could automatically update my webpage without refreshing. Could someone suggest and explain to me what would be the best way to solve my problem? Thanks in advance
add.php file
In this php file, I will just ask for the name of the user.
<form id="form1" name="form1" method="post" action="save.php">
<input type="text" name="firstname" id="firstname"/>
<input type="text" name="lastname" id="lastname"/>
<input type="submit" name="add" id="add" value="add"/>
</form>
save.php In this file, I will just save the value into the database.
$firstname=isset($_POST['firstname'])? $_POST['firstname'] : '';
$lastname=isset($_POST['lastname'])? $_POST['lastname'] : '';
$sql="Insert into student (sno,firstname,lastname) values ('','$firstname','$lastname')";
$sql=$db->prepare($sql);
$sql->execute();
studentlist.php In this file, i want to display the name I enter
$sql="Select firstname, lastname from student";
$sql=$db->prepare($sql);
$sql->execute();
$output="The List of students <br></br>";
while($result=$sql->fetch(PDO::FETCH_ASSOC))
{
$output.="".$result['firstname']." ".$result['lastname']."<br></br>";
}
Problem
When the two pages is open, I need to refresh the studentlist.php before i can see the recently added data.
thanks :D
You'll want to use ajax and jquery. Something like this should work:
add.php
add to the head of the document:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){//loads the information when the page loads
var saveThenLoad = {
url: "save.php",//the file sending data to
type: 'POST',//sends the form data in a post to save.php
dataType: 'json',
success : function(j) {
if(j.error = 0){
$("#student_info").html(j.info);//this will update the div below with the returned information
} else {
$("#student_info").html(j.msg);//this will update the div below with the returned information
}
}
}
//grabs the save.submit call and sends to the ajaxSubmit saveThenLoad variable
$("#save").submit(function() {
$(this).ajaxSubmit(saveThenLoad);
return false;
});
//grabs the submit event from the form and tells it where to go. In this case it sends to #save.submit above to call the ajaxSubmit function
$("#add").click(function() {
$("#save").submit();
});
});
</script>
<!-- put this in the body of the page. It will wait for the jquery call to fill the data-->
<div id="student_info">
</div>
I would combine save and studentlist into one file like this:
$return['error']=0;
$return['msg']='';
$firstname=isset($_POST['firstname'])? $_POST['firstname'] : '';
$lastname=isset($_POST['lastname'])? $_POST['lastname'] : '';
$sql="Insert into student (sno,firstname,lastname) values ('','$firstname','$lastname')";
$sql=$db->prepare($sql);
if(!$sql->execute()){
$return['error']=1;
$return['msg']='Error saving data';
}
$sql="Select firstname, lastname from student";
$sql=$db->prepare($sql);
if(!$sql->execute()){
$return['error']=1;
$return['msg']='Error retrieving data';
}
$output="The List of students <br></br>";
while($result=$sql->fetch(PDO::FETCH_ASSOC))
{
$output.="".$result['firstname']." ".$result['lastname']."<br></br>";
}
$return['$output'];
echo json_encode($return);
Does this need to be in three separate files? At the very least, could you combine add.php and studentlist.php? If so, then jQuery is probably the way to go. You might also want to use some html tags that would make it easier to dynamically add elements to the DOM.
Here's the combined files:
<form id="form1" name="form1">
<input type="text" name="firstname" id="firstname"/>
<input type="text" name="lastname" id="lastname"/>
<input type="submit" name="add" id="add" value="add"/>
</form>
The List of students <br></br>
<ul id="student-list">
<?php
//I assume you're connecting to the db somehow here
$sql="Select firstname, lastname from student";
$sql=$db->prepare($sql);
$sql->execute();
while($result=$sql->fetch(PDO::FETCH_NUM)) //this might be easier to output than an associative array
{
//Returns will make your page easier to debug
print "<li>" . implode(" ", $result) . "</li>\n";
}
?>
</ul>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(function(){
$('#form1').submit(function(event){
event.preventDefault();
//submit the form values
var firstname = $('#firstname').val();
var lastname = $('#lastname').val();
//post them
$.post( "test.php", { firstname: firstname, lastname: lastname })
.done( function(data) {
//add those values to the end of the list you printed above
$("<li>" + firstname + ' ' + lastname + "</li>").appendTo('#student-list');
});
});
});
</script>
You might want to do some testing in in the $.post call above to make sure it was handled properly. Read more about that in the docs.
If you really need three files, then you'll might need to use ajax to do some sort of polling on studentlist.php using setTimeout to see if you have any new items.
The cheap-way is using a meta-refresh to refresh your page (or use JavaScript setInterval and ajax).
The more expensive way is having a Realtime JavaScript application. Look at Socket.IO or something like that.

woocommerce POSTing data before javascript (jQuery) finishes

i have a custom gateway (which works perfectly), the problem is when a customer buys something for the first time, there is some token than needs to be generated with the card info, the thing is that just before that token is generated, the form tries to submit, but an error is displayed saying that "the object could not be found", so, no refresh and nothing, if i press again the submit button (or "place order" button) everything works!.
i believe that by that second time, the token is generated and in the corresponding hidden field:
here is my code, hope somebody could help me :S
HTML (from the chrome inspector):
<input type="hidden" name="card-name" data-conekta="card[name]">
<input type="hidden" name="exp-month" data-conekta="card[exp_month]">
<input type="hidden" name="exp-year" data-conekta="card[exp_year]">
<input type="hidden" name="conektaTokenId" value="">
<input type="hidden" name="conektaCustId" value="false">
Javascript
jQuery(window).load(function() {
var form;
var first_name;
var last_name;
var cvc;
jQuery('form[name="checkout"]').submit(function(event) {
jQueryform = jQuery(this);
Conekta.setPublishableKey(jQuery('input[name="pbkey"]').val());
console.log('entro');
if( jQuery('input[name="conektaCustId"]').val()=="true" && jQuery('input[name="conektaTokenId"]').val().substr(0,4)!="tok_"){
console.log('entro');
first_name = jQuery('#billing_first_name').val();
last_name = ' ' + jQuery('#billing_last_name').val();
expiry = jQuery('#conekta_card-card-expiry').val().replace(/ /g, '').split("/");
jQuery('input[name="card-name"]').val( first_name + last_name );
jQuery('input[name="exp-month"]').val( Number(expiry[0]));
jQuery('input[name="exp-year"]').val( Number(expiry[1]));
jQueryform.prepend('<span class="card-errors"></span>');
Conekta.token.create(jQueryform, conektaSuccessResponseHandler, conektaErrorResponseHandler);
woocommerce_order_button_html
return false;
}
else{
return;
}
});
var conektaSuccessResponseHandler= function(response){
var token_id = response.id;
jQuery('input[name="conektaTokenId"]').val(token_id);
}
var conektaErrorResponseHandler= function(response){
jQueryform.find('.card-errors').text(response.message);
}
});
i have found the solution, you have to add the class processing to the checkout form and just when you finished procesing your data to be send to wherever you need to (usually wordpress/woocommerce), remove that class so the form can submit the new data.

Categories

Resources