CodeIgniter and base_url(), form submission issue - .htaccess

my earlier issue was solved which spoke about base_url duplication in CodeIgniter. However, after editing base_url() as base_url = "http://example.com/myapp/", form submission does not load my thank you page. I have checked it with Firebug, there is a Response: 200 OK coming. But my view register-done.php does not load no matter what I do. The form just stays there. Doesn't move, though the data goes to database and registered. Before this fix, it was working fine. here is the html of form-submission:
<div class="section-title">Personal Details</div>
<form id="profile-image-form" method="post" action="<?= base_url() ?>signup" enctype="multipart/form-data">
<img src="<?= asset_url() ?>css/images/grey-bg.png" width="128" class="profile-pic"/>
<button type="button" id="upload-supplier-user-image-button" class="no-btn-style" onclick="$('#profile_image').click()">Upload User Image</button>
<img style="display:none; width: 35px;" src="<?= asset_url()?>images/upload-loading.gif" id="supplier-profile-upload-gif"/>
<input type="file" name="image" id="profile_image" style="display: none"/>
</form>
<form id="register-company-form" method="post" action="<?= base_url() ?>signup/supplier" enctype="text/plain">
<input type="hidden" name="image" id="image" value=""/>
<input type="text" id="first_name" name="first_name" class="text-field"/>
<input type="text" id="last_name" name="last_name" class="text-field"/>
<input type="text" id="user_name" name="user_name" class="text-field"/>
<input type="email" id="personal_email" name="personal_email" class="text-field"/>
<input type="password" id="password" name="password" class="text-field"/>
<input type="password" id="confirm_password" name="confirm_password" class="text-field"/>
<input type="text" id="job" name="job" class="text-field"/>
<input type="submit" name="sign-up-personal" id="sign-up-personal" class="btn-purple supplier-login-btn" value="Sign Up"/>
<input type="text" id="company_name" name="company_name" class="text-field"/>
<input type="text" id="address_one" name="address_one" class="text-field"/>
<input type="text" id="address_two" name="address_two" class="text-field"/>
<input id="autocomplete" placeholder="Enter your city" type="text" class="text-field" required autocomplete="off"/>
<input id="city" type="hidden" value="" name="city" required>
<input id="country" type="hidden" value="" name="country" required>
<button type="button" class="btn-purple supplier-login-btn" onclick="$('#company_logo_file').click()">Browse</button>
<input type="hidden" id="company_logo" name="company_logo" value=""/>
<textarea id="company_description" name="company_description" class="textarea-field"></textarea>
<input type="text" id="company_website" name="company_website" class="text-field"/>
<input type="email" id="company_email" name="company_email" class="text-field"/>
<input type="text" id="company_telephone" name="company_telephone" class="text-field"/>
<button type="button" class="btn-purple supplier-login-btn" onclick="$('#trade_license').click()">Browse</button>
<input type="file" id="trade_license" name="trade_license" class="text-field hidden" accept="application/pdf"/>
<input type="checkbox" name="terms" value="yes"/> By Signing up, I agree to <span class="terms-of-service">terms of service</span>
<input type="submit" name="sign-up" id="sign-up" class="btn-purple supplier-login-btn" value="Sign Up"/>
</form>
<form id="company_logo_form" method="post" action="" enctype="multipart/form-data">
<input type="file" style="display: none" name="company_logo_file" id="company_logo_file" accept="image/*"/>
</form>
<script type="text/javascript">
$.validator.addMethod("valueNotEquals", function(value, element, arg){
return arg != value;
}, "Value must not equal arg.");
var validator = $('#register-company-form').validate({
/* some validation */
submitHandler: function(form) {
var formData = new FormData($(form)[0]);
$.ajax({
type: $(form).attr('method'),
url: $(form).attr('action'),
data: formData,
dataType : 'json',
cache: false,
contentType: false,
processData: false
})
.done(function (response) {
window.location.href = '<?= base_url() ?>supplier/successful';
});
});
</script>
and here is the signup controller. I have changed nothing, but it stopped sending form to the database :( Any help will be highly appreciated. #DFriend
<?php
class Signup extends CI_Controller {
private $return_data = NULL;
private $return_status = 200;
private $return_message = NULL;
public function index(){
$this->load->model('CaptchaModel');
$this->load->helper('Captcha');
$cid = $this->input->post('cid');
$captcha = $this->input->post('captcha');
$captcha_exist = $this->CaptchaModel->check_captcha($captcha, $cid);
if($captcha_exist)
{
$this->load->model('RegisterModel');
$image = parent::check_user_input($this->input->post('image'));
$title = $this->input->post('title');
$first_name = $this->input->post('first_name');
$last_name = $this->input->post('last_name');
$user_name = $this->input->post('user_name');
$email = $this->input->post('email');
$password = $this->input->post('password');
$gender = $this->input->post('gender');
$mobile = parent::check_user_input($this->input->post('mobile'));
$dob_day = parent::check_user_input($this->input->post('dob_day'));
$dob_month = parent::check_user_input($this->input->post('dob_month'));
$dob_year = parent::check_user_input($this->input->post('dob_year'));
if($dob_day != '' && $dob_month != '' && $dob_year != ''){
$date_of_birth = new DateTime($dob_year . '-' . $dob_month . '-' . $dob_day);
}
else
{
$date_of_birth = '';
}
$country = parent::check_user_input($this->input->post('country'));
$city = parent::check_user_input($this->input->post('city'));
$interests = $this->input->post('interests');
$habits = $this->input->post('habits');
$comment = parent::check_user_input($this->input->post('comments'));
$newsletter = parent::check_user_input($this->input->post('newsletter'));
$registration = $this->RegisterModel->register($image, $title, $first_name, $last_name, $user_name, $email, $password, $mobile, $date_of_birth, $country, $city, $interests, $habits, $comment, $newsletter, $gender);
if($registration == -1)
{
$this->return_status = 400;
parent::returnJson($this->return_data, $this->return_status, $this->return_message);
}
elseif
($registration == -2)
{
$this->return_status = 401;
parent::returnJson($this->return_data, $this->return_status, $this->return_message);
}elseif
($registration){
$this->load->library('session');
$user_data = array('login' => 1,'uid' => $registration);
$this->session->set_userdata($user_data);
parent::returnJson($this->return_data, $this->return_status, $this->return_message);
}
else
{
$this->return_status = 500;
parent::returnJson($this->return_data, $this->return_status, $this->return_message);
}
}
else
{
$this->return_status = 600;
parent::returnJson($this->return_data, $this->return_status, $this->return_message);
}
}
public function supplier()
{
$file_element_name = 'trade_license';
$this->load->model('RegisterModel');
$profile_image_form = $this->input->post('image');
$title = $this->input->post('title');
$first_name = $this->input->post('first_name');
$last_name = $this->input->post('last_name');
$user_name = $this->input->post('user_name');
$email = $this->input->post('personal_email');
$password = $this->input->post('password');
$job = $this->input->post('job');
$company_name = $this->input->post('company_name');
$address_one = $this->input->post('address_one');
$address_two = $this->input->post('address_two');
$country = $this->input->post('country');
$city = $this->input->post('city');
$company_description = $this->input->post('company_description');
$company_website = $this->input->post('company_website');
$company_email = $this->input->post('company_email');
$company_telephone = $this->input->post('company_telephone');
$company_logo = $this->input->post('company_logo');
$trade_license = '';
$config['upload_path'] = './assets/license/';
$config['allowed_types'] = 'pdf';
$config['remove_spaces'] = TRUE;
$this->load->library('upload', $config);
if (!$this->upload->do_upload($file_element_name))
{
$status = 'error';
$msg = $this->upload->display_errors('', '');
}
else
{
$data = $this->upload->data();
$status = "success";
$msg = '';
$trade_license = $data['file_name'];
}
$profile_image = $profile_image_form;
$config['upload_path'] = './assets/profile/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['remove_spaces'] = TRUE;
$this->load->library('upload', $config);
if (!$this->upload->do_upload($profile_image_form))
{
$status = 'error';
$msg = $this->upload->display_errors('', '');
}
else
{
$data = $this->upload->data();
$status = "success";
$msg = '';
$profile_image = $data['file_name'];
}
$email_found = $this->db->get_where("supplier_user", array("company_email" => $email));
if($email_found->result_id->num_rows > 0) {
parent::returnJson($this->return_data, 401, $this->return_message);
}
else
{
$email_found_2 = $this->db->get_where("supplier_user", array("email" => $email));
if($email_found_2->result_id->num_rows > 0) {
parent::returnJson($this->return_data, 402, $this->return_message);
}
else
{
$username_found = $this->db->get_where("supplier_user", array("user_name" => $user_name));
if($username_found->result_id->num_rows > 0) {
parent::returnJson($this->return_data, 403, $this->return_message); }
else
{
$this->RegisterModel->register_supplier($profile_image, $title, $first_name, $last_name, $user_name, $email, $password, $job, $company_name, $address_one, $address_two, $country, $city, $company_description, $company_website, $company_email, $company_telephone, $company_logo, $trade_license);
parent::returnJson($this->return_data, $this->return_status, $this->return_message);
}
}
}
}
}

it seems like there is an issue with your .htaccess file. if you do not want to remove index.php file from the url you can use site_url() instead of base_url.Here is the difference b/w both
base_url() = http://yourwebsite.com/
whereas
site_url() = http://yourwebsite.com/index.php
to remove index.php file from url put this code in .htaccess file
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
read this tutorial for more
http://w3code.in/2015/09/how-to-remove-index-php-file-from-codeigniter-url/

Related

How to read the content of pop up msg which IE shows after submit button

I have automated data entry in to webpage and in the last when I click submit button it shows one pop up in which the registration no. Generated is displayed.
I want to know is there any way I can copy that registration no and save it in excel.
Please find the pic attached.
[enter image description here][1]
[1]:
I did automated to click on submit button but after that how to read pop up have no idea where to begin, searched a lot on internet but didn't find what I was looking for.
https://i.stack.imgur.com/zMhX4.png
Please find HTML code on top there is button save named after clicking on which the pop is generated.
 
 
<input type="submit" name="ctl00$ContentPlaceHolder1$btnOk" value="Ok" id="ctl00_ContentPlaceHolder1_btnOk" class="btn" style="display:none;" />
</div>
<div id="ctl00_ContentPlaceHolder1_UpdateProgress" style="display:none;">
<img id="ctl00_ContentPlaceHolder1_Image1" src="images/loader.gif" alt="Processing" style="border-width:0px;" />
</div>
</td>
</tr>
</table>
<input type="hidden" name="ctl00$ContentPlaceHolder1$hdnVosFlag" id="ctl00_ContentPlaceHolder1_hdnVosFlag" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$hdnLNEXP_TYPE" id="ctl00_ContentPlaceHolder1_hdnLNEXP_TYPE" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$hdnHDRLNEXP_TYPE" id="ctl00_ContentPlaceHolder1_hdnHDRLNEXP_TYPE" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$hdnPFID" id="ctl00_ContentPlaceHolder1_hdnPFID" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$hdnpfRefNo" id="ctl00_ContentPlaceHolder1_hdnpfRefNo" value="0" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$hdnflagNewPan" id="ctl00_ContentPlaceHolder1_hdnflagNewPan" value="N" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$hndchkpan" id="ctl00_ContentPlaceHolder1_hndchkpan" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$hndIsStatusEnabled" id="ctl00_ContentPlaceHolder1_hndIsStatusEnabled" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$hndRetamt" id="ctl00_ContentPlaceHolder1_hndRetamt" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$hndDdlNEFTAcc" id="ctl00_ContentPlaceHolder1_hndDdlNEFTAcc" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$hndUsersol" id="ctl00_ContentPlaceHolder1_hndUsersol" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$hndneft" id="ctl00_ContentPlaceHolder1_hndneft" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$hdnAttchmentID" id="ctl00_ContentPlaceHolder1_hdnAttchmentID" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$hdnPfLvl" id="ctl00_ContentPlaceHolder1_hdnPfLvl" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$hdnvenStatus" id="ctl00_ContentPlaceHolder1_hdnvenStatus" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$TabName" id="ctl00_ContentPlaceHolder1_TabName" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$hdnMode" id="ctl00_ContentPlaceHolder1_hdnMode" value="I" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$venid" id="ctl00_ContentPlaceHolder1_venid" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$siteid" id="ctl00_ContentPlaceHolder1_siteid" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$hdncrAcc" id="ctl00_ContentPlaceHolder1_hdncrAcc" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$hdnNEFTAcc" id="ctl00_ContentPlaceHolder1_hdnNEFTAcc" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$hdnduedtflag" id="ctl00_ContentPlaceHolder1_hdnduedtflag" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$hdnpfidindex" id="ctl00_ContentPlaceHolder1_hdnpfidindex" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$hdnlstPFids" id="ctl00_ContentPlaceHolder1_hdnlstPFids" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$hdnUserType" id="ctl00_ContentPlaceHolder1_hdnUserType" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$hdnDOPLimit" id="ctl00_ContentPlaceHolder1_hdnDOPLimit" value="1000000" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$hdn_IFSC_CODE" id="ctl00_ContentPlaceHolder1_hdn_IFSC_CODE" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$hdn_account_id" id="ctl00_ContentPlaceHolder1_hdn_account_id" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$hdnExpenseSolId" id="ctl00_ContentPlaceHolder1_hdnExpenseSolId" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$hdnOrgCreationDt" id="ctl00_ContentPlaceHolder1_hdnOrgCreationDt" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$hdnChkerEin" id="ctl00_ContentPlaceHolder1_hdnChkerEin" />
<script type="text/javascript" language="javascript">
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
function BeginRequestHandler(sender, args) { var oControl = args.get_postBackElement(); oControl.disabled = true; }
</script>
<script language="javascript" type="text/javascript">
function disposeTree(sender, args) {
var elements = args.get_panelsUpdating();
for (var i = elements.length - 1; i >= 0; i--) {
var element = elements[i];
var allnodes = element.getElementsByTagName('*'),
length = allnodes.length;
var nodes = new Array(length)
for (var k = 0; k < length; k++) {
nodes[k] = allnodes[k];
}
for (var j = 0, l = nodes.length; j < l; j++) {
var node = nodes[j];
if (node.nodeType === 1) {
if (node.dispose && typeof (node.dispose) === "function") {
node.dispose();
}
else if (node.control && typeof (node.control.dispose) === "function") {
node.control.dispose();
}
var behaviors = node._behaviors;
if (behaviors) {
behaviors = Array.apply(null, behaviors);
for (var k = behaviors.length - 1; k >= 0; k--) {
behaviors[k].dispose();
}
}
}
}
element.innerHTML = "";
}
}
Sys.WebForms.PageRequestManager.getInstance().add_pageLoading(disposeTree);
</script>
</td>
</tr>
</table>
</div>
<!-- #main (end) -->
</td>
</tr>
</table>
<!-- #wrapper (end) -->
<script type="text/javascript">Cufon.now();</script>
<script type="text/javascript">
//<![CDATA[
var ctl00_mnuCRM_Data = new Object();
ctl00_mnuCRM_Data.disappearAfter = 500;
ctl00_mnuCRM_Data.horizontalOffset = 0;
ctl00_mnuCRM_Data.verticalOffset = 0;
ctl00_mnuCRM_Data.hoverClass = 'ctl00_mnuCRM_14 hover';
ctl00_mnuCRM_Data.hoverHyperLinkClass = 'ctl00_mnuCRM_13 hover';
ctl00_mnuCRM_Data.staticHoverClass = 'ctl00_mnuCRM_12 statichover';
ctl00_mnuCRM_Data.staticHoverHyperLinkClass = 'ctl00_mnuCRM_11 statichover';
theForm.oldSubmit = theForm.submit;
theForm.submit = WebForm_SaveScrollPositionSubmit;
theForm.oldOnSubmit = theForm.onsubmit;
theForm.onsubmit = WebForm_SaveScrollPositionOnSubmit;
Sys.Application.add_init(function() {
$create(Sys.Extended.UI.CalendarBehavior, {"format":"dd/MM/yyyy","id":"ctl00_ContentPlaceHolder1_TextBox1_CalendarExtender"}, null, null, $get("ctl00_ContentPlaceHolder1_txtduedt"));
});
Sys.Application.add_init(function() {
$create(Sys.Extended.UI.AutoCompleteBehavior, {"completionInterval":10,"completionListCssClass":"autocomplete_completionListElement","completionListItemCssClass":"autocomplete_listItem","completionSetCount":20,"delimiterCharacters":"","highlightedItemCssClass":"autocomplete_highlightedListItem","id":"AutoCompleteVenEx","minimumPrefixLength":2,"onHide":"{\"AnimationName\":\"Parallel\",\"Duration\":\".4\",\"AnimationChildren\":[{\"AnimationName\":\"FadeOut\",\"AnimationChildren\":[]},{\"AnimationName\":\"Length\",\"PropertyKey\":\"height\",\"StartValueScript\":\"$find(\\u0027AutoCompleteVenEx\\u0027)._height\",\"EndValue\":\"0\",\"AnimationChildren\":[]}]}","onShow":"{\"AnimationName\":\"Sequence\",\"AnimationChildren\":[{\"AnimationName\":\"OpacityAction\",\"Opacity\":\"0\",\"AnimationChildren\":[]},{\"AnimationName\":\"HideAction\",\"Visible\":\"true\",\"AnimationChildren\":[]},{\"AnimationName\":\"ScriptAction\",\"Script\":\"\\r\\n // Cache the size and setup the initial size\\r\\n var behavior = $find(\\u0027AutoCompleteVenEx\\u0027);\\r\\n if (!behavior._height) {\\r\\n var target = behavior.get_completionList();\\r\\n behavior._height = target.offsetHeight - 2;\\r\\n target.style.height = \\u00270px\\u0027;\\r\\n }\",\"AnimationChildren\":[]},{\"AnimationName\":\"Parallel\",\"Duration\":\".4\",\"AnimationChildren\":[{\"AnimationName\":\"FadeIn\",\"AnimationChildren\":[]},{\"AnimationName\":\"Length\",\"PropertyKey\":\"height\",\"StartValue\":\"0\",\"EndValueScript\":\"$find(\\u0027AutoCompleteVenEx\\u0027)._height\",\"AnimationChildren\":[]}]}]}","serviceMethod":"GetVendorList","servicePath":"/rfp/frmGSTINPaymentformTax.aspx"}, {"itemSelected":SettxtVDName_hiddenValue,"populated":HidevenImage,"populating":ShowvenImage}, null, $get("ctl00_ContentPlaceHolder1_txtVDName"));
});
Sys.Application.add_init(function() {
$create(Sys.Extended.UI.CalendarBehavior, {"format":"dd/MM/yyyy","id":"ctl00_ContentPlaceHolder1_CalendarExtender1"}, null, null, $get("ctl00_ContentPlaceHolder1_txtInvoicedt"));
});
Sys.Application.add_init(function() {
$create(Sys.Extended.UI.CalendarBehavior, {"format":"dd/MM/yyyy","id":"ctl00_ContentPlaceHolder1_CalendarExtender2"}, null, null, $get("ctl00_ContentPlaceHolder1_txtdoa"));
});
Sys.Application.add_init(function() {
$create(Sys.Extended.UI.AutoCompleteBehavior, {"completionInterval":10,"completionListCssClass":"autocomplete_completionListElement","completionListItemCssClass":"autocomplete_listItem","completionSetCount":20,"delimiterCharacters":"","highlightedItemCssClass":"autocomplete_highlightedListItem","id":"AutoCompleteEx","onHide":"{\"AnimationName\":\"Parallel\",\"Duration\":\".4\",\"AnimationChildren\":[{\"AnimationName\":\"FadeOut\",\"AnimationChildren\":[]},{\"AnimationName\":\"Length\",\"PropertyKey\":\"height\",\"StartValueScript\":\"$find(\\u0027AutoCompleteEx\\u0027)._height\",\"EndValue\":\"0\",\"AnimationChildren\":[]}]}","onShow":"{\"AnimationName\":\"Sequence\",\"AnimationChildren\":[{\"AnimationName\":\"OpacityAction\",\"Opacity\":\"0\",\"AnimationChildren\":[]},{\"AnimationName\":\"HideAction\",\"Visible\":\"true\",\"AnimationChildren\":[]},{\"AnimationName\":\"ScriptAction\",\"Script\":\"\\r\\n // Cache the size and setup the initial size\\r\\n var behavior = $find(\\u0027AutoCompleteEx\\u0027);\\r\\n if (!behavior._height) {\\r\\n var target = behavior.get_completionList();\\r\\n behavior._height = target.offsetHeight - 2;\\r\\n target.style.height = \\u00270px\\u0027;\\r\\n }\",\"AnimationChildren\":[]},{\"AnimationName\":\"Parallel\",\"Duration\":\".4\",\"AnimationChildren\":[{\"AnimationName\":\"FadeIn\",\"AnimationChildren\":[]},{\"AnimationName\":\"Length\",\"PropertyKey\":\"height\",\"StartValue\":\"0\",\"EndValueScript\":\"$find(\\u0027AutoCompleteEx\\u0027)._height\",\"AnimationChildren\":[]}]}]}","serviceMethod":"GetHSNSACList","servicePath":"/rfp/frmGSTINPaymentformTax.aspx"}, {"itemSelected":SetddlTypeValue,"populated":HidehsnImage,"populating":ShowhsnImage}, null, $get("ctl00_ContentPlaceHolder1_txtHSN_SAC"));
});
Sys.Application.add_init(function() {
$create(Sys.UI._UpdateProgress, {"associatedUpdatePanelId":"ctl00_ContentPlaceHolder1_UpdatePanel10","displayAfter":500,"dynamicLayout":true}, null, null, $get("ctl00_ContentPlaceHolder1_UpdateProgress9"));
});
Sys.Application.add_init(function() {
$create(Sys.UI._UpdateProgress, {"associatedUpdatePanelId":"ctl00_ContentPlaceHolder1_savepnlData","displayAfter":500,"dynamicLayout":true}, null, null, $get("ctl00_ContentPlaceHolder1_UpdateProgress"));
});
//]]>
</script>
</form>
</body>
</html>

The data is seen after sending in the form, what can it be?

The data is seen after sending in the form, which may be I am using angular as frontend and nodejs as backend, I would greatly appreciate the support please, it should be noted that I am a beginner in angular
<div class="container p-5">
<div class="row">
<div class="col-md-4 mx-auto">
<div class="card">
<div class="card-header">
Acceso al Sistema
</div>
<div class="card-body">
<form (submit)="login()" >
<div class="form-group">
<input type="text" [(ngModel)]="user.email" name="email" class="form-control" placeholder="Email" autofocus>
</div>
<div class="form-group">
<input type="password" [(ngModel)]="user.contrasenia" name="password" class="form-control" placeholder="Contraseña" >
</div>
<button type="submit" class="btn btn-primary btn-block">
Ingresar
</button>
</form>
</div>
</div>
</div>
</div>
</div>
export class Usuarios {
constructor(email=''){
this.email = email
}
_id:string;
nombre_completo: string;
apellido_paterno:string;
apellido_materno:string;
roles:string;
email:string;
contrasenia:string;
}
You can Encrypt the data and send to server and in the server side you can decrypt the data Please find the sample code below
import * as CryptoJS from 'crypto-js';
decryptParams(result, password) {
// console.log('to decrypt' + result);
let decryptedString: any;
const words = CryptoJS.enc.Base64.parse(result);
// console.log('to decrypt' + words);
const textString = CryptoJS.enc.Utf8.stringify(words);
decryptedString = CryptoJS.AES.decrypt(textString, password);
decryptedString = this.hex2a(decryptedString);
return JSON.parse(decryptedString);
}
encryptParams(params, password) {
let encryptedParams: any;
encryptedParams = CryptoJS.AES.encrypt(JSON.stringify(params), password);
encryptedParams = CryptoJS.enc.Utf8.parse(encryptedParams);
encryptedParams = CryptoJS.enc.Base64.stringify(encryptedParams);
// console.log('encry' + encryptedParams);
return encryptedParams;
}
hex2a(hexx) {
const hex = hexx.toString(); // force conversion
let str = '';
for (let i = 0; i < hex.length; i += 2) {
str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
}
return str;
}

Image upload in a form

I have an angular form with text fields and want to add am option for uploading image in the same form. I'm stuck with the latter.
The angular form contains html tag to upload the file. Once the file is uploaded the uploaded file's name is displayed in the input field.
<!--blog.html-->
<!--form to create new blog-->
<form #blogForm="ngForm" (ngSubmit)="Save(blogForm);">
<div class="form-group">
<label>Blog Title</label>
<input type="text" class="form-control input-text" maxlength="45" name="title" ngModel #blogtitle="ngModel" required placeholder="Blog Title">
<span class="required" *ngIf="blogtitle.errors?.required && (blogtitle.dirty||blogtitle.touched||blogtitle.untouched)">*required</span>
</div>
<div class="form-group">
<label>Blog </label>
<textarea class="textarea form-control" maxlength="150" name="summary" [(ngModel)]="summary">
Blog</textarea>
</div>
<div class="form-group">
<label>Blog Desc</label>
<textarea class="textarea form-control" name="description" ngModel #blogdescription="ngModel" required>Blog Description</textarea>
<span class="required" *ngIf="blogdescription.errors?.required && (blogdescription.dirty||blogdescription.touched||blogdescription.untouched)">*required</span>
</div>
<div class="form-group">
<label>HashTags</label>
<input type="text" class="form-control input-text" name="hashtag" [(ngModel)]="hashtag" placeholder="hashtags">
</div>
<div class="form-group">
<div class="custom-file">
<!--file upload -->
<input type="file" class="custom-file-input form-control-lg" name="file" id="customFile"
value="imageFile.name" (change)="handleImageFileInput($event)">
<input type="text" readonly="true" [value]="imageFile" class="custom-file-label" >
<button type="button" (click)="upload()">Upload</button>
</div>
</div>
<input type="button" class="btn-default" (click)="Save(blogForm)" value="Create">
</form>
//blog.ts
//function to create new blog
Save(blogForm: any) {
if (blogForm.valid === true) {
blogForm = blogForm.value;
blogForm.userId = this.user_id;
blogForm.author = this.display_name;
window.confirm('Want to Publish?');
this.blogservice.Save(blogForm).subscribe(response => {
window.alert('Blog published successfully');
this.router.navigate(['/dashboard']);
});
}
}
//function to display selected image in the input field
handleImageFileInput(event) {
const img1 =event.target.files[0];
const img =event.target.files[0].name;
const fileList: FileList = event.target.files;
const fileCount = fileList.length;
if (fileCount > 0) {
const file = fileList.item(0);
console.log(` image file: ${file.name}`);
console.log(img1);
if(img == undefined) {
this.imageFile = 'Upload an image';
} else {
this.imageFile = img;
}
}
}
Need to save file along with form submission
Here's a JavaScript script which will read your data from input and display it :
<input type='file' accept='image/*' onchange='openFile(event)'><br>
<img id='output'>
<script>
var openFile = function(event) {
var input = event.target;
var reader = new FileReader();
reader.onload = function(){
var dataURL = reader.result;
var output = document.getElementById('output');
output.src = dataURL;
};
reader.readAsDataURL(input.files[0]);
};
</script>
It come from the documentation of FileReader.
With that you should be able to store the input wherever you want and store the path inside of your MongoDB collection.
Else if you want to use Angular plugins, here's one that could be useful for you :
angular-file-upload

Handling uploads multiple images from react js

Good Morning, i got a problem about some codes, fyi im still new to react js, i try to uploads multiple images from react to express and save it to mongoDB
, i already re-search that i need to use multer in my node js, but i dont know the argument need to pass because in react i have 1 name of field of files to upload, but on my submit data has 2 data to send.
handleSubmit(e){
e.preventDefault();
// var formData = new FormData();
// formData.append('file', e.target.value)
// formData.append('file2', e.target.value)
let {imagePreviewUrl} = this.state;
const dataCategory = this.state.dataCategory;
let categoryName = this.refs.categoryName.value;
let categoryImage = this.refs.categoryImage.value;
let categoryDesc = this.refs.categoryDesc.value,
categoryImageCabor = (<img alt="www.google.com" height="100px" src={imagePreviewUrl} />),
namaCabor = this.refs.namaCabor.value,
descCabor = this.refs.descCabor.value,
imageCabor = (<img height="100px" src={this.state.imageCabor.props.src} />)
fetch('http://localhost:4000/add', {
mode:'cors',
method:'post',
headers:{
'Content-Type' : 'application/json',
// "Accept" : "application/json",
// "type" : "formData"
},
body:JSON.stringify({
categoryName : categoryName,
categoryDesc : categoryDesc,
categoryImage: categoryImage,
categoryImageCabor : categoryImageCabor,
namaCabor : namaCabor,
descCabor : descCabor,
imageCabor : imageCabor,
status : true
}),
}).then(res=>{
return res.json();
}).catch(function(err){
if(err){
console.log(err);
}
})
this.setState({
dataCategory : dataCategory,
imagePreviewUrl : false,
});
this.refs.myForm.reset();
this.refs.myForm.focus();
}
handleChange(e){
this.setState({
[e.target.categoryName] : e.target.value,
[e.target.categoryImage] : e.target.value,
[e.target.categoryDesc] : e.target.value
})
}
render(){
let {imagePreviewUrl} = this.state;
let $imagePreview = null;
if(imagePreviewUrl){
$imagePreview = (<img alt ="www.google.com" height="100px" src={imagePreviewUrl} />)
}
return this.state.imageCabor === "" ? <div></div> : (
<div>
<h3>Insert Category Cabang Olahraga </h3>
<form style={{marginTop: 10}} ref="myForm" onSubmit={this.handleSubmit} >
<div className="form-group">
<label>Nama Category</label>
<input
name="categoryName"
type="text"
className="form-control"
ref="categoryName"
onChange={this.handleChange}
/>
</div>
<div className="form-group">
<label>Deskripsi Category </label>
<textarea
name="categoryDesc"
type="text"
className="form-control"
ref="categoryDesc"
rows="5"
onChange={this.handleChange}
/>
</div>
<div className="form-group">
<label>Upload Icon Image</label> <br />
<div>{$imagePreview}</div>
<input
name="categoryImage"
type="file"
ref="categoryImage"
className="image-control"
onChange={this.imageHandleChange}
/>
</div>
<h1>Cabang Olahraga</h1>
<div className ="form-group">
<label>Nama Cabang Olahraga</label>
<input
name="namaCabor"
type="text"
className="form-control"
ref="namaCabor"
value={this.state.namaCabor}
/>
</div>
<div className ="form-group">
<label>Deskripsi Cabang Olahraga</label>
<textarea
name="descCabor"
type="text"
className="form-control"
ref="descCabor"
rows="5"
value={this.state.descCabor}
/>
</div>
<div className="form-group">
<label>Icon Cabang Olahraga</label> <br />
<div><img height="100px" src={this.state.imageCabor.props.src} /></div>
</div>
<div className="form-group">
<input type="submit" value="Apply" className ="btn btn-primary" />
</div>
</form>
</div>
);
}
//node js code
//i dont know the argument need to pass in here
app.post('/', upload.array('catagoryImage', 12), (req, res, next) =>{
const files = req.files;
if(!files){
const error = new Error('Please choose files')
error.httpStatusCode = 400
return next(err)
}
res.send(files);
}}
To send images along with data from frontend to backend, you need to wrap it inside FormData object like this:
let formData = new FormData();
formdata.append('keyName','value') //replace keyName with your key and value with its value.
And do not set any headers in your fetch request. This should do. Try it and let me know.
Hope it helps!!

Angular 6 - Dynamic Search with HttpParams + Pagination

This is not a question. I am sharing the knowledge I gained after much research and testing. I built a search for optional fields using angle 6 and HttpParams. I am sharing this, because I searched a lot, not having been successful in the search.
Dev. Env.: Angular 6.0.9, Spring boot 2.0.7.
Form:
<form [formGroup]="searchForm" (ngSubmit)="submitSearch()">
<div class="row">
<div class="col-md-1">
<label>Código/Ano: </label>
</div>
<div class="col-md-2">
<input type="text" class="form-control form-control-sm" id="inputCodigo" formControlName="codigo" placeholder="código" maxlength="10">
</div>
<div class="col-md-1">
<input type="text" class="form-control form-control-sm" id="inputAno" formControlName="ano" placeholder="ano" maxlength="4">
</div>
<div class="col-md-1">
<label>Período: </label>
</div>
<div class="col-md-2">
<input type="text" class="form-control form-control-sm" placeholder="de" onfocus="(this.type = 'date')" formControlName="dataInicio">
</div>
<div class="col-md-2">
<input type="text" class="form-control form-control-sm" placeholder="ate" onfocus="(this.type = 'date')" formControlName="dataFinal">
</div>
<div class="col-md-1">
<input class="btn btn-primary btn-sm" type="submit" value="Buscar">
</div>
<div class="col-md-2">
<a [routerLink]="['/documentos/cadastro']" class="btn btn-sm btn-danger">Novo Documento</a>
</div>
</div>
Component:
export class DocumentosComponent implements OnInit {
documentos: Documento[];
searchForm: FormGroup;
docFiltro: DocumentoSearch = new DocumentoSearch();
constructor(
private documentoService: DocumentoService,
private fb: FormBuilder,
private page: Page
) {}
ngOnInit() {
this.page.page = "0";
this.createFormGroup();
this.getDocumentosByFilter();
}
getDocumentosByFilter() {
this.docFiltro = this.searchForm.value;
let searchParams = this.createSearchParam(this.docFiltro);
this.documentoService.findPage(searchParams).subscribe(
data => {
this.documentos = data["content"];
this.page.pages = new Array(data["totalPages"]);
},
error => {
console.log(error.error.message);
}
);
}
createSearchParam(docFiltro: DocumentoSearch): HttpParams {
let searchParams = new HttpParams()
searchParams = searchParams.set("page",this.page.page)
if (
docFiltro.codigo != null &&
docFiltro.codigo != undefined &&
docFiltro.codigo != ""
) {
searchParams = searchParams.set("codigo", docFiltro.codigo);
}
if (
docFiltro.ano != null &&
docFiltro.ano != undefined &&
docFiltro.ano != ""
) {
searchParams = searchParams.set("ano", docFiltro.ano);
}
if (
docFiltro.dataInicio != null &&
docFiltro.dataInicio != undefined &&
docFiltro.dataInicio != ""
) {
searchParams = searchParams.set("dataInicio", docFiltro.dataInicio);
}
if (
docFiltro.dataFinal != null &&
docFiltro.dataFinal != undefined &&
docFiltro.dataFinal != ""
) {
searchParams = searchParams.set("dataFinal", docFiltro.dataFinal);
}
return searchParams;
}
setPage(i, event: any) {
event.preventDefault();
this.page.page = i;
this.getDocumentosByFilter();
}
createFormGroup() {
this.searchForm = this.fb.group({
codigo: [""],
ano: [""],
dataInicio: [""],
dataFinal: [""]
});
}
submitSearch() {
this.page.page = '0';
this.getDocumentosByFilter();
}
}
Service method:
findPage(searchParams: HttpParams) {
return this.http.get<Documento[]>(`${API_URL}/sge/documento/search`, {params: searchParams});
}

Resources