Laravel request()->all() doesn't get all inputs - javascript

Sending data via POST form. Why doesn't the controller see all of the values? I've been playing around with the validation, so even setting those to 'required' doesn't change anything...
Form snippet:
<form action="{{ Protocol::home() }}/offers/make" method="POST" id="sendOffer">
<div class="modal-body">
<meta name="csrf-token" content="{{ csrf_token() }}">
<!-- Price -->
<div class="form-group" style="display:none;">
<label>{{ Lang::get('ads/show.lang_your_price') }}</label>
<input type="text" id="price_id" name="price" value="0">
<span class="help-block">{{ Lang::get('ads/show.lang_the_amount_required') }} <b>{{ Helper::getPriceFormat($ad->price, $ad->currency) }}</b></span>
</div>
<!-- location -->
<div class="form-group">
<label>location label</label>
<input type="text" placeholder="Andover MA" id="location_id" class="form-control" name="location_name">
</div>
<!-- Email Address -->
<div class="form-group">
<label>email label</label>
<input type="email" required="" placeholder="email" id="email_name" class="form-control" name="email_name">
</div>
<!-- Phone -->
<div class="form-group">
<label>phone label</label>
<input type="text" maxlength="12" placeholder="555-867-5309" id="friendNumber" class="form-control" name="phone_name">
</div>
<!--Time section-->
<div class="form-group">
<label>The time</label>
<input type="time" id="time_id" name="time_name"
min="9:00" max="18:00" required>
</div>
<!-- Post ID -->
<div class="form-group">
<label>{{ Lang::get('ads/show.lang_post_id') }} (for reference)</label>
<input type="text" readonly="" placeholder="{{ Lang::get('ads/show.lang_post_id') }}" id="postID" value="{{ $ad->ad_id }}" class="form-control" name="ad_id">
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success">{{ Lang::get('ads/show.lang_send_offer') }}</button>
</div>
</form>
Controller:
/**
* Make New Offer
*/
public function make(Request $request)
{
// Check ajax request
if ($request->ajax()) {
$rules = array(
'location_name' => '',
'email_name' => '',
'phone_name' => '',
'time_name' => '',
'ad_id' => 'required'
);
//run rules
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()) {
// error
$response = array(
'status' => 'error',
'msg' => __(print_r($request->all())),
);
return Response::json($response);
}else{
// Get Inputs
$price = $request->get('price');
$location_name = $request->input('location_name');
$email_name = $request->input('email_name');
$phone_name = $request->input('phone_name');
$time_name = $request->input('time_name');
$ad_id = $request->input('ad_id');
$input = $request->all();
//let's figure it out:
dd($input);
// Success test
$response = array(
'status' => 'success',
'msg' => __('return/success.lang_offer_submitted'),
);
return Response::json($response);
Output in console (only showing price and ad_id for some reason):
array:2 [
"price" => "0"
"ad_id" => "1988726232"
]
Route:
// Make an Offer
Route::post('offers/make', 'Ads\OffersController#make');

The error was a result of me forgetting to include these fields in the ajax request smh
var _root = $('#root').attr('data-root');
var offerPrice = document.getElementById('offerPrice').value;
var postID = document.getElementById('postID').value;
var location_name = document.getElementById('location_name').value;
var email_name = document.getElementById('email_name').value;
var phone_name = document.getElementById('phone_name').value;
var time_name = document.getElementById('time_name').value;
$.ajax({
type: "POST",
url: _root + '/offers/make',
data: {
price: offerPrice,
ad_id: postID,
location_name: location_name,
email_name: email_name,
phone_name: phone_name,
time_name: time_name
},

Related

Unsure how to send image to backend using express file upload,

someone please help im trying to submit details together with image to databasei need help in figuring this whole thing out
<form id="register-form">
<!-- <div class="form-group">
<input type="file" id="imageInput" accept="image/*">
</div> -->
<div class="form-group">
<div class="file-upload">
<div class="image-upload-wrap">
<input name = 'sampleFile' enctype = "multipart/form-data" class="file-upload-input" type='file' id="profilepic" onchange="readImage(this)"
accept="image/*" />
<div class="drag-text">
<h3>Drag and drop a file or select add Image</h3>
</div>
</div>
<div class="file-upload-content d-none">
<img class="file-upload-image" src="#" id="imgPreview" />
<div class="image-title-wrap">
<button type="button" onclick="removeUpload()" class="remove-image">Remove <span
class="image-title">Uploaded Image</span></button>
</div>
</div>
</div>
</div>
<div class="form-group">
<label for="title">title:</label>
<input type="text" class="form-control" id="title" required>
</div>
<div class="form-group">
<label for="description">Description:</label>
<input type="text" class="form-control" id="description" required>
</div>
<div class="form-group">
<label for="release">Release:</label>
<input type="text" class="form-control" id="release" required>
</div>
<div class="form-group">
<label for="lang">Language_id:</label>
<input type="text" class="form-control" id="lang" required>
</div>
<div class="form-group">
<label for="rental_duration">Rental Duration:</label>
<input type="text" class="form-control" id="rental_duration" required>
</div>
<div class="form-group">
<label for="rental_rate">Rental rate:</label>
<input type="text" class="form-control" id="rental_rate" required>
</div>
<div class="form-group">
<label for="length">Length:</label>
<input type="text" class="form-control" id="length" required>
</div>
<div class="form-group">
<label for="replacement_cost">Replacement Cost:</label>
<input type="text" class="form-control" id="replacement_cost" required>
</div>
<div class="form-group">
<label for="rating">Rating:</label>
<input type="text" class="form-control" id="rating" required>
</div>
<div class="form-group">
<label for="special_features">Special Features:</label>
<input type="text" class="form-control" id="special_features" required>
</div>
<div class="form-group">
<label for="category_id">Category ID:</label>
<input type="text" class="form-control" id="category_id" required>
</div>
<div class="form-group">
<label for="actors">Actors:</label>
<input type="text" class="form-control" id="actors" required>
</div>
<div class="form-group">
<label for="store_id">Store_id:</label>
<input type="text" class="form-control" id="store_id" required>
</div>
<button type="submit" class="btn btn-primary">Register</button>
<button type="reset" class="btn btn-primary ml-5">Reset</button>
<button type="button" class="btn btn-primary ml-5" id="Logout">Log Out</button>
<!-- <input type="reset" value="Reset"> -->
</form>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
crossorigin="anonymous"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
const baseUrl = "http://localhost:8081";
const token = localStorage.getItem("token");
const loggedInUserID = parseInt(localStorage.getItem("loggedInUserID"));
console.log(token, loggedInUserID)
// document.getElementById("addImage").addEventListener("change", function () {
// readImage(this);
//});
// document.getElementById("submitBtn").addEventListener("click", function () {
// var title = document.getElementById("title").value;
//});
function readImage(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
var imgPreview = document.getElementById("imgPreview");
imgPreview.src = e.target.result;
document.getElementById("imgPreview").style.display = "block";
};
reader.readAsDataURL(input.files[0]);
}
}
if (token === null || isNaN(loggedInUserID)) {
window.location.href = "http://localhost:3001/home";
} else {
$("#register-form").submit((event) => {
// prevent page reload
event.preventDefault();
const pic = $("#profilepic").val()
const title = $("#title").val();
const description = $("#description").val();
const release = $("#release").val();
const lang = $("#lang").val();
const rental_duration = $("#rental_duration").val();
const rental_rate = $("#rental_rate").val();
const length = $("#length").val();
const replacement_cost = $("#replacement_cost").val();
const rating = $("#rating").val();
const feature = $("#special_features").val();
const category_id = $("#category_id").val();
const actors = $("#actors").val();
const store_id = $("#store_id").val();
const requestBody = {
image: pic,
title: title,
description: description,
release_year: release,
language_id: lang,
rental_duration: rental_duration,
rental_rate: rental_rate,
length: length,
replacement_cost: replacement_cost,
rating: rating,
special_features: feature,
category_id: category_id,
actors: actors,
store_id: store_id
};
const formData = new FormData();
formData.append("image", pic);
formData.append("title", title);
formData.append("description", description);
formData.append("release_year", release);
formData.append("language_id", lang);
formData.append("rental_duration", rental_duration);
formData.append("rental_rate", rental_rate);
formData.append("length", length);
formData.append("replacement_cost", replacement_cost);
formData.append("rating", rating);
formData.append("special_features", feature);
formData.append("category_id", category_id);
formData.append("actors", actors);
formData.append("store_id", store_id);
let token = localStorage.getItem("token");
console.log(requestBody);
axios.post(`${baseUrl}/film`, formData, { headers: { "Authorization": "Bearer " + token } })
.then((response) => {
console.log(formData)
window.location.href = "http://localhost:3001/home";
})
.catch((error) => {
console.log(error);
if (error.response.status === 400) {
alert("Validation failed");
} else {
alert("Something unexpected went wrong.");
}
});
});
$("#Logout").click(function () {
window.localStorage.clear();
localStorage.removeItem("token");
localStorage.removeItem("loggedInUserID");
window.location.assign("http://localhost:3001/home");
});
}
</script>
const fileUpload = require("express-fileupload");
app.use(fileUpload());
app.post("/upload", (req, res) => {
if (!req.files || Object.keys(req.files).length === 0) {
return res.status(400).send("No files were uploaded.");
}
let sampleFile = req.files.sampleFile;
// Use the mv() method to place the file in a upload directory
sampleFile.mv("./upload/" + sampleFile.name, (err) => {
if (err) return res.status(500).send(err);
res.send("File uploaded!");
});
});
my html form code and app.js code i just cannot send image to database idk why, i try usin express file upload but the code just cannot insert it in. Someone, please help i have 48 hours left before my deadline please!!!!!! this is my first time doing this , someone guide me

Hidden input not submitted after updating value in on submit event

Using Laravel framework.
I don't get it. I have a hidden input with id = prime near the top.
<form name="paymentForm" action="/parking_302/upload_payment" method="POST" role="form" class="form-horizontal">
{{ csrf_field() }}
<input type="hidden" id="parking_lot_id" name="parking_lot_id" value="{{ $parking_lot_id }}">
<input type="hidden" id="booking_id" name="booking_id" value="{{ $booking_id }}">
<input type="hidden" id="Price" name="Price" value="{{ $Price }}">
<input type="hidden" id="prime" name="prime"> {{-- To be obtained --}}
<legend>電子發票 & TapPay 付款</legend>
<div class="form-group">
<label for="CustomerEmail" class="col-lg-3 col-md-3 col-xs-4">電子信箱</label>
<div class="col-lg-9 col-md-9 col-xs-8">
<input type="email" class="form-control" id="CustomerEmail" name="CustomerEmail" value="{{ old('CustomerEmail') }}">
</div>
</div>
<div class="form-group">
<label for="CustomerPhone" class="col-md-3 col-xs-4">手機號碼</label>
<div class="col-md-9 col-xs-8">
<input type="number" class="form-control" id="CustomerPhone" name="CustomerPhone" value="{{ old('CustomerPhone') }}">
</div>
</div>
<hr>
<div class="form-group">
<div class="col-md-offset-3 col-xs-offset-4 col-md-9 col-xs-8">
<select class="form-control" id="giveTongBian" name="giveTongBian">
<option value="no" #if(old('giveTongBian') === "no") selected #endif>不需統編</option>
<option value="yes" #if(old('giveTongBian') === "yes") selected #endif>輸入統編</option>
</select>
</div>
</div>
<div class="form-group" id="customerIdentGroup">
<label for="CustomerIdentifier" class="col-md-3 col-xs-4">統一編號</label>
<div class="col-md-9 col-xs-8">
<input type="text" class="form-control" id="CustomerIdentifier" name="CustomerIdentifier" value="{{ old('CustomerIdentifier') }}">
</div>
</div>
<div class="form-group" id="customerNameGroup">
<label for="CustomerName" class="col-md-3 col-xs-4">買受人</label>
<div class="col-md-9 col-xs-8">
<input type="text" class="form-control" id="CustomerName" name="CustomerName" value="{{ old('CustomerName') }}">
</div>
</div>
<div class="form-group" id="customerAddrGroup">
<label for="CustomerAddr" class="col-md-3 col-xs-4">地址</label>
<div class="col-md-9 col-xs-8">
<input type="text" class="form-control" id="CustomerAddr" name="CustomerAddr" value="{{ old('CustomerAddr') }}">
</div>
</div>
<div class="tappay-form col-xs-offset-1 col-xs-10">
<h4 style="color: darkkhaki;">信用卡</h4>
<div class="form-group card-number-group">
<label for="card-number" class="control-label"><span id="cardtype"></span>卡號</label>
<div class="form-control card-number"></div>
</div>
<div class="form-group expiration-date-group">
<label for="expiration-date" class="control-label">卡片到期日</label>
<div class="form-control expiration-date" id="tappay-expiration-date"></div>
</div>
<div class="form-group cvc-group">
<label for="cvc" class="control-label">卡片後三碼</label>
<div class="form-control cvc"></div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">Pay</button>
</div>
</div>
</form>
I then have a on submit event which does a few things. At the bottom is me updating the hidden input with id = prime.
$('form').on('submit', function (event) {
//Code for first part of form begin
var boolFlag = true; //Default is submit
var errorMsg = ""; //Initial message
//Begin validation
var numOfNonEmptyFields = 0;
if(document.forms["paymentForm"]["CustomerEmail"].value != "") {
numOfNonEmptyFields++;
}
if(document.forms["paymentForm"]["CustomerPhone"].value != "") {
numOfNonEmptyFields++;
}
if(numOfNonEmptyFields == 0) {
errorMsg += "請輸入至少一個電子信箱或手機號碼.\n";
boolFlag = false;
}
//End validation
//Final steps: overall error message + success or fail case
if(boolFlag == false) {
alert("錯誤:\n" + errorMsg);
return false;
}
//Code for first part of form end
// fix keyboard issue in iOS device
forceBlurIos()
const tappayStatus = TPDirect.card.getTappayFieldsStatus()
console.log(tappayStatus)
// Check TPDirect.card.getTappayFieldsStatus().canGetPrime before TPDirect.card.getPrime
if (tappayStatus.canGetPrime === false) {
bootbox.alert({
title: "錯誤訊息",
message: "取得不了Prime.",
buttons: {
ok: {
label: "OK",
className: "btn btn-primary"
}
}
});
return false
}
// Get prime
TPDirect.card.getPrime(function (result) {
if (result.status !== 0) {
bootbox.alert({
title: "錯誤訊息",
message: result.msg,
buttons: {
ok: {
label: "OK",
className: "btn btn-primary"
}
}
});
return false
}
$("#prime").val(result.card.prime);
})
})
I've tested the hidden input with alert($("#prime").val()) directly after and it seems updated, however after submission, my Controller receives the value as null while other hidden input values are correct. So I suspect it's something got to do with the on submit event.
Added id attribute to the form element:
<form id="paymentForm" name="paymentForm" action="/parking_302/upload_payment" method="POST" role="form" class="form-horizontal">
Removed type from the button and added id:
<button id="submit-btn" class="btn btn-default">Pay</button>
Introduced a new click listener:
$(document).on("click","#submit-btn", function(event){
event.preventDefault();
validateAndSendForm();
});
Introduced a new function for the final form submit:
function submitForm(){
//do other stuff here with the finalized form and data
//.....
$( "#paymentForm" ).submit();
}
And put all of your old things into a new function as well:
function validateForm(){
//Code for first part of form begin
var boolFlag = true; //Default is submit
var errorMsg = ""; //Initial message
...
...
...
}
// Get prime
TPDirect.card.getPrime(function (result) {
if (result.status !== 0) {
bootbox.alert({
title: "錯誤訊息",
message: result.msg,
buttons: {
ok: {
label: "OK",
className: "btn btn-primary"
}
}
});
return false;
}
$("#prime").val(result.card.prime);
//use when you are ready to submit
submitForm();
})
}
So, basically you will have a "submitForm" function that you can use whenever you are ready to submit the form.
Seems like TPDirect.card.getPrime is something that gets data asynchronously so the $('form').on('submit' function won't wait for it to finish.

how to autofill the form with ajax laravel?

I trying to autofill my form with cnic which i set as unique. If Cnic exists then all fields against the entered cnic with autofill. how i will do that? I have uploaded my form , jquery and controller. If you need more data to understand you can ask. I am getting data but form is not filling with ajax request. how to resolve this issue?
My form:
<form class="form" method="post" action="{{route('add.member')}}">
<input type="hidden" name="_token" value="{{csrf_token()}}">
<div class="row justify-content-md-center">
<div class="col-md-6">
<div class="form-body">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="name">Name</label>
<input type="text" id="name" class="form-control" placeholder="Enter Name" name="name" value="{{old('name')}}">
#if ($errors->has('name'))
<span style="color: red" class="help-block">{{ $errors->first('name') }}</span>
#endif
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="cnic">CNIC</label>
<input type="number" id="cnic" class="form-control" placeholder="Enter CNIC" name="cnic" value="{{old('cnic')}}">
#if ($errors->has('cnic'))
<span style="color: red" class="help-block">{{ $errors->first('cnic') }}</span>
#endif
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="mobile_number">Mobile Number</label>
<input type="number" id="mobile_number" class="form-control" placeholder="Enter Mobile Number" name="mobile_number" value="{{old('mobile_number')}}">
#if ($errors->has('mobile_number'))
<span style="color: red" class="help-block">{{ $errors->first('mobile_number') }}</span>
#endif
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="party_joining_year">Party Joining Year</label>
<input type="text" id="party_joining_year" class="form-control" placeholder="Enter Party Joining Year" name="party_joining_year" value="{{old('party_joining_year')}}">
#if ($errors->has('party_joining_year'))
<span style="color: red" class="help-block">{{ $errors->first('party_joining_year') }}</span>
#endif
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="qualification">Qualification</label>
<input type="text" id="qualification" class="form-control" placeholder="Enter Qualification" name="qualification" value="{{old('qualification')}}">
#if ($errors->has('qualification'))
<span style="color: red" class="help-block">{{ $errors->first('qualification') }}</span>
#endif
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="party_position">Party Position</label>
<input type="text" id="party_position" class="form-control" placeholder="Enter Party Position" name="party_position" value="{{old('qualification')}}">
#if ($errors->has('party_position'))
<span style="color: red" class="help-block">{{ $errors->first('party_position') }}</span>
#endif
</div>
</div>
</div>
<div class="form-group">
<label for="profession">Profession</label>
<input type="text" id="profession" class="form-control" placeholder="Enter Profession" name="profession" value="{{old('qualification')}}">
#if ($errors->has('profession'))
<span style="color: red" class="help-block">{{ $errors->first('profession') }}</span>
#endif
</div>
<div class="form-group">
<label for="district">District/Tahseel</label>
<input type="text" id="district" class="form-control" placeholder="Enter District" name="district" value="{{old('qualification')}}">
#if ($errors->has('district'))
<span style="color: red" class="help-block">{{ $errors->first('district') }}</span>
#endif
</div>
</div>
</div>
</div>
</form>
Ajax:
$("#cnic").focusout(function(e){
// alert($(this).val());
var cnic = $(this).val();
$.ajax({
type: "POST",
url: "{{route('get.all.fields')}}",
data: {'cnic':cnic},
dataType: 'json',
success : function(e) {
if(e===0){
$('.flash-message').html('Data not found');
$('#cnic').val('');
}
else {
$('.flash-message').html('');
r = $.parseJSON(e); //convert json to array
$('#name').autocomplete({
source: r.name,
}); //assign name value
$('#mobile_number').autocomplete({
source: r.mobile,
}); //assign email value
$('#party_joining_year').autocomplete({
source: r.party_joining_year,
}); //assign department value
$('#qualification').autocomplete({
source: r.qualification,
}); //assign department value
$('#party_position').autocomplete({
source: r.party_position,
}); //assign department value
$('#profession').val(r.profession).autocomplete({
source: r.profession,
}); //assign department value
$('#district').val(r.profession).autocomplete({
source: r.district,
}); //assign department value
$("#cnic").html(e);
}
}
});
});
</script>
My Controller:
public function getAllFields(Request $request)
{
$getFields = Member::where('cnic', $request->get('cnic'))->get(['name','mobile','party_joining_year','qualification','party_position','profession','district']);
return json_encode($getFields[0]['mobile']);
}
Route:
Route::post('/get_fields', 'MemberController#getAllFields')->name('get.all.fields');
In your controller you should be returning a proper JSON response
public function getAllFields(Request $request)
{
try {
$getFields = Member::where('cnic',$request->cnic)->first();
// here you could check for data and throw an exception if not found e.g.
// if(!$getFields) {
// throw new \Exception('Data not found');
// }
return response()->json($getFields, 200);
} catch (\Exception $e) {
return response()->json([
'message' => $e->getMessage();
], 500);
}
}
You shouldn't need to parse the json as
dataType: 'json'
will automatically expect JSON and the response variable will already be an object and you just need to map it like
$("#cnic").focusout(function(e){
// alert($(this).val());
var cnic = $(this).val();
$.ajax({
type: "POST",
url: "{{route('get.all.fields')}}",
data: {'cnic':cnic},
dataType: 'json',
success : function(data) {
$('#name').val(data.name);
$('#mobile_number').val(data.mobile);
$('#party_joining_year').val(data.party_joining_year);
...
},
error: function(response) {
alert(response.responseJSON.message);
}
});
});
You must read the laravel docs carefully. you don't need to get the inputs if you want a row from db.
The ->get() method returns an array of al the matched rows.
The ->first() method returns only the first row that matches the where clause.
So you must first correct the eloquent query. If you want to specify the columns that you want to retrieve from the database you must use the ->select method. But I don't see any reason to do that. so your controller must look like this:
public function getAllFields(Request $request)
{
$getFields = Member::where('cnic',$request->get('cnic'))->first();
return json_encode($getFields);
}
After that, you must decode the JSON array with jquery and add the values one by one.
$("#cnic").focusout(function(e){
// alert($(this).val());
var cnic = $(this).val();
$.ajax({
type: "POST",
url: "{{route('get.all.fields')}}",
data: {'cnic':cnic},
dataType: 'json',
success : function(e) {
if(e.length === 0){
$('.flash-message').html('Data not found');
$('#cnic').val('');
}
else {
$('.flash-message').html('');
r = $.parseJSON(e); //convert json to array
$('#name').val(r.name);
$('#mobile_number').val(r.mobile);
$('#party_joining_year').val(r.party_joining_year)
and so on...
$("#cnic").html(e); //-> I dont realy understand why you use this part of code?
}
}
});
});
Remember: you must get the fields from "r" object exactly by the name of database column that you retrieve the data.

Get values from HTML to javascript

So I have a simple form where I ask the user some info to register and make an account, this is the part of the form I am using to achieve that:
<form class="login-form2" action="index.html">
<div class="center sliding"><img style='width:20%; margin: 42%; margin-top: 8%; margin-bottom: 0%;'src="./images/logoTemporal.png"></div>
<div class="login-wrap">
<p class="login-img"><i class="icon_lock_alt"></i></p>
<!-- Name -->
<div class="input-group">
<span class="input-group-addon"><i class="icon_profile"></i></span>
<input type="text" id="Name" name="Name" class="form-control" placeholder="Name or Name.Corp" autofocus>
</div>
<!-- Email -->
<div class="input-group">
<span class="input-group-addon"><i class="icon_key_alt"></i></span>
<input type="email" id="Email" name="Email" class="form-control" placeholder="Email">
</div>
<!-- Passwrod -->
<div class="input-group">
<span class="input-group-addon"><i class="icon_key_alt"></i></span>
<input type="password" id="Password" name="Password" class="form-control" placeholder="Password">
</div>
<!-- Confirm password -->
<div class="input-group">
<span class="input-group-addon"><i class="icon_key_alt"></i></span>
<input type="password" class="form-control" placeholder="Confirm Password">
</div>
<!-- Tipo -->
<div class="item-content input-group-addon">
<div class="item-media"><i class="icon f7-icons">Tipo Usuario</i></div>
<br>
<div class="item-input">
<select id="Tipo" name="Tipo">>
<option value="0" selected>Empresa</option>
<option value="1">Usuario</option>
</select>
</div>
</div>
<br>
<!-- Button-->
<!-- <a class="btn btn-primary btn-lg btn-block" href="register.html">Register</a> -->
<p> <input type="button" class="btn btn-primary btn-lg btn-block" id="signup" value="Send"/></p>
</div>
</form>
I am trying to get the values into some variables in a jc, but for some reason I am not getting them:
$(document).ready(function() {
$("#signup").click(function() {
alert("Im in the function");//this is the only alert showing when I test the page...
//From here on it is not working
var Name = $('#Name').val();
var Email = $('#Email').val();
var Password = $('#Password').val();
var Tipo = $('#Tipo').val();
if (Name == '' || Email == '' || Password == '' || Tipo == '')
{ alert("please complete the information"); }
else {
// AJAX code to submit form.
$.ajax({
type: "POST",
url: 'dummy url',
crossDomain: true,
beforeSend: function(){ $mobile.loading('show')},
complete: function(){ $mobile.loading('hide')},
data: ({Name: Name, Email: Email, Password: Password, Tipo: Tipo}),
dataType: 'json',
success: function(html){
alert("Thank you for Registering with us! you
can login now");
},
error: function(html){
alert("Not Working");
}
});
}//else end
});
});
I am still trying to learn many things here but what I need to know is why the variables are not getting the values from the form, could be something dumb but I just cant see it... Would appreciate some help...
EDIT:
Adding my php code, now I get an error when trying to send the data to my host´s php using JSON, the javascript prints the "not working" alert, what I think is that my php is not really getting the json so its not working but im not 100% sure so here is my php code:
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, DELETE, OPTIONS');
require 'data/DataCollector.php';
$varData = json_decode($data);
$Name = $varData->Name;
$Email = $varData->Email;
$Password = $varData->Password;
$Tipo = $varData->Tipo;
$database = new DataCollector([
'database_name' => 'dummy url',
'server' => 'dummy server',
'username' => 'dummy username',
'password' => 'dummy password',
'charset' => 'utf8',
]);
if($_POST){
$database->insert("Usuario", [
"nombre" => $_POST[$Name],
"email" => $_POST[$Email],
"password" => $_POST[$Password],
"tipoUsuario" => $_POST[$Tipo]
]);
}
?>
I have never used JSON and I am trying to learn about it, there is probably A LOT of issues with my code but any help will be very much appreciated! thanks!
your dictionary does not seem to be correct.
try this:
data: {"Name": Name, "Email": Email, "Password": Password, "Tipo": Tipo}

How to Check database field through AJAX

i have created a form which is submitting data through ajax to the database.this works fine.how can i prevent entering sitename is already available in database.if that sitename already in database it should give error message.
Controller
public function user_add()
{
$data_save = array(
"Mnumber" => $this->input->post("Mnumber"),
"email" => $this->input->post("email"),
"fname" => $this->input->post("fname"),
"address" =>$this->input->post("address"),
"sitename" =>$this->input->post("sitename"),
/* "reqnum" => $this->input->post("reqnum"),*/
"title" => $this->input->post("title"),
"descr" => $this->input->post("descr"),
/*"payment" => $this->input->post("payment"),*/
"uniquekey" => $this->input->post("uniquekey")
/*"subscription" => $this->input->post("subscription"),
"email_sent" => $this->input->post("email_sent"),*/
);
if ($this->user_mod->AddUser($data_save)) {
echo "Successfully Saved";
}
else {
echo "error";
}
}
view
<script>
function save_user_new() {
var Mnumber = $('#Mnumber').val();
var email = $('#email').val();
var fname = $('#fname').val();
var address = $('#address').val();
var sitename = $('#sitename').val();
/*var reqnum = $('#reqnum').val();*/
var title = $('#title').val();
var descr = $('#descr').val();
var uniquekey = $('#uniquekey').val();
/*var subscription = $('#subscription').val();
var email_sent = $('#email_sent').val();
var payment = $('#payment').val();*/
if (sitename != "" && email != "") {
$.ajax({
type: "post",
async: false,
url: "<?php echo site_url('form_con/user_add'); ?>",
data: {
"Mnumber": Mnumber,
"email": email,
"fname": fname,
"address": address,
"sitename": sitename,
/*"reqnum": reqnum,*/
"title": title,
"descr": descr,
"uniquekey": uniquekey
/*"subscription": subscription,
"email_sent": email_sent,
"payment":payment*/
},
dataType: "html",
success: function (data) {
alert(data);
if (data == 'error') {
$('#success_msg').hide();
$('#error_msg1').show();
$('#error_msg1').html("Error : Something wrong.");
} else if (data == 'have') {
$('#success_msg').hide();
$('#error_msg1').show();
$('#error_msg1').html("Error : This Sitename is already exists.");
} else {
$('#error_msg1').hide();
$('#success_msg').show();
$('#success_msg').html("User details successfully saved.");
/*setTimeout(function() { location="features.php"},2000);*/
location.href = 'freecreate';
}
}
});
} else {
$('#success_msg').hide();
$('#error_msg1').show();
$('#error_msg1').html("Error : Please enter User Details.");
}
}
</script>
<form action="#" id="form_sample_1">
<div class="form-body">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Your First Name</label>
<input type="text" class="form-control" id="fname" name="fname" placeholder="Enter text" required="">
</div>
<div class="form-group">
<label class="control-label">Email Address</label>
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-envelope"></i></span>
<input type="email" class="form-control" id="email" name="email" placeholder="Email Address" required="">
</div>
</div>
<div class="form-group">
<label class="control-label">Your Mobile Number</label>
<input type="text" class="form-control" id="Mnumber" name="Mnumber" placeholder="Enter text" required="">
<!--<span class="help-block"> A block of help text. </span>-->
</div>
<div class="form-group">
<label class="control-label">Your Address</label>
<input type="text" class="form-control" id="address" name="address" placeholder="Enter text" required="">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Your Site Name</label>
<input type="text" class="form-control" id="sitename" name="sitename" placeholder="Enter text" required="">
<span class="help-block"> please enter the sitename only.if you wish to cretae site as john just type john.it will create the site automatically as john.site.mobi </span><br>
</div>
<div class="form-group">
<label class="control-label">Title of Your Web site</label>
<input type="text" class="form-control" id="title" name="title" placeholder="Enter text" required="">
</div>
<div class="form-group">
<label class="control-label">Description of Your Web Site</label>
<input type="text" class="form-control" id="descr" name="descr" placeholder="Enter text" required="">
<!--<input type="hidden" class="form-control" id="req_num" name="req_num" value="1" placeholder="Enter text">-->
<?php $uniquekey = md5(uniqid(rand(), true)); ?>
<input type="hidden" class="form-control" id="uniquekey" name="uniquekey" value="<?php echo $uniquekey ?>" placeholder="Enter text">
<!--<input type="hidden" class="form-control" id="subscription" name="subscription" value="1" placeholder="Enter text">
<input type="hidden" class="form-control" id="email_sent" name="email_sent" value="1" placeholder="Enter text">-->
<!--<input type="hidden" class="form-control" id="payment" name="payment" value="1" placeholder="Enter text">-->
</div>
</div>
<div class="form-actions right">
<!--<a class="btn green" onclick="save_user_new()">Submit</a>-->
<button type="submit" id="save_btn" class="btn green" onclick="save_user_new()">Submit</button>
<button type="button" class="btn default">Cancel</button>
</div>
</div>
</form>
Model
public function AddUser($data_save)
{
if ($this->db->insert('users', $data_save)) {
return true;
} else {
return false;
}
}
Write a validate function which actually checks for empty value in textbox and returns true or false. Consider below example.
function ValidateForm(form){
var valid=true;
$(form).find('input[type="text"]').each(function(){
if($(this).val()=="")
valid=false;
});
return valid;
}
function save_user_new() {
//getting all the values
//change if condition to
var form=$("#form_sample_1");
if(ValidateForm(form))
{
//continue with ajax
}
else
{
alert('Please fill all the fields');
return false;
}
}
Add jQuery required in save_user_new function
$("input").prop('required',true);
There is a couple of ways to do this.
As previously mentioned, write a validate method and check if the record already exists in the database.
Set the field to 'unique', and catch the error when you run the query,
also if you want to save yourself some time and coding write a helper function which will load all your post variables for your.
eg.
function LoadPostVariables($variables = [])
{
$CI = & get_instance();
$return_array = [];
foreach($variables as $key){
$p_val = $CI->input->post($key);
//you could perform some basic validation here
$return_array[$key]=$p_val;
}
}
$values = LoadPostVariables(['MNumber', 'email', 'fname', 'address', 'sitename', 'title', 'descr', 'uniquekey']);
public function AddUser($data_save)
{
$check = false;
$query = "SELECT * FROM users WHERE email='$data_save' LIMIT 1";
$result = mysqli_query($dbc, $query);
if($result){
while($row = mysqli_fetch_assoc($result)){
$check = true;
}
}
if($check == false){
// add data
}else{
echo 'Email already found'; exit();
}
}

Categories