I am using laravel 4 and I am trying to display login validation by using ajax. I have the following javascript validation:
jQuery('#form-signin').submit(function()
{
var url = $(this).attr("action");
jQuery.ajax({
url: url,
type: "post",
data: jQuery('#form-signin').serialize(),
datatype: "json",
beforeSend: function()
{
jQuery('#ajax-loading').show();
jQuery(".validation-error-inline").hide();
}
})
.done(function(data)
{
$('#validation-login').empty()
if (data.validation_failed === 1)
{
var arr = data.errors;
alert(arr);
}
else {
window.location = data.redirect_to;
}
})
.fail(function(jqXHR, ajaxOptions, thrownError)
{
alert('No response from server');
});
return false;
});
and in my userController:
public function doLogin() {
Input::flash();
$data = [
"errors" => null
];
if (Auth::attempt(array('email' => Input::get('email'), 'password' => Input::get('password')))) {
return Response::json(["redirect_to" => "/"]);
} else {
if (Request::ajax()) {
$response_values = array(
'validation_failed' => 1,
'errors' => 'Invalid username or password',
);
return Response::json($response_values);
}else
{
echo 'error';
}
}
}
The problem is that it always displays "error" message, which means that jaax request isn't performed. What is wrong?
In your doLogin() function try
return Response::json(array(
'validation_failed' => 1,
'errors' => 'Unknow error'
))
instead of
echo "error"
Related
I'm trying to check if same email exist in server db, but ajax is returning code 0 even my server is opened.
I checked it by using URL in browser.
if (input == email.find(".form_input").val()) {
emailChecking = true;
$.ajax({
url: "https://localhost:8888/check?target=" + input,
async: true,
type: "GET",
dataType: "text",
success: (data) => {
console.log(data);
if (emailChecking == true) {
emailChecking = false;
inputField(email, error);
}
},
error: (request, status, errorLine) => {
if (emailChecking == true) {
emailChecking = false;
error = "cannot check email - code " + request.status;
inputField(email, error);
}
}
});
}
I'm new in js and I'm having problems with my node application.
I have a function like this in the client side:
$('form#formNewCustomer').submit(function (e) {
e.preventDefault();
var $form = $(this);
$.post(
$form.attr("action"),
$form.serialize(),
function (data) { alert("first success") },
"json"
).done(function () {
alert("second success");
}).fail(function () {
alert("error");
}).always(function () {
alert("finished");
});
});
And a function like this in the server side:
app.post('/customer',
[
check('email', "Invalid E-mail.").isEmail().normalizeEmail().optional({ checkFalsy: true }),
check('name', "Empty name").trim().isLength({ min: 2 }).escape(),
],
(req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
console.log(errors)
return res.status(422).json({ errors: errors.array() })
} else {
collection.insertOne(req.body)
.then(result => {
//do something
})
.catch(error => console.error(error))
}
})
The problem is, it always alerts the 'fail' function, what can I do to return properly and to alert the 'check' messages ('invalid e-mail' for example)?
I'm trying to create AJAX form with Symfony, but my form return empty object. When I send manualy writed text or array everything works fine. Where is the bug? I do something wrong with form or javascript code is the problem?
/**
* Renders the "new" form
*
* #Route("/", name="demo_new")
* #Method("GET")
*/
public function newAction(Request $request) {
$entity = new Demo();
$form = $this->createForm(DemoType::class, $entity);
return $this->render('default/new.html.twig', array(
'entity' => $entity,
'form' => $form->createView()
)
);
}
/**
*
* #Route("/", name="demo_create")
* #Method("POST")
*
*/
public function createAction(Request $request) {
if (!$request->isXmlHttpRequest()) {
return new JsonResponse(array('message' => 'You can access this only using Ajax!'), 400);
}
$entity = new Demo();
$form = $this->createForm(DemoType::class, $entity, array(
'action' => $this->generateUrl('demo_create'),
'method' => 'POST',
));
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$data = $form->getData();
return new JsonResponse(
[
'message' => 'Success!',
'data' => $data
], 200);
}
$response = new JsonResponse(
array(
'message' => 'Error',
'form' => $this->renderView('default/new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
))), 400);
return $response;
}
}
and Javascript code:
function initAjaxForm()
{
$('body').on('submit', '.ajaxForm', function (e) {
e.preventDefault();
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize()
})
.done(function (data) {
if (typeof data.message !== 'undefined') {
console.log(data.data);
console.log(data.message);
}
})
.fail(function (jqXHR, textStatus, errorThrown) {
if (typeof jqXHR.responseJSON !== 'undefined') {
if (jqXHR.responseJSON.hasOwnProperty('form')) {
$('#form_body').html(jqXHR.responseJSON.form);
}
$('.form_error').html(jqXHR.responseJSON.message);
} else {
alert(errorThrown);
}
});
});
}
Had same issue today with version 2.8 gonna leave this here in case it end up healping someone else i've added this to my form builder
/**
* {#inheritdoc}
*/
public function getBlockPrefix()
{
return '';
}
I have the following example form below where beforeSend function shows a message that is sending and once it is sent an other function is called .done(function (data) showing a message that message has been sent. All I want to do is to use another function where the message is not sent, to display the message "error, message is not sent"
var form = $('#main-contact-form');
form.submit(function (event) {
$.ajax({
type: 'POST',
url: '../sendemail.php',
data: {
Name: name,
Subject: $form.find("input[name='subject']").val(),
Email: email,
message: $form.find("textarea[name=message]").val(),
},
beforeSend: function () {
// message is sending...
}
}) //end ajax
.done(function (data) {
// message sent!
});
});//end contact form
You can use fail api to handle errors as shown below.
Also, in the $.ajax({constObj}) you can have apis like success and error to handle the same.
Refer here for more info
//1.
$.ajax({
type: 'POST',
url: '../sendemail.php',
data: {
Name: name,
Subject: $form.find("input[name='subject']").val(),
Email: email,
message: $form.find("textarea[name=message]").val(),
},
beforeSend: function () {
// message is sending...
}
}) //end ajax
.done(function (data) {
// message sent!
})
.fail(function(){
//handle error here
});
//2.
constObj.success(function(data){
});
constObj.error(function(error){
});
Instead of .done use ajax options success and error. Throw error on server when sending email fails.
$.ajax({
success: function () {
// message sent!
},
error: function () {
// message sent failed!
}
});
On server side:
if ($this->sendMessage()) {
echo "ok";
} else {
throw new Exception('Email failed to send.', 500);
}
You can't tell if user actually receives email (I guess there is some complicated ways to figure it out).
You use done(), which is executed after a SUCCESSFUL ajax request (usually returns HTTP 200). If you read http://api.jquery.com/jquery.ajax/, there is fail(), which is executed after a FAILED ajax request.
It also depends the output of sendemail.php. If your PHP returns other than HTTP 200 when error, you can utilize fail() promise method, for example...
$.ajax({
beforeSend: function() {
$('msg').text('Sending email...');
}
}).done(function() {
$('#msg').text('Success!');
}).fail(function() {
$('#msg').text('Failed!');
});
But, if your PHP also returns HTTP 200 when error, you can do something like the following...
PHP:
$response = array(
'status' => null,
'error' => null
);
if ($mailer->send()) {
$response['status'] = true;
} else {
$response['status'] = false;
$response['error'] = 'Unable to send email';
}
jQuery:
$.ajax({
beforeSend: function() {
$('msg').text('Sending email...');
}
}).done(function(data) {
if (data.status === true) {
$('#msg').text('Success!');
} else {
$('#msg').text('Failed: ' + data.error);
}
});
i use ajax to create a session and to redirect the page when the user clicks on a button like this .. im using this in the facebook api(using the api to create a session with the user.id)
FB.login(function(response) {
if (response.session) {
FB.api('/me', function(user) {
if (user!=null) {
var request = new XMLHttpRequest();
if(document.getElementById("ans2").value==""){
document.getElementById("belowbutton2").innerHTML ="Don't leave it blank!!";
}
else{
var request2 = new XMLHttpRequest();
request.onreadystatechange=function(){
if(request.readyState==4 && request.status==200){
document.getElementById("debugger").innerHTML = request.responseText;
window.location = "weekques/weekques.php";
}
}
var uid = user.id;
alert(uid);
var jqXHR = ($.ajax)({url:"sessions.php?uid="+uid,
async:false,
cache: false,
timeout: 30000,
error:function(){
window.location = "http://www.xyz.com";
},
success:function(){
request.open("GET", "weekques/answer.php?ans="+document.getElementById("ans2").value, true); //+"&qid="+qidjs
request.send();
}
});
}
}
});
}
});
but the problem is that the window is redirecting before the session is created ..
heres the
sessions.php file
<?php
session_start();
require_once("connection.php");
$user=mysql_query("SELECT * from `thebirbals`.`FBusers` where uid='$uid';");
$row_count=mysql_num_rows($result);
$_SESSION['uid']=$_GET["uid"];
$uid = $_SESSION['uid'] ;
if($row_count==1){
$_SESSION['name'] = $check["name"];
$_SESSION['profile_link'] = $check["profile_link"];
$_SESSION['dp'] = $check["dp"];
}
else{
require_once('facebook/src/facebook.php');
$facebook = new Facebook(array(
'appId' => '1550598824560526',
'secret' => '4cf28242b5abfa26be8fd3e2074e5724',
'cookie' => false
));
$fql = "SELECT first_name,profile_url,pic_small from user where uid=$uid";
$response = $facebook->api(array(
'method' => 'fql.query',
'query' =>$fql,
));
foreach($response as $val)
{
$_SESSION['name']=$val["first_name"];
$_SESSION['dp']=$val["pic_small"];
$_SESSION['profile_link']= $val["profile_url"];
$name = $val["first_name"];
$profile_link = $val["profile_url"];
$dp = $val["pic_small"];
echo "done";
}
$insert=mysql_query("INSERT INTO `thebirbals`.`FBusers` ( `uid`, `name`, `profile_link`, `dp`) VALUES ('$uid', '$name', '$profile_link', '$dp');");
}
?>
i want to redirect after the sessions.php is finished running this does not happen
ty in advance for any help .. :)
I took a stab. Not sure if this will fix your issue entirely, but take it as a starting point:
FB.login(function (response) {
if (response.session) {
FB.api('/me', function (user) {
if (user != null) {
if (document.getElementById("ans2").value == "") {
document.getElementById("belowbutton2").innerHTML = "Don't leave it blank!!";
}
else {
var uid = user.id;
alert(uid);
$.ajax({ url: "sessions.php?uid=" + uid,
async: false,
cache: false,
timeout: 30000,
error: function () {
window.location = "http://www.xyz.com";
},
success: function () {
$.get("weekques/answer.php", $.param({ "ans": document.getElementById("ans2").value }), function (data) {
alert("Answer received");
document.getElementById("debugger").innerHTML = data;
window.location = "weekques/weekques.php";
});
}
});
}
}
});
}
});