I have a registration form that on submit, validates passwords and domain names that match respectively. If true, I am trying to then check that the domain name does not exist in the DB via an ajax request.
<div class="grid-6">
<p>
<label for="First Name">First Name:</label>
<input type="text" name="first_name" placeholder="James" required value="">
<label for="Last Name" name="lastname">Last Name:</label>
<input type="text" name="last_name" placeholder="Brown" required value="">
<label for="email">Email:</label>
<input type="email" name="email" placeholder="email#email.com" required value="">
<label for="Preferred Password">Preferred Password:</label>
<input id="og_password" type="password" name="password" required value="">
<label for="Confirm Password">Confirm Password</label>
<input id="confirm_password" type="password" name="password_confirm" required value="">
</p>
</div><!-- /grid-6-->
<div class="grid-6">
<p>
<label for="Domain Name">Domain Name <span class="italic red">(lowercase letters and numbers only - no spaces):</span></label>
<input id="domain_name_a" type="text" name="domain_name_a" placeholder="mystudioname" required value="">
<label for="Domain Name">Confirm Domain Name:</label>
<input id="domain_name_b" type="text" name="domain_name_b" placeholder="mystudioname" required value="">
</p>
</div>
JS
unction passwordMatch() {
var pass1 = $('#og_password').val();
var pass2 = $('#confirm_password').val();
var domain1 = $('#domain_name_a').val();
var domain2 = $('#domain_name_b').val();
var error = true;
if(pass1 != pass2){
alert("Your passwords do not match!");
return false; // cancel form submission if passwords don't match
}
if(domain1 != domain2){
alert("Your domain names do not match!");
return false;
}
//no errors check DB for domain exits
checkDomain(domain1);
}
function checkDomain(domain) {
alert(domain);//testing only
$.ajax({
type:"POST",
url: "/actions/domain.php",
data: {
domain:domain
}
success: function(result) {
if(result = false) {
alert(result);
} else {
alert(result);
}
}
});
}
Things run well through the alert(domain), which is returning the correct value. The problem is somewhere in the domain.php file, the return, or just plain incorrect use of the .ajax. Here is the php
PHP
<?php
require_once("../includes/connection.php");
$domainName = $_POST['domain'];
$sql = "SELECT domain_name
FROM user
WHERE domain_name = '{$domainName}'
";
$run = mysqli_query($mysqli, $sql);
$result = mysqli_fetch_assoc($run);
echo $result['domain_name'];
?>
Any help on where I have gone wrong on this would bea appreciated.
Thanks!
Looks like you are missing a comma between the data and success function in your ajax Request.
data: {
domain:domain
} , < -- Missing comma here
success: function(result) {
If that was a direct copy of your code - you're missing a comma in the ajax call after data: {}, <- right there.
Also, remove the if...else from the success statement, because it's not done right as well (you're testing a value by using ONE equal sign, and all that does is just declare the value you're trying to test against). Just try: success: function(result) { console.log(result); alert(result); } and see what you get.
For some odd reason jQuery does not recognise the file by a shortened url.
The solution is to type the whole url -> not only smtg/smtg.php but http://www.domain.com/smtg/smtg.php.
Also, you could try to send the data in json format by adding the following line of code into your ajax call: "dataType: 'json'," and then outputting from a php file like this: "echo json_encode("return value");"
Related
using code from here
https://www.codingsnow.com/2021/01/create-php-send-email-contact-form.html
<h4 class="sent-notification"></h4>
<form id="myForm">
<h2>Send an Email</h2>
<label>Name</label>
<input id="name" type="text" placeholder="Enter Name">
<br><br>
<label>Email</label>
<input id="email" type="text" placeholder="Enter Email">
<br><br>
<label>Subject</label>
<input id="subject" type="text" placeholder=" Enter Subject">
<br><br>
<p>Message</p>
<textarea id="body" rows="5" placeholder="Type Message"></textarea><!--textarea tag should be closed (In this coding UI textarea close tag cannot be used)-->
<br><br>
<button type="button" onclick="sendEmail()" value="Send An Email">Submit</button>
</form>
<script src="http://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
function sendEmail() {
var name = $("#name");
var email = $("#email");
var subject = $("#subject");
var body = $("#body");
if (isNotEmpty(name) && isNotEmpty(email) && isNotEmpty(subject) && isNotEmpty(body)) {
$.ajax({
url: 'sendEmail.php',
method: 'POST',
dataType: 'json',
data: {
name: name.val(),
email: email.val(),
subject: subject.val(),
body: body.val()
}, success: function (response) {
$('#myForm')[0].reset();
$('.sent-notification').text("Message Sent Successfully.");
}
});
}
}
function isNotEmpty(caller) {
if (caller.val() == "") {
caller.css('border', '1px solid red');
return false;
} else
caller.css('border', '');
return true;
}
</script>
what do i need to change in both the files for it to work
right now when i put two contact forms on one page, both top working even though individually both of them are working..I have tried changes variable names and function names but cant figure out the error. in the network tab it says "failed, something went wrong"
I'll explain it with an example. Let's say you have a function to add up two numbers:
function add() {
return 3 + 5;
}
If you ever need to add a different set of numbers, this function is useless. However, if you pass variable information as function argument you have a multiple purpose function:
function add(a, b) {
return a + b;
}
As about assigning IDs in HTML, it adds more burden than benefits. Compare these two snippets and figure out which one is easier to use and extend:
jQuery(function ($) {
$("#input1, #input2, #input3").each(function (index, input) {
console.log(input.value);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input id="input1" value="One">
<input id="input2" value="Two">
<input id="input3" value="Three">
</form>
jQuery(function ($) {
$("input").each(function (index, input) {
console.log(input.value);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input value="One">
<input value="Two">
<input value="Three">
</form>
This is just an example to illustrate the point. The usual way to handle a form element is to assign it a name rather than an ID.
I have a form that is posting data to a php api file. I got the api working and it creates an account but want to use AJAX to send the data so I can make the UX better. Here is what the PHP sending script is expecting:
<form id="modal-signup" action="/crowdhub_api_v2/api_user_create.php" method="post">
<div class="modal-half">
<input type="text" placeholder="First Name" name="user_firstname"></input>
</div>
<div class="modal-half">
<input type="text" placeholder="Last Name" name="user_lastname"></input>
</div>
<div class="modal-half">
<input type="Radio" placeholder="Gender" value="male" name="user_gender">Male</input>
</div>
<div class="modal-half">
<input type="Radio" placeholder="Gender" value="female" name="user_gender">Female</input>
</div>
<div class="modal-half">
<input type="date" placeholder="DOB" name="user_dateofbirth"></input>
</div>
<div class="modal-half">
<input type="text" placeholder="Zip Code" name="user_zip"></input>
</div>
<input class="end" type="email" placeholder="Email" name="user_email"></input>
<input type="password" placeholder="Password" name="user_password"></input>
<input type="submit"></input>
</form>
PHP
$user_firstname = $_REQUEST['user_firstname'];
$user_lastname = $_REQUEST['user_lastname'];
$user_email = $_REQUEST['user_email'];
$user_password = $_REQUEST['user_password'];
$user_zip = $_REQUEST['user_zip'];
$user_dateofbirth = $_REQUEST['user_dateofbirth'];
$user_gender = $_REQUEST['user_gender'];
$user_phone = $_REQUEST['user_phone'];
$user_newsletter = $_REQUEST['user_newsletter'];
How would I send this via ajax? I found this script that says it worked, but it did not create a user. I imagine its sending the data not the right way.
Ajax
$(function () {
$('#modal-signup').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '/api_v2/api_user_create.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
First, let's get ajax in order:
$(function () {
$('#modal-signup').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
//same url as the form
url: '/crowdhub_api_v2/api_user_create.php',
data: $('form').serialize(),
//we need a variable here to see what happened with PHP
success: function (msg) {
//output to the page
$('#output').html(msg);
//or to the console
//console.log('return from ajax: ', msg);
}
});
});
});
Somewhere on the form page, add a div with id output:
<div id="output></div>
Finally, in api_user_create.php, there is an error:
$user_gender = $_REQUEST['user_gender'];
//these last two do not exist on the form
$user_phone = $_REQUEST['user_phone'];
$user_newsletter = $_REQUEST['user_newsletter'];
I'd recommend some error-checking on the PHP side, like this
if(!empty($_REQUEST)){
//For developing, you may want to just print the incoming data to see what came through
//This data returns into the msg variable of the ajax function
print_r($_POST);
//once that's good, process data
if(isset($_REQUEST['user_gender'])){
$user_gender = $_REQUEST['user_gender'];
}
//etc... as before
} else {
echo 'no data received';
}
I am creating an employee hierarchy and while setting up the superior for new employee I would like to check if the employee already exists in database ... but :) I would like to do it with AJAX to know it realtime without sending the form ..
I have absolutely no idea how to do it, since I am a newbie to Laravel ..
***UPDATED BASED ON ADVICES:***
I have a form in add_emp.blade.php:
<form action="../create_employee" method="POST">
<button class="button" type="submit" style="float:right"><span>Save</span></button>
<div style="clear:both"></div>
<fieldset>
<legend>Personal data</legend>
<label for="first_name">First name:</label><input type="text" class="add_emp required" name="first_name" value="" /><br />
<label for="last_name">Last name:</label><input type="text" class="add_emp required" name="last_name" value="" /><br />
<label for="superior">Superior:</label><input type="text" class="add_emp" name="superior" value="" id="superior_list" /><br />
</fieldset>
</form>
Here is a script in add_employee.blade.php
<script type="text/javascript">
$('#superior_list').blur(function(){
var first_name = $('#superior_list');
$.ajax({
method: "POST",
url: '/check_superior',
data: { superior: superior }
})
.done(function( msg ) {
if(msg == 'exist') {
//employee exists, do something...
alert( "good." );
} else {
//employee does not exist, do something...
alert( "bad." );
}
});
})
</script>
route for handling the superior:
Route::post('check_superior', 'EmployeeController#check_superior');
This is the Controller function check_superior:
public function check_superior(Request\AjaxUserExistsRequest $request){
if(Employee::where('superior','=',$request->input('superior'))->exists()){
return "exist";
}else{
return "not exist";
}
}
But still not working ... can you advice where could be the issue?
*** FINAL SOLUTION ***
Form:
<form action="../create_employee" method="POST">
<button class="button" type="submit" style="float:right"><span>Save</span></button>
<div style="clear:both"></div>
<fieldset>
<legend>Personal data</legend>
<label for="first_name">First name:</label><input type="text" class="add_emp required" name="first_name" value="" /><br />
<label for="last_name">Last name:</label><input type="text" class="add_emp required" name="last_name" value="" /><br />
<label for="superior">Superior:</label><input type="text" class="add_emp" name="superior" value="" id="superior_list" /><span id="check-superior-status"></span><br />
</fieldset>
</form>
Add to app.blade.php
meta name="csrf-token" content="{{ csrf_token() }}"
Controller
public function check_superior(Request $request){
if(Employee::where('first_name','=',$request->input('superior_fname'))
->where('last_name','=',$request->input('superior_lname'))
->exists()){
return "exist";
}else{
return "not exist";
}
}
final emp.blade.php AJAX script
// place data after SEPERIOR selection
$( "#superior_list" ).blur(function() {
var sup_list = $(this).val();
var sup_arr = sup_list.split(' ');
var superior_fname = sup_arr[0];
var superior_lname = sup_arr[1];
var superior = superior_fname+" "+superior_lname;
// control print out
//$('#check-superior-status').text(superior);
// get real data
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
method: "POST",
url: '/check_superior',
data: { superior_fname: superior_fname, superior_lname: superior_lname },
/* // debug only
error: function(xhr, status, error){
$('#check-superior-status').text(xhr.responseText);
},
*/
success: function(data){
$('#check-superior-status').text(data);
}
})
});
This works like a charm :) thank you guys .. hope this will help someone ..
First make the request.
php artisan make:request AjaxUserExistsRequest
Then open the request file (App\Http\Requests) and find the following:
public function validate(){
return [
//rules
];
}
This is where you would stick your validation rules so you can check against the form elements being submit.
Then you should use dependency injection to force your request into the first argument of the user_exists() function:
public function user_exists(Requests\AjaxUserExistsRequest $request){
return User::where('first_name', $request->first_name)->first();
}
This will return nullif no user exists, otherwise we don't care about the response.
Finally, of course we need our route.
Route::post('employee_exists', 'EmployeeController#user_exists');
Lastly, we'll go ahead and capture the form submit and check if the user exists with our jQuery.
$('#employee_form').submit(function(e){
e.preventDefault();
var first_name = $('#first_name').val(),
$this = this; //aliased so we can use in ajax success function
$.ajax({
type: 'POST',
url: '/employee_exists',
data: {first_name: first_name},
success: function(data){
if(data == null){
//then submit the form for real
$this.submit; //doesn't fire our jQuery's submit() function
} else {
//show some type of message to the user
alert('That user already exists!');
}
}
});
});
The below will give alert message the user already exists! if the first_name exists in your db or it will give alret nothing.(if you want to check with superior change the code vice versa)
first make sure you have jquery.min.js in your public folder.
Now in blade.php add id for first_name, last_name, and superior as below:
<form action="../create_employee" method="POST">
<button class="button" type="submit" style="float:right"><span>Save</span></button>
<div style="clear:both"></div>
<fieldset>
<legend>Personal data</legend>
<label for="first_name">First name:</label><input type="text" id="first_name" class="add_emp required" name="first_name" value="" /><br />
<label for="last_name">Last name:</label><input type="text" id="last_name" class="add_emp required" name="last_name" value="" /><br />
<label for="superior">Superior:</label><input type="text" class="add_emp" name="superior" value="" id="superior_list" /><br />
</fieldset>
</form>
<script>
$(document).ready(function(){
$("#superior_list").blur(function(){
var first_name = $('#first_name').val();
var last_name = $('#last_name').val();
var superior = $('#superior_list').val();
$.ajax({
type: 'POST',
url: '/check_superior',
data: {first_name: first_name, last_name: last_name, superior: superior},
success: function(data){
if(data == 0){
alert('nothing');
} else {
alert('the user already exists!');
}
}
});
});
});
</script>
and in your route.php
Route::post('/check_superior', array('as' => '', 'uses' => 'EmployeeController#check_superior'));
in EmployeeController.php
public function check_superior(){
// can get last_name, superior like first_name below
$first_name = Input::get('first_name');
$data = YourModel::where('first_name',$first_name)->get();
return count($data);
}
It should work. if it doesn't please show us your error
Give your form an id:
<form action="../create_employee" method="POST" id="employee_form">
<button class="button" type="submit" style="float:right"><span>Save</span></button>
<div style="clear:both"></div>
<fieldset>
<legend>Personal data</legend>
<label for="first_name">First name:</label><input type="text" class="add_emp required" name="first_name" id="first_name" value="" /><br />
<label for="last_name">Last name:</label><input type="text" class="add_emp required" name="last_name" value="" /><br />
<label for="superior">Superior:</label><input type="text" class="add_emp" name="superior" value="" id="superior_list" /><br />
</fieldset>
</form>
your js will look like this
$('#employee_form').submit(function(e){
e.preventDefault();
var first_name = $('#first_name');
$.ajax({
method: "POST",
url: "checkUserExistence.php",
data: { first_name: first_name }
})
.done(function( msg ) {
if(msg == 'exist') {
//employee exists, do something...
} else {
//employee does not exist, do something...
}
});
})
also add csrf_field in your form to generate token, and use this token while sending request.
in your form:
{{ csrf_field() }}
in your ajax request:
$.ajax({
headers: {'X-CSRF-Token': $('input[name="_token"]').val()},
//other data....
})
you can also do it with meta teg. in your head teg
<meta name="csrf-token" content="{{ csrf_token() }}">
in your request
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content');
//other data...
}
});
Form:-
<form name="form">
<div class="formfieldContainer">
<label> Email :</label>
<div class="login_wrapper loginContainer">
<span> </span>
<input type="email" id="email" required name="user_email" autofocus="autofocus" placeholder="Enter Email Address"/>
</div>
</div>
<div class="formfieldContainer">
<label> Password :</label>
<input type="password" name="user_password" placeholder="Enter Password"/>
</div>
<input type="button" name= "submit" value="submit" id="submit_login"/>
</form>
AJAX:-
$("#submit_login").click(function(){
var username=$('input[name=user_email]').val();
var password=$('input[name=user_password]').val();
$.ajax({
type: "POST",
url: "newExam.php",
data:{name: username,
pwd: password},
cache: false,
success: function(dataa) {
if(dataa)
{
console.log(dataa);
if(dataa==0)
{ $('form').effect( "shake" ); $('p.error').show(); $("#submit_login").val('Login')
alert('nodata');
}
else if(dataa==1){
window.location.href="user.php";
}
}
}
});// ajax
});
PHP:-
<?php
include('db.php');
$email_php = $_POST['name'];
$pwd_php=$_POST['pwd'];
$sql = "select name from user where email='$email_php' and password='$pwd_php'";
$result = mysqli_query($conn,$sql);
$num_rows= mysqli_num_rows($result);
if($num_rows>0){
$_SESSION['login_user']= $email_php;
echo '1';
}
else{
echo '0';
}
?>
I need the page to redirect to user.php when logged in successfully. But i am getting the following error:
Notice: Undefined index: name in C:\xampp\htdocs\demo\newExam.php on line 3
Notice: Undefined index: pwd in C:\xampp\htdocs\demo\newExam.php on line 4
How to overcome it?
Yo should be redirecting it from php page (using headers)instead of using window.location.href
You can use this method if you don't want to use php.
$.extend( {
redirectPost: function(location, args)
{
var form = '';
$.each( args, function( key, value ) {
form += '<input type="hidden" name="'+key+'" value="'+value+'">';
});
$('<form action="'+location+'" method="POST">'+form+'</form>').submit();
} });
Usage
$.redirectPost("user.php", {'key1': 'data1', 'key2': 'data2'});
Credit - https://gist.github.com/aabril/e6b96379ab0eb151a179
I have a popup form which i am submitting through AJAX and PHP. The problem is the form is submitting successfully but script is neither uploading pic nor inserting pic name to mysql.
If i don't use a popup form with the same script than it's working properly.
Any help ??
Html form:
<form action="" method="post" class="signupform">
<label>Full Name</label>
<input type="text" Placeholder="Name" name="name" pattern="[A-Z a-z]{3,25}" title="Name should contain 3 to 25 characters" Required="required"/>
<br />
<label>Email Address</label>
<input type="email" Placeholder="Email-id" name="email" Required="required"/>
<br />
<label>Password</label>
<input type="password" Placeholder="Password" name="pass" pattern="[A-Za-z0-9#]{6,15}" title="Password should be alphanumeric. Only A-Z,a-z,0-9 and # allowed and it must be 6 to 15 digits long." Required="required"/>
<br />
<label>Sex</label>
<span>Male<input type="radio" name="sex" checked="checked" value="M"/> Female<input type="radio" name="sex" value="F"/></span>
<br />
<label>City</label>
<input type="text" Placeholder="City" name="city" Required="required"/>
<br />
<label>Profile pic</label>
<input type="file" Placeholder="Profile pic" name="dp"/>
<br />
<div class="checkbox">
<input id="send_updates" type="checkbox" Required="required"/>
<label for="send_updates">I accept the terms and conditions</label>
</div>
<div class="action_btns">
<div class="one_half"><i class="fa fa-angle-double-left"></i> Back</div>
<div class="xyx xyxy"><input type="submit" value="Register" name="submitp" class="signsub"/></div>
</div>
</form>
Ajax:
$(document).ready(function()
{
$('.signsub').click(function()
{
$.ajax({
type: "POST",
url: "ajaxsignup.php",
data: $('.signupform').serialize(),
cache: false,
success: function(data) {
if (data)
{
$('.user_register').hide();
$(".error").html(" Thank you for joining us you are successfully logged in !!").show().delay(30000).fadeOut('slow');
window.location.reload().delay(30000);
}
else
{
$(".signsub").val('Register')
$(".error").html("<span style='color:#cc0000'>Error:</span> Invalid username and password. ");
}
}
});
return false;
});
});
ajaxsignup.php
<?php
session_start();
include('includes/db.php');
$name=$_POST['name'];
$pass=$_POST['pass'];
$email=$_POST['email'];
$sex=$_POST['sex'];
$city=$_POST['city'];
$dp=$_FILES['dp']['name'];
include('includes/uploadfiledp.php');
$queryb="INSERT INTO login VALUES('','$name','$pass','$email','$sex','$city','$chckfil')";
$resultb=mysql_query($queryb);
if($resultb)
{
$_SESSION['user']=$email;
echo ok;
}
?>
uploadfiledp.php
$allowedExts = array("jpeg", "jpg");
$extension = end(explode(".", $_FILES["dp"]["name"]));
if (in_array($extension, $allowedExts))
{
if ($_FILES["dp"]["error"] > 0)
{
echo "Return Code: " . $_FILES["dp"]["error"] . "<br>";
}
else
{
if (file_exists("images/" . $_FILES["dp"]["name"]))
{
$b=explode(".", $_FILES["dp"]["name"]);
$first=$b[0];
$ext=$b[1];
$i=1;
do
{
$fname1=$first;
$fname1=$fname1.$i;
$i++;
$chckfil=$fname1.".".$ext;
}
while(file_exists("images/" . $chckfil));
move_uploaded_file($_FILES["dp"]["tmp_name"],
"images/" . $chckfil);
}
else
{
move_uploaded_file($_FILES["dp"]["tmp_name"],
"images/" . $_FILES["dp"]["name"]);
$chckfil=$_FILES["dp"]["name"];
}
}
}
else
{
echo "Invalid file";
}
The .serialize() method creates a text string in standard URL-encoded notation. It can act on a jQuery object that has selected individual form controls.Data from file select elements is not serialized.Something like this might help u..
You can make use of Formdata() ,
$(document).ready(function()
{
$("#formID").submit(function(){
{
var formData = new FormData($(this)[0]);
$.ajax({
type: "POST",
url: "ajaxsignup.php",
data: formData,
contentType: false,
processData: false,
cache: false,
success: function(data) {
if (data)
{
$('.user_register').hide();
$(".error").html(" Thank you for joining us you are successfully logged in !!").show().delay(30000).fadeOut('slow');
window.location.reload().delay(30000);
}
else
{
$(".signsub").val('Register')
$(".error").html("<span style='color:#cc0000'>Error:</span> Invalid username and password. ");
}
}
});
return false;
});
});
FYI
FormData
ProcessData is set to false so that it prevents jQuery from automatically transforming the data into a query string