how to fill field values using ajax in yii2? - ajax

I am using ajax in yii2.
How to fill fields without submit form. Without submitting the validation is working, but how to add field value.
In below code $this->name is my field name.
if($this->statusOk){
$this->name = "gana";
}else{
return $this->addError('branch_code', ' code can’t be found');
}

you can set your value in save function(in model) or before saving your model(in controller) ,and use custom validation just for validation.

Try this,custom ajax
$(document).ready(function () {
$("body").on("blur", "#id", function () {
var data = $("#nameField").val();
$.ajax({
url : "validURL",
type : "post",
data : {"sortcode":data},
success: function (response)
{
var json_obj = $.parseJSON(response);
if(json_obj.errorMessage) {
// do something
}else {
// do something
}

Related

How to make layout false in Laravel If request is ajax

I have trying to load a page using simple get request
<script>
$(document).ready(function(){
$("li").click(function(e){
e.preventDefault();
var href = $("a",this).attr('href');
$.ajax({
async: true,
type: "GET",
url: href,
success: function (response) {
$('#main-content').html(response);
}
})
});
});
</script>
In response I am getting content with full layout. But Here I am trying to get only content without layout. In controller I have written code like below
public function index()
{
if ($request->ajax())
{
$this->layout = null; //but same result
}
$tags = Tag::orderBy('id', 'desc')->paginate(10);
return view('admin.tags.index')->with('tags',$tags);
}
But I am getting same result with layout, how can I make layout false ? Or can change layout in controller ?
you can use the renderSections
return view('admin.tags.index')->renderSections()['content'];
https://laravel-tricks.com/tricks/render-view-without-layout
Well, you are still returning a view. Why not do:
return response()->json(["data"=>"some data"]);
after your Ajax check? This will return a JSON response to your frontend.

Laravel 5.4 - forgot password ajax validation

I have a generic AJAX form submit JS class:
$(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('.ajax-form').submit(function() {
var form = $(this);
var url = form.attr('action');
var data = form.serialize();
if (!form.hasClass('valid')) {
$.ajax({
url: url,
type: 'post',
data: data,
dataType: 'json',
success: function(result) {
$('.field').removeClass('has-error');
form.addClass('valid');
form.submit();
},
error: function(result) {
var errors = result.responseJSON;
$('.field').removeClass('has-error');
$.each(errors, function(key, value) {
var field = $('.field.' + key);
field.addClass('has-error').children('.error-message').text(value[0]);
});
}
});
return false;
}
});
});
This works great for AJAX validation on all my forms. I am now trying to implement this on the default "forgot password" form that is generated with the auth scaffold (resources/views/auth/passwords/email.blade.php).
<form class="ajax-form" method="POST" action="{{ route('password.email') }}">
...
</form>
Although the AJAX validation is working here, the problem I am having is that when the validation passes, it is also performing the "forgot password" functionality. So basically it sends the reset password email twice (once during the AJAX submit and once during normal form submit).
I only want the AJAX submit to perform validation. If validation is successful it should (as it currently does) perform a normal form submit which will send the email.
Did you want to keep the Ajax submit but remove the normal form submit? If so then assuming you have a button to submit the form, you can keep the form from submitting in this answer:
Want html form submit to do nothing
If I understand the issue correctly you need to prevent Form Default behavior and validate and if everything is validated, resume the default form behavior to submit the data.
$('.ajax-form').submit(function(evt) {
evt.preventDefault(); // This would prevent default form submission functionality
var form = $(this);
var url = form.attr('action');
var data = form.serialize();
if (!form.hasClass('valid')) {
$.ajax({
url: url,
type: 'post',
data: data,
dataType: 'json',
success: function(result) {
$('.field').removeClass('has-error');
form.addClass('valid');
form.unbind('submit').submit(); // Submit the Form If everything is validated
},
error: function(result) {
var errors = result.responseJSON;
$('.field').removeClass('has-error');
$.each(errors, function(key, value) {
var field = $('.field.' + key);
field.addClass('has-error').children('.error-message').text(value[0]);
});
}
});
return false;
}
});
Here is the correct way to resolve this. In Auth\ForgotPasswordController override the sendResetLinkEmail function as follows:
/**
* Send a reset link to the given user.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\RedirectResponse
*/
public function sendResetLinkEmail(Request $request)
{
$this->validate($request, ['email' => 'required|email']);
// Inserted this piece of code which checks for AJAX request
if ($request->ajax()) {
return response()->json();
}
// We will send the password reset link to this user. Once we have attempted
// to send the link, we will examine the response then see the message we
// need to show to the user. Finally, we'll send out a proper response.
$response = $this->broker()->sendResetLink(
$request->only('email')
);
return $response == Password::RESET_LINK_SENT
? $this->sendResetLinkResponse($response)
: $this->sendResetLinkFailedResponse($request, $response);
}
By doing if ($request->ajax()) we allow it to check for ajax request and only return a json response. Then in the subsequent request when it does a regular form post it will perform the forgot password functionality.

how to access a controller function from outside of controller in codeigniter

I have a folder (suppose it's name is "test") outside of controller folder which contains a file name "error404.php" and my controller name is "test_controller.php" which has a method name "tst()". error404.php is a view page in where i want to access data from test_controller.php via ajax.
<script>
$(document).ready(function(e) {
$('#search_items_err').keyup(function(e) {
if($('#search_items_err').val().trim()==''){$('#sugglist').html(''); return false;}
search_key=$(this).val().trim();
var data = {
search_key: search_key
};
alert(search_key);
$.ajax({
data: data,
type: "post",
url: "test_controller/tst",
success: function(response) {
var options = JSON.parse(response);
alert(options);
}
});
});
});
</script>
My tst function is:
public function tst(){
$search_key = $_POST['search_key'];
echo "success";
}
But my ajax doesn't work. I suspect that it may contain some problems in the (url: "test_controller/tst",). So how can i solve it? What is the syntax of accessing test_controller's method from error404.php page?How do i access base url?
Take a look at this ajax concept
in your ajax function :
url : baseURL+'test_controller/search', //Make sure this url is working properly
data : {'search_key' : search_key},
in you test_controller/search
public function search()
{
//generate data and load your view
$data = "Generated Data array";
$this->load->view('test_folder/search', $data); //Load your view from application/view/ not from outside the controller
}

Ajax call not fetching data from model in cakephp

My ajax is getting called but it is not fetching data from the model, so validations are not happening.In controller data is not getting picked from model and consequently the success function is not capturing any data.
I am doing in the first name field in signup tab popup.
Here is the ajax call code
JS code, validation.js
var ajaxHandler = function() {
$.ajax({
method: 'post' ,
url : '/medicare/Users/validate_form' ,
params : {
field:$('#first_name').attr('id'),
value: $('#first_name').val()
} ,
success: function(data){
console.log("Successful");
} ,
error : function(e){
console.log(e) ;
}
}) ;
}
Controller action, validate_form
public function validate_form(){
if($this->RequestHandler->isAjax()){
$this->request->data['User'][$this->request['form']['field']] = $this->request['form']['value'];
$this->User->set($this->data);
if($this->User->validates()){
$this->autoRender = FALSE;
}
else{
$error = $this->validateErrors($this->User);
$this->set('error',$this->User->validationErrors[$this->request['data']['field']][0]);
}
}
}
There is no data sending on POST request because you wrote-
params: {
field:$('#first_name').attr('id'),
value: $('#first_name').val()
} ,
it should be as-
data : {
field:$('#first_name').attr('id'),
value: $('#first_name').val()
} ,

Ajax post request from Backbone to Laravel

I'm trying to send a Backbone collection to Laravel with an Ajax Request.
I don't need to save it or update the database I just need to process the data with the Omnypay php Api. Unfortunately the Laravel Controller variable $input=Input::all() contain an empty string.
var url = 'index.php/pay';
var items = this.collection.toJSON;
$.ajax({
url:url,
type:'POST',
dataType:"json",
data: items,
success:function (data) {
if(data.error) { // If there is an error, show the error messages
$('.alert-error').text(data.error.text).show();
}
}
});
This is the Laravel Route:
Route::post('pay','PaypalController#doPay');
And finally the Laravel Controller:
class PaypalController extends BaseController {
public function doPay() {
$input=Input::all();
}
}
Your route doesn't match, it's
Route::post('pay','PaypalController#doPay');
So the url should be
var url = 'pay';
instead of
var url = 'index.php/pay';
BTW, not sure if anything else (backnone) is wrong.
Update : toJSON is a method, so it should be (you missed ())
var items = this.collection.toJSON();
The hack solution I found to transfer a backbone collection to Laravel was to convert the collection to JSON and then wrapping it in a plain object, suitable for the jQuery Ajax POST. Here is the Code:
var url = 'index.php/pay';
var items = this.collection.toJSON();
var plainObject= {'obj': items};
$.ajax({
url:url,
type:'POST',
dataType:"json",
data: plainObject,
success:function (data) {
if(data.error) { // If there is an error, show the error messages
$('.alert-error').text(data.error.text).show();
}
}
});
Now the $input variable of my "doPay" controller function contain an array of Backbone models.

Resources