I use jquery ajax to add data to database. When i click submit button, my page return blank. I use firebug to debug and see message: 500 (Internal Server Error).
routes.php
Route::controller('subscribers', 'SubscribersController');
SubscribersController.php
class SubscribersController extends \BaseController {
//The method to show the form to add a new feed
public function getIndex() {
//We load a view directly and return it to be served
return View::make('subscribe_form');
}
//This method is to process the form
public function postSubmit() {
//We check if it's really an AJAX request
if(Request::ajax()) {
$validation = Validator::make(Input::all(), array(
//email field should be required, should be in an email
//format, and should be unique
'email' => 'required|email|unique:subscribers, email'));
if($validation->fails()) {
return $validation->errors()->first();
} else {
$create = Subscribers::create(array(
'email' => Input::get('email')
));
//If successful, we will be returning the '1' so the form
//understands it's successful or if we encountered an unsuccessful creation attempt,
//return its info
return $create?'1':'We could not save your address to our system, please try again later';
}
} else {
return Redirect::to('subscribers');
}
}
}
view file:
{{--Form Starts Here --}}
{{Form::open(array('url' => URL::to('subscribers/submit'), 'method' => 'post'))}}
<p>Simple Newsletter Subscription</p>
{{Form::text('email', null, array('placeholder'=>'Type your E-mail address here'))}}
{{Form::submit('Submit!')}}
{{Form::close()}}
{{--Form Ends Here --}}
{{--This div will show the ajax response --}}
<div class="content"></div>
{{-- Because it'll be sent over Ajax, we add the jQuery source --}}
{{HTML::script('http://code.jquery.com/jquery-1.11.0.min.js') }}
<script type="text/javascript">
//Even though it's on footer, I just like to make
//sure that DOM is ready
$(function() {
//We hide de the result div on start
$('div.content').hide();
//This part is more jQuery related. In short, we make an Ajax post request and get
//the response back from server
$('input[type="submit"]').click(function(e) {
e.preventDefault();
$.post('http://localhost/laravel-blueprint/newsletter/public/subscribers/submit', {email: $('input[name="email"]').val()
}, function($data) {
if($data == '1') {
$('div.content')
.hide()
.removeClass('success error')
.addClass('success')
.html('You\'ve successfully subscribed to our newsletter')
.fadeIn('fast');
} else {
//This part echos our form validation errors
$('div.content')
.hide().removeClass('success error')
.addClass('error')
.html('There has been an error occurred: <br /><br />'+$data)
.fadeIn('fast');
}
});
});
//We prevented to submit by pressing enter or any other way
$('form').submit(function(e) {
e.preventDefault();
$('input[type="submit"]').click();
});
});
</script>
i use laravel 4
log-access:
127.0.0.1 - - [11/Mar/2014:17:54:41 +0700] "POST /laravel-blueprint/newsletter/public/subscribers/submit HTTP/1.1" 500 381
Any solution?
In order for your code to work, do the following changes:
SUBSCRIBERS CONTROLLER
class SubscribersController extends \BaseController {
public function getIndex() {
return View::make('subscribe_form');
}
public function postSubmit() {
if(Request::ajax()) {
$validation = Validator::make(Input::all(),
['email' => 'required|email|unique:subscribers,email']);
if($validation->fails()) {
return $validation->errors()->first();
} else {
// Note here that the model is Subscriber and not Subscribers
// This is the default convention for the subscribers table
$create = Subscriber::create(array(
'email' => Input::get('email')
));
return $create ? '1' : 'We could not save your address';
}
} else {
return Redirect::to('subscribers');
}
}
}
IMPORTANT FOR SUBSCRIBER MODEL
class Subscriber extends Eloquent {
// I don't know if you have timestamps enabled, but if not this is necessary
public $timestamps = false;
// Must be present for mass assignment to work (Subscriber::create)
protected $fillable = array('email');
}
Comment
500 (Internal Server Error) might be caused due to a PHP fatal.
Do you have error_reporting on?
If not, try
error_reporting(E_ALL); ini_set('display_errors', 1);
and check.
Related
Spring shows - Resolved [org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public com.cg.bookstore.entities.OrderDetails com.cg.bookstore.controller.OrderDetailsController.updateDeliveryStatus(int,java.lang.String)]
Console shows - Uncaught (in promise) Error: Request failed with status code 400
class UpdateOrder extends Component {
state = {
deliveryStatus:""
}
handleChange = (event) => {
const deliveryStatus = { ...this.state.deliveryStatus };
this.setState({ deliveryStatus: event.target.value });
};
handleSubmit = (event) => {
// Prevents default behaviour of submit button
event.preventDefault();
console.log(this.state.deliveryStatus)
console.log()
OrderService.updateDeliveryStatus(this.props.match.params.orderDetailsId,this.state.deliveryStatus)
.then((res) => {
this.props.history.push("/admin/orders");
});
};
In OrderService I call the updateDeliveryStatus
async updateDeliveryStatus(orderId,deliveryStatus){
return await axios.patch(BASE_URL+"/"+orderId,deliveryStatus)
}
The updateDeliveryStatus service in spring
#Override
public OrderDetails updateDeliveryStatus(int orderId, String deliveryStatus)
{
Optional<OrderDetails> opt = orderDetailsRepo.findById(orderId);
OrderDetails od;
if (opt.isPresent())
{
od = opt.get();
od.setDeliveryStatus(deliveryStatus);
orderDetailsRepo.save(od);
} else
{
throw new OrderDetailsNotFoundException("Order is not found");
}
return od;
}
While I was testing backend in POSTMAN , I pass the input as plain string and it works fine. Is it because the input in not in form of json the issue? How to fix this ?
Usually, when using #PutMethod and wanting to update a resource you need to provide both ID of the resource you want to update and the new body, which in this case I presume is 'OrderDetails', error suggests is missing there.
Without java controller code it's only assumptions though.
I'm creating a Reactive Form in angular to register some devices. In this form I ask for a serial number, and I want to check if this serial number is already registered in my database.
When I type in the input form it activates the function serialNumAvailability to display or not a message. This function calls a service function called checkSerialNumAvailability which send a get request to my back-end. I made some console.log and used Postman to test the get request, and it seems to work fine on the back-end side. But at the moment I type one character in the input field, I go back to my home page, and I can't understand why...
Here is my HTML template verification:
<input formControlName="serialNum" type="text" class="form-control" placeholder="Ex: SL07101-BL" name="serialNum" required>
<div *ngIf="f.submitted " class="help-block mt-2 text-danger" i18n> Serial Number is required</div>
<div *ngIf="serialNum?.value.errors.serialNumAvailability" i18n> Serial Number already registered</div>
Then my component function serialNumAvailability :
serialNumAvailability(control: FormControl) {
return Observable.timer(500).switchMap(() => {
return this.portalService.checkAvailabilitySerialNum(control.value)
.map(res => {
if (res && res.length == 1 && res[0].serialNum) {
console.log("ON RENVOIE TRUE");
return { serialNumAvailability: true};
}
console.log("ON RENVOIE NULL");
return null;
});
});}
My service function :
checkAvailabilitySerialNum(term: string): Observable<Portal[]> {
let portals: Portal[];
if (!term.trim()) {// if search is empty
return Observable.of([]);
}
return this.http.get<Portal[]>(this.serverURL + `portal/?serialNum=${term}`)
.map(Portals => Portals.filter(portals => portals.serialNum === term)
);
}
And finally the Node side :
router.get('/',
function (req, res) {
console.log("ON RENTRE BIEN DANS LA FONCTION : " + req.query.serialNum);
return models.portals.findAll({
attributes: ['serialNum'],
where: {
serialNum: req.query.serialNum
}
}).then((serialNums) => {
if (serialNums) {
serialNums = serialNums.map((serialNum) => {
serialNum = serialNum.toJSON();
console.log(serialNum);
return serialNum;
})
}
console.log("ON FAIT RES.SEND DE "+serialNums);
res.send(serialNums);
})
})
I don't know why I'm redirected, if someone has encountered this problem, thanks for support :)
Finally the problem was solved. The redirection was due to a token interceptor which handled my request. As it was not authorized to GET information, I simply added an exception to this interceptor for my URL.
This looks like this :
if (req.headers.has(this.config.InterceptorSkipHeader)) {
let headers = req.headers.delete(this.config.InterceptorSkipHeader);
return next.handle(req.clone({ headers }));
}
if(this.authenticationService.isLoggedIn()){
this.authenticationService.updateExpiration();
}
else if (this.router.routerState.snapshot.url != "/register-portal"){
this.router.navigate(['/login'], { queryParams: { returnUrl: ''} });
}
Thanks to those who answered :)
in my react-redux form, i want to make recaptcha a required field, and disable my navigation bar component until recaptcha response is verified, i found some similar questions with javaScript but i wasn't able to apply them with React, because i am using react-recaptcha plugin :
<div className="form_wrapper">
<ReCAPTCHA
sitekey="xxxxxxxxxxx"
render="explicit"
onloadCallback={this.callback}
verifyCallback={this.verifyCallback}
/>
</div>
<NavigationBar
fields={requiredFields}
// disableNext={this.props} (here where i make conditions to disable)
/>
here are my callback and verifyCallback methods:
verifyCallback(response) {
return response;
}
callback() {
console.log('Done !!');
}
thank you
i added the code suggested by Hardik Modha, as follows but still having the same issue:
<NavigationBar
fields={requiredFields}
disableNext={this.props ... && !this.validateForm()}
/>
verifyCallback(response) {
this.setState({
reCaptchaResponse: response,
});
}
validateForm() {
if (!this.state.reCaptchaResponse || this.state.reCaptchaResponse.trim().length === 0) {
return false;
}
return true;
}
var Recaptcha = require('react-recaptcha');
// specifying verify callback function
var verifyCallback = function (response) {
this.setState({
reCaptchaResponse: response
});
};
ReactDOM.render(
<Recaptcha
sitekey="xxxxxxxxxxxxxxxxxxxx"
render="explicit"
verifyCallback={verifyCallback}
onloadCallback={callback}
/>,
document.getElementById('example')
);
You can pass a prop verifyCallBack to react-recaptcha, in that callback function you can store the response in state or wherever you want. Now, if response is empty you can simply disable the next button or you can put validation when user clicks on validation.
e.g. If you are storing response in state then you can check whether reCaptcha response is empty or not.
validateForm() {
// other field validations....
if (!this.state.reCaptchaResponse || this.state.reCaptchaResponse.trim().length === 0) {
return {success: false, message: 'Captcha is required.'};
}
}
Edit: For the edited question,
You can also create a state variable say btnDisabled and initialize it with true.
constructor() {
super();
this.state = {btnDisabled: true};
}
and Next button as
<button disabled={this.state.btnDisabled}>Next</button>
Now, in your validateForm method you can check whether the reCaptcha response is empty or not and based on that you can set the btnDisabled variable to true or false.
validateForm() {
// other field validations....
if (!this.state.reCaptchaResponse || this.state.reCaptchaResponse.trim().length === 0) {
return {success: false, message: 'Captcha is required.'};
} else {
this.setState({
btnDisabled: false
});
}
}
Side Note: You should never rely on client side validations. User can easily bypass client side validations. So, You should implement server side validations, too.
im trying to working on this project https://www.youtube.com/watch?v=bu0J-j5qYas
so i can charge multiple times with dummy credit-card.
But i got exception error message when i try to check out, it say must provide source or customer, below is the javascript i wrote.
Stripe.setPublishableKey(''); // im not showingt this key (censored)
var $form = $('#checkout-form');
$form.submit(function(event) {
$('#charge-error').addClass('hidden');
$form.find('button').prop('disabled', true);
Stripe.card.createToken({
number: $('#card-number').val(),
cvc: $('#card-cvc').val(),
exp_month: $('#card-expiry-month').val(),
exp_year: $('#card-expiry-year').val(),
name: $('#card-name').val()
}, stripeResponseHandler);
return false;
});
function stripeResponseHandler(status, response) {
if (response.error) {
$('#charge-error').removeClass('hidden');
$('#charge-error').text(response.error.message);
$form.find('button').prop('disabled', false);
} else {
var token = response.id;
$form.append($('<input type="hidden" name="stripeToken" />').val(token)); // this will generate the stripeToken
// Submit the form:
$form.get(0).submit();
}
}
and i make this functionc below inside the controller directory just like the guide say
public function postCheckout(Request $request)
{
if (!Session::has('cart')) {
return redirect()->route('shop.shoppingCart');
}
$oldCart = Session::get('cart');
$cart = new Cart($oldCart);
Stripe::setApiKey(''); // not showing this key (censored)
try {
Charge::create(array(
"amount" => $cart->totalPrice * 100,
"currency" => "usd",
"source" => $request->input('stripeToken'), // obtained with first code i wrote above
"description" => "Test Charge"
));
} catch (\Exception $e) {
return redirect()->route('checkout')->with('error', $e->getMessage());
}
Session::forget('cart');
return redirect()->route('product.index')->with('success', 'Successfully purchased products!');
}
}
it keep return the catch that throw exception error message, is this mean it failed to get the stripetoken, how am i suppose to fix this? please help me
hi i think i figured out the problem, i rest the the api keys and also i check your spaces between the quotation marks in the public and secret keys,
Stripe.setPublishableKey('pk_anjndjxnh8hih9u220822');
and
Stripe::setApiKey('sk_dkneijhf9u9ue9ujednf9hefnie'); // not showing this key (censored)
try this Stripe: Must provide source or customer it is work for me!
just adding script with jquery-3.1.1.min.js like <script type="text/javascript" src="/javascripts/jquery-3.1.1.min.js"></script> before calling your checkout js file.
I am developing websites where I am using AngularJS in frontend and Laravel php framework in backend.
I have one simple form that is sending $http.post call to laravel backend and there are data processed and email is sended.
Everything works fine on my local Apache server but on online on webhosting server it returns 502 (bad gateway error) in developer console (see screenshot below).
Screenshot: http://s32.postimg.org/bwnxyps1x/502.jpg
And yet, when this error appears, script in backend is executed and email is sended. It is really weird.
In AngularJS I have simple factory that is sending $http.post call...
var sendForm = function sendForm($http) {
return {
sendForm: function($scope) {
return $http({
method: 'POST',
url: '/odeslat',
data: {titul: $scope.form.titul, jmeno: $scope.form.jmeno, prijmeni: $scope.form.prijmeni, email: $scope.form.email,
telefon: $scope.form.telefon, zprava: $scope.form.zprava, human: $scope.form.human}
});
}
}
};
module.exports = sendForm;
This is my controller.
var formularCtrl = function formularCtrl($scope, sendForm) {
$scope.form = {};
$scope.form.human = 'Jsem člověk.';
var odeslano = false;
$scope.submitForm = function submitForm(isValid) {
$scope.showErrorMessage = false;
$scope.errorMessage = "";
if((isValid) && (!odeslano))
{
sendForm.sendForm($scope).success(function(data){
if (!data.success) {
// if not successful, bind errors to error variables
$scope.errorMessage = data.message;
$scope.showErrorMessage = true;
} else {
// if successful, bind success message to message
$scope.message = data.message;
$scope.showMessage = true;
odeslano = true;
}
});
}
else
{
$scope.showErrorMessage = true;
$scope.errorMessage = "Doplňte prosím všechny povinné údaje. ";
}
}
};
module.exports = formularCtrl;
And finally this is just simple method in laravel controller.
public function sendForm(Request $request) {
$v = Validator::make($request->all(), [
'jmeno' => 'required'
]);
if($v->passes()) {
$input = $request->all();
$this->sendMessage($input);
return response()->json(['success' => true, 'message' => 'Formulář byl odeslán. Jakmile to bude možné, budete kontaktováni.']);
}
elseif($v->fails())
{
$input = $request->all();
return response()->json(['success' => false, 'message' => 'Musíte doplnit povinné údaje']);
}
}
private function sendMessage($input)
{
Mail::send('emails.formular', $input, function($message)
{
$message->from(self::FROM, self::SUBJECT);
$message->to(self::TO);
});
}
I am not expert on AngularJS and I am really confused by this error. Do you have any suggestions – what can be the cause?
Thank you very much! All tips are appreciated.
502 indicates the server could not complete something properly. So it is sending out an e-mail, but maybe it tries to something after that script like update a DB. As your local is working OK and your remote is working partially OK this boils down to some server issue, is it possible there is more logging on this server that can tell us why the 502 is being issued. Perhaps the e-mail program returns this after attempting to send the e-mail?
It seems just like backend doesn't send anything back to your angular app. It should response with OK (200 for example) HTTP status.
Okay. So I have contacted webhosting provider and they turned off OPcache in htaccess and it is working now... :)