How to implement ajax in laravel - ajax

I am trying to implement ajax in laravel framework, where I am trying to check for the availability for the username, I was able to implement the same via core php but not able to get through laravel 4.

1) You have to define a method in your controller (i.e UserController)
public function postEmail()
{
$userCount = User::where('email', '=', Input::get('email'))->count();
if ($userCount == 0)
{
return "true";
} else {
return "false";
}
}
2) In your registration form you have to do jQuery validation like this to make a remote call on Controller method
$(document).ready(function() {
$('#registration-form').validate({
rules: {
email: {
required: true,
email: true,
remote: {
type: "POST",
url: '/user/email'
}
}
},
messages: {
email: {
remote: "The email has already been taken!"
}
},
success: function(date) {
console.log(data);
}
});

Related

Api sending data from backend to frontend

I have made an web app where the users can question and answer. By fetching the data from database, i send the required data to frontend using JSON. Here is the controller.
public function addquestion(Request $request)
{
if($request->Ajax())
{
if (Auth::check())
{
$question = new Question();
$question->question=$request->question;
$question->save();
$addq_id=new QuestionUser();
$addq_id->q_id=$question->id;
$addq_id->user_id = Auth::user()->id;
$addq_id->save();
echo json_encode(array('status'=>TRUE,'question'=>$request->question));die;
}
else
{
echo json_encode('notloggedin');die;
}
}
}
and here is jquery and ajax:
$(document).on('click','.addquestion',function(e)
{
e.preventDefault();
var question = $(this).prev().val();
$.ajax({
type:"POST",
url: "{{url('/music/addquestion')}}",
data: {
"_token": "{{ csrf_token() }}",
"question": question
},
success: function (data) {
var res = $.parseJSON(data);
if(res.status == true)
{
window.location.reload();
}
else if(res == 'notloggedin')
{
alert('You must login first!');
}
}
});
});
I also used the facebook api and google api for authentication. But, here i am confused on what is building your own api mean. Is my this app an api? I have read more of the articles that it is the interface between backend and frontend?

How to validate model using collection.create()

I'm trying to make a form validated before submit. For this, I defined a create method within the View which is responsible to call collection.create() method to create the model.
Here is a sample code:
app.ContactCreateView = Backbone.View.extend({
template: _.template($('#tpl-create-contact').html()),
initialize: function () {
this.router = new app.ContactsRouter();
this.contacts = new app.ContactsCollection();
},
events: {
'click #btn-create' : 'create',
'click #btn-cancel' : 'cancel',
},
render: function() {
this.$el.html(this.template());
return this;
},
getAttributes: function () {
console.log('getAttributes()');
var attr = {
name: $('#input-name').val().trim(),
category: $('#input-category').val().trim(),
phone: $('#input-phone').val().trim(),
email: $('#input-email').val().trim(),
};
console.log('attr : ' + JSON.stringify(attr))
return attr;
},
create: function () {
console.log('create()');
// Create the Model
this.contacts.create(this.getAttributes(), {
wait : true,
success: function () {
console.log('success');
//this.hideErrors();
var router = new app.ContactsRouter();
router.navigate('contacts', true);
},
error: function () {
console.log('error(s)')
//this.showErrors(errors);
}
});
},
The 'success' callback is well called but I don't manage to get the 'error' callback called once the model.validate() method is failing.
Here is the model with the validate method :
app.ContactModel = Backbone.Model.extend({
urlRoot: '/user',
// Default attributes for the Contact
defaults: {
name: null,
phone: null,
email: null,
category: null,
photo: "/images/placeholder.png"
},
validate: function(attrs) {
console.log('validate() : ' + JSON.stringify(attrs));
var errors = [];
if (!attrs.name) {
errors.push({name: 'name', message: 'Please fill name field.'});
}
if (!attrs.category) {
errors.push({name: 'category', message: 'Please fill category field.'});
}
console.log('errors : ' + JSON.stringify(errors));
return errors.length > 0 ? errors : false;
}
});
And the collection:
app.ContactsCollection = Backbone.Collection.extend({
model: app.ContactModel,
url: '/user',
//localStorage: new Backbone.LocalStorage('contacts-backbone'),
getById: function (iId) {
return this.where({id: iId});
},
getByName: function (iName) {
return this.where({name: iName});
}
});
I really don't understand what I'm doing wrong... If somebody can help me :-(
Regards,
when the validation is failed error callback is not called , it trigger an "invalid" event on model, and set the validationError property on the model.
method 1(listening on model):
app.ContactModel = Backbone.Model.extend({
urlRoot: '/user',
//your error catched here
initialize : function(){
this.on("invalid",function(model,error){
alert(error);
});
defaults: {
name: null,
phone: null,
email: null,
category: null,
photo: "/images/placeholder.png"
},
validate: function(attrs) {
console.log('validate() : ' + JSON.stringify(attrs));
var errors = [];
if (!attrs.name) {
errors.push({name: 'name', message: 'Please fill name field.'});
}
if (!attrs.category) {
errors.push({name: 'category', message: 'Please fill category field.'});
}
console.log('errors : ' + JSON.stringify(errors));
return errors.length > 0 ? errors : false;
}
});
method 2 (check whether validationError property is set in your view):
create: function () {
console.log('create()');
// Create the Model
this.contactModel.save(this.getAttributes(), {
wait : true,
success: function () {
console.log('success');
this.contacts.add(this.contactModel);
var router = new app.ContactsRouter();
router.navigate('contacts', true);
},
error: function () {
console.log('error(s)')
}
});
//your error catched here
if (this.contactModel.validationError) {
alert(this.contactModel.validationError)
}
},
So I played around with this for a while in an app I'm currently working on and found it kind of irritating and never really got it to work.
Instead I went the jQuery validation route and found it very helpful for doing validations. I highly recommend checking it out! It has a lot of built in validations you can just use and you can also override the error messages that display (also built in).
Example - I wanted a number only text field (excuse the coffeescript) :).
jQuery.validator.setDefaults(
debug: true,
success: "valid")
if #model.get('number_only')
$('#number_only').validate({
debug: true,
rules: {
"number[entry]": {
required: true,
range: [#model.get('min_number'), #model.get('max_number')],
number: true
}
},
messages: {
"number[entry]": {
required: "This field is required. Please enter a numeric value.",
min: jQuery.validator.format("Please enter a value greater than or equal to {0}."),
max: jQuery.validator.format("Please enter a value less than or equal to {0}."),
number: "Please enter a numeric value"
range: jQuery.validator.format("Please enter a value between {0} and {1}.")
}
}
})
If that doesn't really get what you want (seemed like you maybe are more interested in displaying the errors your server sends back whereas this route would more be validating the content before saving your model) let me know and I can see if I can figure out your problem.

Calling controller in Codeigniter via checkbox click

I need that when clicking on a checkbox, I sent it to a remote url to call a controller in Codeigniter This is what I'm trying to do...
$("#checkbox").click(function() {
if($("#checkbox").is(':checked')) {
alert("go to url");
} else {
alert("isnt active");
}
});
Use ajax to make the request to the server.
$.ajax({
url: "http://example.com/controller-name/function-name/parameter1",
cache: false
}).done(function(data) {
//Do something with the response.
});
See: http://api.jquery.com/jQuery.ajax/
you can try this
$("#checkbox").click(function() {
if($("#checkbox").is(':checked')) {
$.ajax({
url:base_url+'your_controller_name/your_function_name',
type: 'post',
data:{any data you want to sent},
success : function(resp){
if(resp)
{
//do what you want
}
},
error : function(resp){}
});
} else {
alert("isnt active");
}
});
Please let me know if you face any problem.
UPDATE
May be you want like this.
$("#checkbox").click(function(){
if($("#checkbox").is(':checked')) {
window.location.href="domain_name/your_controller_name/your_function_name";
} else {
alert("isnt active");
}
});

Ajax simple login

I have this simple Ajax code, my question is only, what does data.logged return, and what i need to have in the logged.php file...
I'm new to ajax, sorry for the dumb question...
$.ajax('logged.php', {
data: {
login: login,
pass: pass
},
success: function(data)
{
if (data.logged)
{
setTimeout(function() {
document.location.href = 'index.php'
}, 2000);
}
else
{
setTimeout(function() {
formLogin.clearMessages();
displayError('Utilizador ou password errados');
}, 2000);
}
},
error: function()
{
formLogin.clearMessages();
displayError('Error while contacting server, please try again');
}
});
On the client side, adding dataType : 'json' worked for me.
$.ajax('handler.php', {
data: {
login: login,
pass: pass
},
dataType : 'json',
success: function(data)
{
//code here
}
//more code here
}
And then on the server side:
$user = $_GET['login'];
$pass = $_GET['pass'];
$result = array();
if( /* login logic here */) {
$result['logged'] = 'true';
} else {
$result['logged'] = false;
}
header('Content-type: application/json');
echo json_encode($result);
That's a jQuery AJAX request which will be expecting responseText in JSON format. In this case, it seems like the JSON returned by your PHP file only needs to have a single property logged which will be either true or false depending on whether or not the login was successful.

JQuery Validation Plugin: Use Custom Ajax Method

Looking for some assistance with the Jquery form validation plugin if possible.
I am validating the email field of my form on blur by making an ajax call to my database, which checks if the text in the email field is currently in the database.
// Check email validity on Blur
$('#sEmail').blur(function(){
// Grab Email From Form
var itemValue = $('#sEmail').val();
// Serialise data for ajax processing
var emailData = {
sEmail: itemValue
}
// Do Ajax Call
$.getJSON('http://localhost:8501/ems/trunk/www/cfcs/admin_user_service.cfc?method=getAdminUserEmail&returnFormat=json&queryformat=column', emailData, function(data){
if (data != false) {
var errorMessage = 'This email address has already been registered';
}
else {
var errorMessage = 'Good'
}
})
});
What I would like to do, is encorporate this call into the rules of my JQuery Validation Plugin...e.g
$("#setAdminUser").validate({
rules:{
sEmail: {
required: function(){
// Replicate my on blur ajax email call here
}
},
messages:{
sEmail: {
required: "this email already exists"
}
});
Wondering if there is anyway of achieving this? Many thanks
You are doing an AJAX request, ergo: the validation is already finished working when your custom validator returns either true or false.
You will need to work with async. See also this post: How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?
Lets say we have a custom validation to check the Unique Mobile, So we will add a new method as follows to check the unqiue Mobile no :
jQuery.validator.addMethod("uniqueMobile", function(value, element) {
var response;
$.ajax({
type: "POST",
url: <YOUR SERVER SCRIPT/METHOD>,
data:"mobile="+value,
async:false,
success:function(data){
response = data;
}
});
if(response == 0)
{
return true;
}
else if(response == 1)
{
return false;
}
else if(response == 'logout')
{
return false;
}
}, "Mobile is Already Taken");
You can add a custom validation method like this
$.validator.addMethod('unique',
function(value) {
$.get('http://localhost:8501/ems/trunk/www/cfcs/admin_user_service.cfc','?method=getAdminUserEmail&returnFormat=json&queryformat=column&emailData='+ value,
function(return_data) {
return return_data;
})
}
, "this email already exists"
);
then add the unique class to your email field or you can use something like this
$.validator.addClassRules("unique-email", {
unique: true
});
Try this:
$.validator.addMethod('unique',
function(value) {
var result = $.ajax({
async:false,
url:"http://yoursamedomain.com/checkemail",
data:'email='+ value,
dataType:"text" });
if(result .responseText) return true; else return false;
} , "This email address has already been registered");
For serverside AJAX validation use remote rule. This is same as standard jQuery AJAX request object. Your server must returns string "true" for valid value or "false" for invalid, also it can passes some string "This email was already taken", and this will be perceived as invalid, and render as an error message:
$( "#myform" ).validate({
rules: {
email: {
required: true,
email: true,
remote: {
url: "check-email.php",
type: "post",
data: {
username: function() {
return $( "#username" ).val();
}
}
}
}
}
});
Read documentation here remote-method

Resources