How to get Output it showing no any error & output? - ajax

The contoller shows output error1 it does not shoe even row(),and does not give any error in developer tool. it get the file from ajax users_controller but does not work & issue is contant.
This is the form:
<form class="form-signin" >
<h1 class="h3 mb-3 font-weight-normal">Please sign in</h1>
<label for="name" class="sr-only">Username</label>
<input type="text" id="name" class="form-control" placeholder="Username" autofocus><br/>
<label for="Password" class="sr-only">Password</label>
<input type="text" id="password" class="form-control" placeholder="Password">
<div class="checkbox mb-3">
<label>
<input type="checkbox" value="remember-me"> Remember me
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Login</button>
<p class="mt-5 mb-3 text-muted">© 2017-2018</p>
<span class="error"></span>
</form>
These are the scripts:
<script>
$(document).ready(function(){
$('form').on('submit',function(){
var username = $('#name').val();
var password = $('#password').val();
$.ajax({
type:'post',
url:'users_controller/login_check',
data: {
username:'username',
password:'password'
},
success:function(result)
{
if(result !== 'error')
{
window.location.href=result;
}
else
{
$('.error').html('');
$('.error').html('<p class="alert alert-danger">Invalid username or password</p>');
$('.error').show();
}
}
});
return false;
});
});
This is controller file:
public function login_check()
{
$username = $this->input->post('username',TRUE);
$password = $this->input->post('password',TRUE);
$this->load->model('users_model');
//$row = $this->load->users_model('getUsers');
$row = $this->users_model->getUsers($username,$password);
if($row)
{
if($this->username === $username && $this->password === $password)
{
$this->session->set_userdata('user_id',$row->user_id);
$this->session->set_userdata('user_name',$row->username);
echo base_url('users_controller');
}
else
{
echo "error";
}
}
else{
echo "error1";
print_r($row);
}
}
The contoller shows output error1 it does not shoe even row(),and does not give any error in developer tool.

Related

!empty function wont work on login using codeigniter

This is my login form
<form action="<?php echo site_url('admin/checkAdmin')?>
<div class="form-group">
<input type="text" name="email" placeholder="Enter Your Email" class="form-control">
</div>
<div class="form-group">
<input type="password" name="password" placeholder="Enter Your Password" class="form-control">
</div>
<div class="form-group">
<button class="btn btn-primary" type="submit">Signin</button>
</div>
</form>
And my controller
public function checkAdmin()
{
$data['aEmail'] = $this->input->post('email', true);
$data['aPassword'] = $this->input->post('password', true);
if (!empty($data['aEmail']) && !empty($data['aPassword']))
{
echo 'working';
}
else
{
echo 'not working';
}
}
Whether I key in values or not, it still echos 'not working'. Where is the problem?
Controller Code:-
class admin extends CI_Controller {
function login()
{
$email= $this->input->post("email");
$password = $this->input->post("password");
$result = $this->db->get_where('table_name',array('email'=>$email,'password'=>$password))->row_array();
if ($result >0) //active user record is present
{
$url = base_url('admin/Admin/dashboard');
redirect($url);
}
else{
redirect('admin/Admin');
}
}
}

Values from fields does not pass throug ajax to php

I have a small contact form that almost works as i should. The file is uploaded and sent correctly, but all the other values from the input fields in the form does not pass throug the script. Does anyone see what I am missing?
Form:
<form id="contactForm" name="sentMessage" novalidate="" method="post" enctype="multipart/form-data">
<input type="hidden" name="path" id="path" value="projectpage">
<div><div class="textwidget custom-html-widget"><div class="moduletable pt-2 pb-2 mb-4">
<div class="custom pl-2 pr-2 pt-4 pb-2 mb-4">
<div class="control-group form-group">
<div class="col"><label for="name">Navn:</label><input id="name" class="form-control" required="" type="text" data-validation-required-message="Skriv inn ditt navn.">
<div class="help-block"></div>
</div>
</div>
<div class="control-group form-group">
<div class="col"><label for="phone">Telefonnummer:</label><input id="phone" class="form-control" required="" type="tel" data-validation-required-message="Skriv inn et telefonnummer.">
<div class="help-block"></div>
</div>
</div>
<div class="control-group form-group">
<div class="col"><label for="email">E-post:</label><input id="email" class="form-control" required="" type="email" data-validation-required-message="Skriv inn en e-postadresse.">
<div class="help-block"></div>
</div>
</div>
<div class="control-group form-group">
<div class="col"><label for="message">Melding:</label><textarea id="message" class="form-control" style="resize: none;" cols="100" maxlength="999" required="" rows="10" data-validation-required-message="Skriv en melding"></textarea>
<div class="help-block"></div>
</div>
</div>
<div class="control-group form-group">
<div class="col"><label for="attachment">Vedlegg:</label> <input type="file" name="attachment[]" class="form-control border-0 w-auto" multiple="multiple">
</div>
</div>
<div class="control-group form-group">
<div class="col"><label class="checkbox"> <input id="terms-and-conditions" name="terms-and-conditions" required="" type="checkbox" data-validation-required-message="Kryss av denne boksen hvis du vil fortsette"> Ved avkryssning samtykker du i vår personvernerklæring. </label>
<div class="help-block"></div>
</div>
</div>
<p class="help-block"></p>
<div id="success"></div>
<div class="col"><button id="sendMessageButton" class="btn btn-success" type="submit">Send oss melding</button></div></div>
</div></div></div></form>
JS: I think the problem is here, but I cant figure out what to change or add to make the data from the fields pass through along with the attachment.
$(function() {
$("#contactForm input,#contactForm textarea").jqBootstrapValidation({
preventSubmit: true,
submitError: function($form, event, errors) {},
submitSuccess: function($form, event) {
$("#btnSubmit").attr("disabled", true);
event.preventDefault();
var data = new FormData(contactForm);
$.ajax({
url: "/wp-content/themes/bootstrap/mail/contact_me.php",
type: "POST",
method: 'POST',
data: data,
cache: false,
contentType: false,
processData: false,
success: function() {
$("#btnSubmit").attr("disabled", false);
$('#success').html("<div class='alert alert-success'>");
$('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×").append("</button>");
$('#success > .alert-success').append("<strong>Takk for din interesse. </strong>");
$('#success > .alert-success').append('</div>');
$('#contactForm').trigger("reset");
},
error: function() {
$('#success').html("<div class='alert alert-danger'>");
$('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×").append("</button>");
$('#success > .alert-danger').append("<strong>Sorry, it seems that my mail server is not responding. Please try again later!");
$('#success > .alert-danger').append('</div>');
$('#contactForm').trigger("reset");
},
});
},
filter: function() {
return $(this).is(":visible");
},
});
$("a[data-toggle=\"tab\"]").click(function(e) {
e.preventDefault();
$(this).tab("show");
});
});
$('#name').focus(function() {
$('#success').html('');
});
PHP:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
/* Exception class. */
require 'Exception.php';
/* The main PHPMailer class. */
require 'PHPMailer.php';
$name = strip_tags(htmlspecialchars($_POST['name']));
$from = strip_tags(htmlspecialchars($_POST['name']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$phone = strip_tags(htmlspecialchars($_POST['phone']));
$message = strip_tags(htmlspecialchars($_POST['message']));
$path = strip_tags(htmlspecialchars($_POST['path']));
$mail = new PHPMailer;
$mail->CharSet = 'UTF-8';
$mail->Encoding = 'base64';
$mail->AddReplyTo(($email_address), ($name));
$mail->setFrom('noreply#mydomain.no', 'Kontaktskjema på nettside');
$mail->addAddress('email#gmail.com', 'My NAME');
$mail->Subject = 'Melding fra ' .$name. ' via kontaktskjema';
$mail->Body = "Du har fått en melding via kontaktskjemaet på nettsiden.\n\n"."Her er detaljene:\n\nNavn: $name\n\nE-post: $email_address\n\nTelefon: $phone\n\nMelding:\n$message";
foreach ($_FILES["attachment"]["name"] as $k => $v) {
$mail->AddAttachment( $_FILES["attachment"]["tmp_name"][$k], $_FILES["attachment"]["name"][$k] );
}
if(!$mail->send()) {
echo 'Message was not sent.';
echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent.';
}
return true;
?>
Most of your <input> elements don't have name attributes. So this won't include them:
new FormData(contactForm)
The file input works because it has a name:
<input type="file" name="attachment[]" class="form-control border-0 w-auto" multiple="multiple">
^----- here ------^
Add names to the rest of the inputs that you want included in the FormData object.
Like David said most of your <input> elements dont have name attributes and thats why the FormData method dont include them, you have two work arounds here:
Get all your data into an array using the id of each element and pass this array to your ajax e.g:
let data = {
name : $('#name').val(),
email: $('#email').val(),
.....
};
add the name attribute to each input.
Hope it helps

Register component doesn't insert data. Throws new MethodNotAllowedHttpException($others);

I'm trying to post user register data to my db using axios.post from Register.vue component. but this gives me an error. I don't know if the error is on the form or on the inputs.
This is my Register.vue
<template>
<div class="login-wrapper border border-light">
<form action="" method="post" enctype="multipart/form-data" class="form-horizontal">
<h2 class="form-signin-heading">Please sign in</h2>
<div class="form-group">
<label for="usuario" class="sr-only">Username</label>
<input v-model="usuario" type="usuario" id="inputEmail" class="form-control" placeholder="Username" required autofocus>
<label for="inputEmail" class="sr-only">Email </label>
<input v-model="email" type="email" id="inputEmail" class="form-control" placeholder="Email address" required autofocus>
<label for="inputPassword" class="sr-only">Password</label>
<input v-model="password" type="password" id="inputPassword" class="form-control" placeholder="Password" required>
<button class="btn btn-primary" #click="registrarUsuario()">Register</button>
</div>
</form>
</div>
</template>
<script>
export default {
data () {
return {
usuario: '',
email: '',
password: '',
errorPersona : 0,
errorMostrarMsjPersona : [],
}
},
methods: {
registrarUsuario(){
console.log(this.email);
if (this.validarUsuario()){
return;
}
let me = this;
axios.post('/user/registrar',{
'email' : this.email,
'usuario': this.usuario,
'password': this.password
}).then(function (response) {
console.log("3");
}).catch(function (error) {
console.log("4");
console.log(error);
});
},
validarUsuario(){
console.log("2");
this.errorPersona=0;
this.errorMostrarMsjPersona =[];
if (!this.email) this.errorMostrarMsjPersona.push("El correo de usuario no puede estar vacío.");
if (!this.usuario) this.errorMostrarMsjPersona.push("El nombre de usuario no puede estar vacío.");
if (!this.password) this.errorMostrarMsjPersona.push("El password no puede estar vacío.");
if (this.errorMostrarMsjPersona.length) this.errorPersona = 1;
return this.errorPersona;
},
}
}
</script>
This is my UserController.php
public function store(Request $request)
{
if (!$request->ajax()) return redirect('/');
DB::beginTransaction();
$usuario = new User();
$usuario-> usuario = $request->usuario;
$usuario-> password = bcrypt($request->password);
$usuario-> condicion = 1;
$usuario->save();
console.log('end');
DB::commit();
}
This is my web.php
Route::get('/main', function () {
return view('contenido/contenido');
})->name('main');
//Route::resource('proyecto', 'ProyectoController', ['except' => 'show']);
Route::get('/user', 'UserController#index');
Route::post('/user/registrar', 'UserController#store');
Route::put('/user/actualizar', 'UserController#update');
Route::put('/user/desactivar', 'UserController#desactivar');
Route::put('/user/activar', 'UserController#activar');
Route::get('/register','Auth\RegisterController#showRegisterForm');
You must need csrf token or disable it.
First for disable
Http/Middleware/VerifyCsrfToken.php
protected $except = [
'/user/registrar'
];
Second for send with csrf your ftemplate
<template>
<div class="login-wrapper border border-light">
<form action="" method="post" enctype="multipart/form-data" class="form-horizontal">
{{ csrf_field() }}
<h2 class="form-signin-heading">Please sign in</h2>
<div class="form-group">
<label for="usuario" class="sr-only">Username</label>
<input v-model="usuario" type="usuario" id="inputEmail" class="form-control" placeholder="Username" required autofocus>
<label for="inputEmail" class="sr-only">Email </label>
<input v-model="email" type="email" id="inputEmail" class="form-control" placeholder="Email address" required autofocus>
<label for="inputPassword" class="sr-only">Password</label>
<input v-model="password" type="password" id="inputPassword" class="form-control" placeholder="Password" required>
<button class="btn btn-primary" #click="registrarUsuario()">Register</button>
</div>
</form>
</div>
</template>
UPDATE
You can get csrf token from app.blade.php
var csrfToken = $('meta[name="csrf-token"]').attr('content');
Then update your axios.post request
axios.post('/user/registrar',{
'email' : this.email,
'usuario': this.usuario,
'password': this.password
},headers: {
'X-Requested-With': 'XMLHttpRequest',
'X-CSRFToken': csrfToken,
}).then(function (response) {
console.log("3");
}).catch(function (error) {
console.log("4");
console.log(error);
});

apply validation on ko.computed using knockout.js

i just created a scenario , the thing i wanted, can you check out this fiddle jsfiddle.net/5PRMe/393. i want to validate this, some piece of code i used here, but comment it.kindly check this.
Bascially i am follow this link https://github.com/knockout/knockout/wiki/View-Add-Edit-Delete-Design-Pattern (full code of this link is at the bottom of the page), to create my code, but i want knockout validation, with proper messages, but i did't understand how to do validation if we have with binding with computedObservable, can anyone help me to sort out the problem?
var baseModel = function () {
this.id = ko.observable(0);
this.name = ko.observable("").extend({ required: true });
this.title = ko.observable(undefined).extend({
required: { message: "You must select title" },
});
this.email = ko.observable("").extend({ required: true });
this.phone = ko.observable("").extend({ required: true });
this.mobile = ko.observable('');
this.streetAddress = ko.observable('');
this.city = ko.observable('');
this.state = ko.observable('');
this.zipCode = ko.observable('');
this.fax = ko.observable('');
this.description = ko.observable('');
this.editSelectedItemErrors = ko.validation.group([this.name,this.accountId,this.title,this.gender,this.email,this.phone,this.country]);
}
var viewModel = function () {
var self = this;
self.editSelectedItem = ko.observableArray('');
var mappedItems = ko.mapping.fromJS(new baseModel());
self.editSelectedItem(mappedItems);
self.saveContact = function (form) {
if (baseModel.editSelectedItemErrors().length === 0) {
// save data
}
else{
baseModel.editSelectedItemErrors.showAllMessages();
}
}
self.SelectedRecord = ko.computed(function () {
var selected = self.editSelectedItem();
selected.selectedOption;
//selected.selectLanguage;
selected.streetAddress;
var result = (selected);
console.log(result.length);
if (result != null) {
result = ko.toJS(result);
var observable = ko.mapping.toJS(result);
//console.log(observable);
return observable;
} else {
return new baseModel();
};
}, self);
}
var contactModel = new viewModel();
$(function () {
ko.validation.init({
registerExtenders: true,
messagesOnModified: true,
insertMessages: true,
parseInputAttributes: true,
messageTemplate: null,
decorateElement: true,
grouping: { deep: true, observable: true, live: true }
}, true);
ko.applyBindings(contactModel);
});
<div id="divContact" class="flt w100 space form" data-bind="with : SelectedRecord()">#*<!-- ko with : SelectedRecord -->*#
<div class="row">
<label>
First Name</label>
<span>
<input id="Name" name="Name" type="text" data-bind="value : name,uniqueName: true" class="field required" placeholder="Name" />
</span>
</div>
<div class="row">
Email</label>
<span>
<input id="Email" type="text" data-bind="value : email,uniqueName: true" class="required field" placeholder="Email" /></span>
</div>
<div class="row">
<label>
Phone</label>
<span>
<input id="Phone" type="text" data-bind="value : phone,uniqueName: true" class="field" placeholder="Phone" /></span>
<label>
Mobile</label>
<span>
<input id="Mobile" type="text" data-bind="value : mobile,uniqueName: true" class="field" placeholder="Mobile" /></span>
</div>
<div class="row">
<label>
Street Adress</label>
<span>
<input id="Street" type="text" data-bind="value : streetAddress,uniqueName: true" class="field" placeholder="Street" /></span>
<label>
City</label>
<span>
<input id="City" type="text" data-bind="value : city,uniqueName: true" class="field" placeholder="City" /></span>
</div>
<div class="row">
<label>
State</label>
<span>
<input id="State" type="text" data-bind="value : state,uniqueName: true" class="field" placeholder="State" /></span>
<label>
Zip Code</label>
<span>
<input id="Zip" type="text" data-bind="value : zipCode,uniqueName: true" class="field" placeholder="Zip Code" /></span>
</div>
<div class="row">
Fax</label>
<span>
<input id="Fax" type="text" data-bind="value : fax,uniqueName: true" class="field" placeholder="Fax" /></span>
</div>
<div class="row">
<label>
Description</label>
<span>
<textarea class="input-field " data-bind="value: description,uniqueName: true"></textarea></span>
</div>
<div class="row">
<input data-bind="click: function() { contactModel.saveContact($data,0);}" type="submit" value="Save" class="btn"/>
<input type="button" class="btn" value="Cancel" data-bind="click: function() { contactModel.cancelCreate($data,0);}">
</div>

stripe token is not passing

I have an application built in Laravel 4 and uses this package
I am following this tutorial
This is the error I am getting http://postimg.org/image/c4qwjysgp/
My issue is $token is not correctly passing or the $token is empty.
I have already done a var_dump($token); die(); and get nothing but a white screen so not data is passing.
Here is the view
#extends('layouts.main')
#section('content')
<h1>Your Order</h1>
<h2>{{ $download->name }}</h2>
<p>£{{ ($download->price/100) }}</p>
<form action="" method="POST" id="payment-form" role="form">
<input type="hidden" name="did" value="{{ $download->id }}" />
<div class="payment-errors alert alert-danger" style="display:none;"></div>
<div class="form-group">
<label>
<span>Card Number</span>
<input type="text" size="20" data-stripe="number" class="form-control input-lg" />
</label>
</div>
<div class="form-group">
<label>
<span>CVC</span>
<input type="text" size="4" data-stripe="cvc" class="form-control input-lg" />
</label>
</div>
<div class="form-group">
<label>
<span>Expires</span>
</label>
<div class="row">
<div class="col-lg-1 col-md-1 col-sm-2 col-xs-3">
<input type="text" size="2" data-stripe="exp-month" class="input-lg" placeholder="MM" />
</div>
<div class="col-lg-1 col-md-1 col-sm-2 col-xs-3">
<input type="text" size="4" data-stripe="exp-year" class="input-lg" placeholder="YYYY" />
</div>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-lg">Submit Payment</button>
</div>
</form>
#stop
Here is the route
Route::post('/buy/{id}', function($id)
{
Stripe::setApiKey(Config::get('laravel-stripe::stripe.api_key'));
$download = Download::find($id);
//stripeToken is form name, injected into form by js
$token = Input::get('stripeToken');
//var_dump($token);
// Charge the card
try {
$charge = Stripe_Charge::create(array(
"amount" => $download->price,
"currency" => "gbp",
"card" => $token,
"description" => 'Order: ' . $download->name)
);
// If we get this far, we've charged the user successfully
Session::put('purchased_download_id', $download->id);
return Redirect::to('confirmed');
} catch(Stripe_CardError $e) {
// Payment failed
return Redirect::to('buy/'.$id)->with('message', 'Your payment has failed.');
}
});
Here is the js
$(function () {
console.log('setting up pay form');
$('#payment-form').submit(function(e) {
var $form = $(this);
$form.find('.payment-errors').hide();
$form.find('button').prop('disabled', true);
Stripe.createToken($form, stripeResponseHandler);
return false;
});
});
function stripeResponseHandler(status, response) {
var $form = $('#payment-form');
if (response.error) {
$form.find('.payment-errors').text(response.error.message).show();
$form.find('button').prop('disabled', false);
} else {
var token = response.id;
$form.append($('<input type="hidden" name="stripeToken" />').val(token));
$form.get(0).submit();
}
}
Here is the stripe.php in package
<?php
return array(
'api_key' => 'sk_test_Izn8gXUKMzGxfMAbdylSTUGO',
'publishable_key' => 'pk_test_t84KN2uCFxZGCXXZAjAvplKG'
);
Seems like the Config::get might be wrong.
It would have to be written this way.
Stripe::setApiKey(Config::get('stripe.api_key'));
I figured out the problem. In the source for the external javascript file, the "/" was missing at the beginning of the relative path. That is why the javascript file for the homepage was rendering fine but the /buy page was not rendering the javascript file.

Resources