Why won't this script load? - javascript

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.

Related

Javascript XMLHttpRequest and Jquery $.ajax both are returning the current page HTML code

The problem
Hello i want to start off hoping all of y'all are having a fantastic day! I'm having a really weird problem that i have never came across before. I have a bootstrap navigation form with two fields, an input for a email and a field for the password.
When the user submits the form it calls to an AddEventListener which is waiting for a click of the login button. and after that is called it validates(Server Side Validation) the form of the entered data. After both the email_validated and password_validated is both equal to true it calls to a function called checkLogin(email, password){email = entered email in field, password = entered password in field}. In the checkLogin function it called to a JQuery $.ajax({}) call which sends the email and password field to a php document located in /scripts/checkLogin.php. However instead of it returning "Hello"(For testing purposes) is returns the entire HTML code for the current page(As shown above)
JQuery $.ajax({}) code
Here i have the code for the $.ajax({}) call.
Console
I'm not getting any errors in the console except for the XHR finished loading: POST
Other Pictures
Here are some other pictures that i am including to hopefully give yall a better idea of the structure.
Note
I just want to add that i have checked Stackoverflow for similar problems and other people have had this problem but they solutions did not work on my code. I have also tried just using a regular XMLHttpRequest and the same problem occurred, i'm honestly not sure what is wrong with the code for i have never had this problem before. Thank you for taking the time to read this i appreciate any help that i can get with solving this. I'm not the best with $.ajax({}) or XMLHttpRequest and im willing to make any changed to the code to try to get this to work. Below is my code for the entire javascript validation(server side).
Code
<form class="form-inline my-2 my-lg-0" method="POST">
<input class="form-control mr-sm-2 nav-login" type="text" autocomplete="off" placeholder="Email" name="email" value="trest#gmail.com" id="email">
<input type="password" name="password" autocomplete="off" class="form-control nav-login mr-sm-2" placeholder="Password" value="password" name="password" id="password">
<button class="btn btn-success my-2 my-sm-0 nr" type="button" name="login_button" id="login_button">Login <i class="fas fa-sign-in-alt"></i></button>
</form>
<script>
document.getElementById('login_button').addEventListener('click', (e) => {
e.preventDefault();
// const email_regex = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
let email_validated = true;
let password_validated = true;
let email = document.getElementById('email');
let password = document.getElementById('password');
// let email_length = email.value.length;
// let password_length = password.value.length;
//
//
// if(!email_length){
// email.classList.add('is-invalid');
// }else{
// if(!email_regex.test(email.value)){
// email.classList.add('is-invalid');
// }else{
// email.classList.remove('is-invalid');
// email.classList.add('is-valid');
// email_validated = true;
//
// }
// }
// if(!password_length){
// password.classList.add('is-invalid');
// }else{
// password.classList.remove('is-invalid');
// password.classList.add('is-valid');
// password_validated = true;
// }
if(email_validated === true && password_validated === true){
checkLogin(email.value, password.value);
}
});
function checkLogin(email, password){
$.ajax({
type: "POST",
url: '/scripts/checkLogin.php',
data: {
'email': email,
'password': password
},
contentType: "application/json; charset=utf-8",
success: (result) => {
alert(result);
}
});
}
</script>
Links to the other StackOverFlow question
ajax returns the html code of current page instead of json
I was the way my server was configured with xammp as t.niese said.

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.

How to dynamically show error messages through PHP

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

Form submission without blank data

I have a form in at the footer section of my website, it email me basic user inputs and the current page url. Here is its layout
<form action="" id="myform" method="post">
<input name="name" type="text" class="transparent-white-border-input" placeholder="Your Name">
<input name="email" type="text" class="transparent-white-border-input" placeholder="Email Address">
<textarea name="enquiry" class="transparent-white-border-input" rows="5" placeholder="Enquiry or Project Details...."></textarea>
<input name="from_page" type="hidden" value="<?=$_SERVER[HTTP_HOST].$_SERVER[REQUEST_URI]?>">
<div class="send-btn">Send</div>
</form>
following is my ajax submission and javascript validation
<script>
$('.send-btn').click(function(){
if(validateForm()){
$.ajax({
url: "/ajax-request.php?function=footer_contact_form",
type: "post",
data: $("#myform").serialize(),
success: function() {
$(".emocean-contact-form .section-container").html('<h1 style="color: #fff; text-align:center;">Thank you for contacting us, we will get back to you shortly.</h1>');
}
});
}
else{
alert("Please fill in all fields in blue.");
}
})
function validateForm(){
a=document.forms["myform"]["name"];
a_regex=/\S/;
d=document.forms["myform"]["email"];
d_regex=/^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; //stackoverflow standard
e=document.forms["myform"]["enquiry"];
e_regex= /\S/;
valid = true;
$("#myform input").css("backgroundColor", "");
$("#myform textarea").css("backgroundColor", "");
function check (origin, regex){
if (!regex.test(origin.value)){
origin.style.backgroundColor="blue";
valid = false;
}
}
check(a, a_regex);
check(d, d_regex);
check(e, e_regex);
return valid;
}
</script>
Here comes the problem. I tested in different devices and different browsers but everything works fine. But when it goes live sometimes it emails me with proper information just like in the test, but sometimes it sends me an email with all post data blanks, even $_post["from_page"] is blank. Don't know how this happened. I tried to submit this form in browser console to bypass the validation, while most fields are blank $_post["from_page"] still has value.
Also it didn't look like spam robots things since the blank emails are now coming quite often and they are all in random time. As mentioned before, some emails are not blank. Anyone with any idea what could possibly the problem be?
This post might or might not be relevant.

Categories

Resources