I am having a problem with the $_POST array that comes from my form.
Here is the code for my form:
<form id="form-add-client" method="post" data-ajax="false">
<input type="text" name="companyName" id="companyName" value="" placeholder="Company Name" />
<input type="text" name="email" id="email" value="" placeholder="Email" />
<br />
<input type="text" name="firstName" id="firstName" value="" placeholder="First Name" />
<input type="text" name="lastName" id="lastName" value="" placeholder="Last Name" />
<input type="tel" name="workPhone" id="workPhone" value="" placeholder="Work Phone" />
<input type="tel" name="mobilePhone" id="mobilePhone" value="" placeholder="Mobile Phone" />
<br />
<input type="text" name="streetAddress" id="streetAddress" value="" placeholder="Street Address" />
<input type="text" name="city" id="city" value="" placeholder="City" />
<input type="text" name="postalCode" id="postalCode" value="" placeholder="Postal Code" />
<br />
<input type="button" data-theme="b" name="submit" id="submit-add-client" value="Add Client" />
</form>
Here is the jQuery ajax code:
// Add Client
$(document).on('pagebeforeshow', '#add-client', function(){
$(document).on('click', '#submit-add-client', function() { // catch the form's submit event
if($('#companyName').val().length > 0 && $('#email').val().length > 0){
// Send data to server through the ajax call
// action is functionality we want to call and outputJSON is our data
// fetch the data for the form
var data = $('#form-add-client').serialize();
$.ajax({url: 'http://www.website.co.nz/goflowdata/addclient.php',
data: data,
type: 'post',
async: 'true',
dataType: 'json',
beforeSend: function() {
// This callback function will trigger before data is sent
$.mobile.loading('show'); // This will show ajax spinner
},
complete: function() {
// This callback function will trigger on data sent/received complete
$.mobile.loading('hide'); // This will hide ajax spinner
},
success: function (result) {
if(result.status) {
$.mobile.changePage("#add-client-success");
} else {
alert('Add client unsuccessful!');
}
},
error: function (request,error) {
// This callback function will trigger on unsuccessful action
alert('Network error has occurred please try again!');
}
});
} else {
alert('Please fill all necessary fields');
}
return false; // cancel original event to prevent form submitting
});
});
Here is the code from the addclient.php file:
<?php
header("Access-Control-Allow-Origin: *");
require_once("debug/chromephp.php");
$formData = $_POST;
ChromePhp::log($_POST);
require_once("config.php");
$companyName = $formData['companyName'];
$email = $formData['email'];
$firstName = $formData['firstName'];
$lastName = $formData['lastName'];
$workPhone = $formData['workPhone'];
$mobilePhone = $formData['mobilePhone'];
$streetAddress = $formData['streetAddress'];
$city = $formData['city'];
$postalCode = $formData['postalCode'];
$sql="INSERT INTO clients (companyName, email, firstName, lastName, workPhone, mobilePhone, streetAddress, city, postalCode) VALUES ('$companyName', '$email', '$firstName', '$lastName', '$workPhone', '$mobilePhone', '$streetAddress', '$city', '$postalCode')";
$result = mysql_query($sql);
if($result) {
// Success
$output = array('status' => true, 'massage' => 'Success!');
echo json_encode($output);
} else {
// Failed
$output = array('status' => false, 'massage' => 'Failed!');
echo json_encode($output);
}
?>
My problem is with the $formData['postalCode']; variable. It seems to be emtpy. I have used ChromePHP to try debug the issue and it returns the form data before being posted via ajax. In the serialized string the postalCode is there as you can see the console screenshot below. Can anyone see why this is happening? Any help is much appreciated.
When I use ChromePHP to log the contents of $_POST to the console I get this twice:
Object {companyName: "TestCompany", email: "test#email.com", firstName: "John", lastName: "Doe", workPhone: "01234567"…} city: "Testcity" companyName: "TestCompany" email: "test#email.com" firstName: "John" lastName: "Doe" mobilePhone: "012345678" postalCode: "" streetAddress: "7 Test Street" workPhone: "01234567" proto: Object
Screenshot:
Screenshot of MySQL table row:
Screenshot of console logged variables:
Related
referral-page.php
I have submitted email data and store in DB and then goto Primary page
<form action="store-db.php">
<input type="text" name="email" />
<input type="submit" value="Submit" />
</form>
I have stored email data in DB using ajax ( this was completed ). but I want to post email value to primary-page.php
primary-page.php ( email field should be prefilled if I come from referral otherwise it should be empty value )
<form action="thank-you.php">
<input type="text" name="name" value="" />
<input type="text" name="email" value="<?php echo !empty($_POST['email']) ? $_POST['email'] : ''; ?>" />
<input type="submit" value="Submit" />
</form>
After the ajax call to the DB has succeeded, why not just redirect to the thank you page, sending the email address in the query string ($_GET)?
Or maybe better: just submit to the php page and do the db storage there, before outputting "thank you" or "error"?
myself form action changed to primary-page.php
<form action="primary-page.php" id="primary_page">
<input type="text" name="email" />
<input type="submit" value="Submit" />
</form>
1) data validate and stored in DB using ajax ( store-db.php )
2) email value post to primary-page.php using function frm_submit()
var form_validate = $("#primary_page");
form_validate.validate({
rules: {
email: {
required: true,
email: true
}
},
submitHandler: function () {
var param = form_validate.serialize();
var btn_submit = $("#submit");
$.ajax({
type: "POST",
url: '/store-db.php',
data: param,
cache: false,
dataType: "json",
success: function (response) {
frm_submit();
}
});
});
function frm_submit() {
form = document.getElementById('primary_page');
form.submit();
}
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 hope this question is not too broad but it is not with a specific piece of code. Basically at random times and on random queries I have failures in my code. Most of the time it seems like it is on my INSERT calls. UPDATE and DELETE still work fine, but INSERT will fail across the entire page for several hours at a time before mysteriously working again. The page is only being used and tested by myself currently.
One of the sample queries.
PHP
session_start();
$poster = $_SESSION['login_user'];
$conn = new PDO("mysql:host=localhost;dbname=spectrum",'root', '1234abcd');
$u = $_POST['user'];
$p = md5($_POST['pass']);
$e = $_POST['email'];
$fn = $_POST['first_name'];
$ln = $_POST['last_name'];
$t = $_POST['type'];
$sql = "INSERT INTO users(id, user, pass, email, type, first_name, last_name, poster) VALUES ('', :user, :pass, :email, :type, :first, :last, :poster)";
$q = $conn->prepare($sql);
$q->bindParam(":user", $u);
$q->bindParam(":email", $e);
$q->bindParam(":pass", $p);
$q->bindParam(":type", $t);
$q->bindParam(":first", $fn);
$q->bindParam(":last", $ln);
$q->bindParam(":poster", $poster);
$q->execute();
echo json_encode('User has been added.');
This is done through an Ajax call.
JQuery
var request;
if (request) {
request.abort();
}
var $form = f;
var $inputs = $form.find("input, select, button, textarea");
var serializedData = $form.serialize();
$inputs.prop("disabled", true);
request = $.ajax({
url: site + "/backend/formup.inc.php",
type: "post",
dataType: 'json',
data: serializedData
});
request.done(function (data){
if(data.location){
window.location.replace(data.location);
}
else{
alert(data);
location.reload(false);
}
});
request.fail(function (jqXHR, textStatus, errorThrown){
alert(
"The following error occured: "+
textStatus, errorThrown
);
});
request.always(function (data) {
if(!data.tvar){
$inputs.prop("disabled", false);
}
});
Here is the HTML.
<form class="hidden" method="POST">
<input type="text" name="user" placeholder="Username" required/>
<input type="email" name="email" placeholder="Email" required/>
<input type="password" name="pass" placeholder="Password" required/>
<input type="text" name="first_name" placeholder="First Name" required/>
<input type="text" name="last_name" placeholder="Last Name" required/>
<input type="radio" name="type" value="0">Owner
<input type="radio" name="type" value="1">Employee
<input type="radio" name="type" value="2">Artist
<input type="radio" name="type" value="3">Venue
<input type="radio" name="type" value="4">Fan<br />
<input type="hidden" name="fname" value="add_user" />
<input type="submit" class="button" value="Add" />
</form>
Also I apologize if some formatting may be off with my questions. First time posting and getting used to the site.
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");"