crud ajax jquery symfony3 wont work - javascript

Problem: How do I validate the form and return the validation messages in modal box without refreshing the page.
I just started learning Symfony 3 and I got trouble adding data using AJAX.
I know how to include the template form inside of the modal box but I don't know how to show the error messages of $form->isValid() inside the modal and persist it.
new.html.twig
UPDATE: I can now call the method action in Controller. But when I validate the form I haven't received any validation error inside modal box.
<script>
$(function () {
$('.withdropdown').dropdown();
$('.add-company-launch').modal();
$('#company-form').submit(function(e) {
var formUrl = "{{ path('monteal_backend_company_ajax') }}";
var formData = new FormData(this)
$.ajax({
url: formUrl,
type: 'POST',
data: formData,
contentType: false,
cache: false,
processData: false,
success: function(data, textStatus, jqXHR)
{
if(data['status'] === 'success'){
alert('success');
} else {
$('#add-company').html(data['html']);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
}
});
e.preventDefault();
});
})
</script>
{% endblock %}
CompanyController.php
UPDATE: I have create two methods for AJAX,
1. Method to handle a form.
2. AjaxHandler.
public function newAction() {
$company = new Company();
$form = $this->createForm(CompanyForm::class, $company);
return $this->render('Admin/Backend/Company/new.html.twig', array(
'form'=>$form->createView()
));
}
public function ajaxAction(Request $request) {
if (!$request->isXmlHttpRequest()) {
return new JsonResponse(array('message' => 'You can access this only using Ajax!'), 400);
}
$company = new Company();
$form = $this->createForm(CompanyForm::class, $company);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($company);
$em->flush();
return new JsonResponse(array(
'status' => 'success'), 200
);
}
$html = $this->renderView("Admin/Backend/Company/new.html.twig", array(
'form' => $form->createView())
);
return new JsonResponse(['status' => 'error', 'html' => $html]);
}

1 - In your newAction, just create the form and pass the view (createView) to your template.
2 - write a ajaxFormHandlerAction and here create the form, handle it, validate it, render a view in a variable :
$html = $this->renderView('yourTemplate.html.twig', array($form->createView()));
Edit: of course your ajax must post the form to your newly ajax url... END Edit
3 - if it is'nt validated
Return a JsonResponse(array('html' => $html, 'status' => 'error'));
if validated
Return a JsonResponse(array('status' => 'success'));
4 - In your ajax success callback, render the newly form if status error..
if status success, redirect or whatever
Hope this help
Edit :
something like this for your controler :
use Symfony\Component\HttpFoundation\JsonResponse;
public function ajaxFormHandlerAction(Request $request)
{
$company = getYourCompany(); //get it from db?
$form = $this->createForm(CompanyForm::class, $company));
$form ->handleRequest($request);
if($form ->isValid()){
//do whatever you want, maybe persist, flush()
return new JsonResponse(array(
'status' => 'success'));
}
$html = $this->renderView("yourModalTemplate.html.twig", array('form' => $form->createView()));
return new JsonResponse(['status' => 'error', 'html' => $html]);
}
And in your success ajax callback:
success: function(data, textStatus, jqXHR)
{
if(data['status'] === 'success'){
alert('success');
// maybe redirect the user ???
}else if(data['status' === 'error']){
$('#idOfYourModal').html(data['html']); //assuming you use jquery, or translate to javascript
}
},
You have to create a twig template with only the modal inside...

Related

Unable to Show Meta information with Post

I am practicing on a very simple Laravel project with AJAX and jQuery. I am trying to edit post and its meta information which I added before. I Tried console.log and its showing me post with meta information. Post is coming from posts table and meta information is coming from post_metas table where I added post_id as forign key. Post data is showing in edit modal but I am unable to put meta information in their specific fields in edit Modal.
Here is my PostController.php
public function edit($id)
{
$post = Post::with('meta')->find($id);
if ($post) {
return response()->json([
'status' => 200,
'post' => $post,
]);
} else {
return response()->json([
'status' => 404,
'message' => 'Post Not Found',
]);
}
}
Here is Index.blade.php (jQuery AJAX Code)
$(document).on('click', '.edit_post_btn', function(e) {
e.preventDefault();
var post_id = $(this).val();
var route_url = "{{ route('blog.edit', ':id') }}";
route_url = route_url.replace(':id', post_id);
$.ajax({
type: "GET",
url: route_url,
success: function(response) {
if (response.status === 200) {
console.log(response.post);
$('#edit_title').val(response.post.title);
$('#edit_excerpt').val(response.post.excerpt);
$('#edit_content').val(response.post.content);
$('#edit_min_to_read').val(response.post.min_to_read);
$('#edit_meta_description').val(response.post.meta_description);
$('#edit_meta_keywords').val(response.post.meta_keywords);
$('#edit_meta_robots').val(response.post.meta_robots);
} else {
console.log(response.message);
}
}
});
});
And This is My route:
Route::get('/edit/{id}', [PostController::class, 'edit'])->name('blog.edit');
See File Please:
Meta information is in the meta object:
$('#edit_meta_description').val(response.post.meta.meta_description);
$('#edit_meta_keywords').val(response.post.meta.meta_keywords);
$('#edit_meta_robots').val(response.post.meta.meta_robots);

Laravel 6 Error - Undefined property: App\Http\Controllers\GetContentController::$request

I am trying to send form data including files (if any) without form tag via Ajax request. However, I am getting the following error message
Undefined property: App\Http\Controllers\GetContentController::$request
Here are my codes
Controller
public function GetContentController($params){
$CandidateFullName = $this->request->CandidateFullName;
$CandidateLocation=$this->request->CandidateLocation;
//inserted into database after validation and a json object is sent back
Web.php
Route::match(['get', 'post'], '{controller}/{action?}/{params1?}/{params2?}', function ($controller, $action = 'index', $params1 = '',$params2 = '') {
$params = explode('/', $params1);
$params[1] = $params2;
$app = app();
$controller = $app->make("\App\Http\Controllers\\" . ucwords($controller) . 'Controller');
return $controller->callAction($action, $params);
})->middleware('supadminauth');
Blade
<input type="text" id="CandidateFullName" name="CandidateFullName" class="form-control">
<input type="text" id="CandidateLocation" name="CandidateLocation" class="form-control">
<button id="final_submit">Submit</button>
<script>
$('#final_submit').click(function(e){
e.preventDefault();
var data = {};
data['CandidateFullName']= $('#CandidateFullName').val();
data['CandidateLocation']=$('#CandidateLocation').val();
submitSaveAndNext(data)
});
function submitSaveAndNext(data){
//console.log(data);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': '{{csrf_token()}}'
}
});
$.ajax({
type : "POST",
url : '{{url("GetContent/submitContent")}}', //GetContentController ,but without Controller in the end
dataType : "json",
contentType : "application/json",
data : JSON.stringify(data),
success : function(response){
//console.log("response ",response);
if(response.message=="success"){
swal({
title:"Success",
type: "success",
});
}else{
swal({
title:"Sorry! Unable to save data",
type:"warning"
})
}
},
error:function(xhr, status, error){
swal({
title:"Sorry! Unable to save data",
type:"warning"
})
}
}) //ajax ends
I don't think controller instance in laravel possess the property having request instance, you'll have to type-hint to obtain the object of the request
public function GetContentController($params) {
// $this->request is the issue
$CandidateFullName = $this->request-> CandidateFullName;
$CandidateLocation = $this->request->CandidateLocation;
}
So you can try either of the below-given solutions
// make sure include the Request class into your controller namespace
public function GetContentController($params, Request $request) {
$CandidateFullName = $request->input('CandidateFullName');
$CandidateLocation = $request->input('CandidateLocation');
}
Or use the helper function for request
public function GetContentController($params) {
$CandidateFullName = request('CandidateFullName');
$CandidateLocation = request('CandidateLocation');
}
These links will help you get more details :
https://laravel.com/docs/8.x/requests#accessing-the-request
https://laravel.com/docs/5.2/helpers#method-request

How to pass hidden field value via ajax to codeigniter controller

I have a view file which contains a button (link):
<a href id="savebutton" class="btn btn-warning">Save</a>
Somewhere else in this view I have also declared some hidden fields in a form that contain my userid and vacancyid.
echo form_input(dataHiddenArray('userid', $this->auth_user_id));
echo form_input(dataHiddenArray('vacancyid', $vacancydetails[0]->vacancy_id));
These hidden fields translate to:
<input type="hidden" value="2" class="userid">
<input type="hidden" value="1" class="vacancyid">
Now I want to be able to send these values to my controller (via AJAX) so that I can insert them in my database.
My JS file looks like this:
$(function() {
var postData = {
"userid" : $("input.userid").val(),
"vacancyid" : $("input.vacancyid").val()
};
btnSave = $('#savebutton'),
ajaxOptions = {
cache: false,
type: 'POST',
url: "<?php echo base_url();?>dashboard/vacancy/saveVacancy",
contentType: 'application/json',
dataType: 'text'
};
btnSave.click(function (ev) {
var options = $.extend({}, ajaxOptions, {
//data : $(this).closest('form').serialize()
data: postData
});
ev.preventDefault();
// ajax done & fail
$.ajax(options).done(function(data) {
alert(data); // plausible [Object object]
//alert(data[0]); // plausible data
console.log(data); // debug as an object
}).fail(function (xhr, status, error) {
console.warn(xhr);
console.warn(status);
console.warn(error);
});
});
And my controller looks like this (it is not doing much because it doesn't return anything):
public function saveVacancy() {
//$this->load->model('user/usersavedvacancies_model');
/*$data = array(
'userid' => $this->input->post('userid'),
'vacancyid'=>$this->input->post('vacancyid')
);*/
echo $this->input->post('userid');
}
Minor changes to javascript
$(function () {
var postData = {
"userid": $("input.userid").val(),
"vacancyid": $("input.vacancyid").val()
};
btnSave = $('#savebutton'),
ajaxOptions = {
type: 'POST',
url: "<?php echo base_url('dashboard/vacancy/saveVacancy);?>",
dataType: 'json'
};
btnSave.click(function (ev) {
var options = $.extend({}, ajaxOptions, {
//data : $(this).closest('form').serialize()
data: postData
});
ev.preventDefault();
// ajax done & fail
$.ajax(options).done(function (data) {
console.log(data); // debug as an object
if (data.result === 'success') {
alert("Yeah, it saved userid " + data.userid + " to vacancy id " + data.vacancyid);
}
}).fail(function (xhr, status, error) {
console.warn(xhr);
console.warn(status);
console.warn(error);
});
});
});
In the controller
public function saveVacancy()
{
//assigning a more useable object name to the model during load
$this->load->model('user/usersavedvacancies_model', 'save_vacancy');
$data = array(
'userid' => $this->input->post('userid'),
'vacancyid' => $this->input->post('vacancyid')
);
//send data to model and model returns true or false for success or failure
$saved = $this->save_vacancy->doSaveId($data); //yes, I made up the method, change it
$result = $saved ? "success" : "failed";
echo json_encode(array('result' => $result, 'userid' => $data['userid'], 'vacancyid' => $data['vacancyid']));
}
You need to understand that $.ajax takes two methods i.e GET and POST and from the documentation you can see that default method is GET so Since you have not defined method as GET/POST probably the method is taken GET so first change define ajax method to POST as well as you need to be clear about dataType of ajax it may be one of JSON/html and default is json.
$.ajax({
method: "POST",
url: url,
data: data,
dataType:'html'
});
I guess this helped you can learn detail from
Learn more.

How to validate form data using form_validation in codeigniter submitted using ajax

I'm writting a code using CodeIgniter
ajax
var formData = {};
var url = $(form_id).attr("action");
$(form_id).find("input[name]").each(function (index, node) {
formData[node.name] = node.value;
});
$(form_id).find('select[name]').each(function (index, node) {
formData[node.name] = node.value;
});
$(form_id).find('textarea[name]').each(function (index, node) {
formData[node.name] = node.value;
});
$.ajax({
type: "POST",
data: {
'formdata': formData
},
url: url,
dataType: 'json',
success: function(result) {
if (result.data) {
make_alert();
} else {
$('#error-msg').html(result.message);
}
},
error: function(result) {
// error code here
}
});
Which will sent a data formData to add function in controller
add function
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required',
array('required' => 'You must provide a %s.')
);
$this->form_validation->set_rules('email', 'Email', 'required');
and this part here receive the formData values
$post_data = $this->input->post('formdata');
$data = array (
'username' => $post_data['username'],
'email' => $post_data ['email'],
'password' => $post_data ['password']
);
and this part run the validation
if ($this->form_validation->run() == FALSE) {
$result['message'] = validation_errors();
} else {
$result['data'] = $this->ion_auth->register($data['identity'], $data['password'], $data['email'], $data['additional_data'], $data['group']);
}
which return json
echo json_encode($result);
before using ajax, the code run smoothly without problem, but when using ajax, the validator return a message saying fields should be required, meaning, it doesn't receive form data submitted.
this part,
$data = array (
'username' => $post_data['username'],
'email' => $post_data ['email'],
'password' => $post_data ['password']
);
when using var_dump() on $data show it received form data submitted using ajax.
My question is, how to validate this $data using form_validation?
You cant validate using form_validation library
You should validate manually usin if statement and you will set error message as you want

Getting Alert from ajax request

I have editable html table of user Information. There are some columns such as user_ID, branch_ID etc. when I am going to change the branch_ID of the user I want to check the particular user has tasked assigned to him or not. If he has tasks then update is not allowed. for that I am using the following java script part.
if(field=='branch_ID'){
$.ajax({
type: 'post',
url: 'check_user.php',
data: {udata: user_id},
success: function (data) {
// message_status.text(data);
}
})
}
In check_user.php
$user_id= $_POST['udata'];
$sql1="SELECT * FROM assign_task WHERE user_ID=$user_id";
$query1=mysqli_query($con,$sql1);
if(mysqli_num_rows($query1)>0){
echo"you can't update";
return false;
}
else{
echo"ok with it".$sql1;
}
The thing is I want the respond from check_user.php as an alert and return false to stop updating the content. As I am new to jQuery please help me.
You can use JSON to pass more complex data:
PHP :
if(mysqli_num_rows($query1)>0){
echo json_encode(array("success" => false));
}
else{
echo json_encode(array("success" => true,
"message" => "ok with it".$sql1));
}
Javascript:
success: function (data) {
var jsonData = JSON.parse(data);
if(jsonData.success){
alert(jsonData.message);
}
}
Remember to do more advanced checking on your variables and types first!

Categories

Resources