Symfony2 + Ajax: remove form error - javascript

I am trying to create entity via Symfony2 and Ajax. When I try to enter existing name, I want to get error under 'Name' textbox. After entering another correct name, I want error message to remove and submit from successfully. My code is not submitting correct data, but keeps adding more error messages.
Controller
public function createSubmitAction(Request $request){
$collection = new Collection();
$user = $this->getUser();
$form = $this->createForm(
new CollectionType(),
$collection
);
$form->handleRequest($request);
$colname = $form["name"]->getData();
$existing = $this->getDoctrine()->getRepository('CollectionBundle:Collection')->findBy(['name' => $colname, 'user' => $user]);
if ($existing != NULL) {
return new JsonResponse(['error' => 'already exists']);
}
if ($form->isValid() && $form->isSubmitted()) {
$em = $this->getDoctrine()->getManager();
$collection->setUser($user);
$em->persist($collection);
$em->flush();
return new JsonResponse([
'id' => $collection->getId(),
'name' => $collection->getName()
]);
}
}
Javascript
function createInObjectCollection(){
var $form = $('#create-in-object-form');
$($form).submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: $form.attr('action'),
data: $form.serialize()
}).done(function( data ) {
if (data.error){
$('<label class="form-error">Collection with such name already exists</label>').insertAfter('#mymini_collectionbundle_collection_name');
$('#mymini_collectionbundle_collection_name').addClass('error');
}
else{
$("#collection_bundle_add_to_collection option:first-child").after('<option value='+ data.id + '>' + data.name + '</option>');
$('#createCollectionModal').foundation('reveal', 'close');
}
});
});
}

I have a similar situation. And I use EventListener:
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
function (FormEvent $event) {
$form = $event->getForm();
$data = $event->getData();
\\...
}
);
And you can use Events like "SUBMIT" and "PRE_SUBMIT".

Related

my data not update in the database in laravel 5.4

I am using laravel 5.4 in my app I update some record through ajax jquery I get the data from form values through ajax function and append it in array and pass that array (formData in my code) to ajax data then when I request my data in controller it updated as null message in my database.
This is my view jquery function
$('#updateProduct').on('submit', function(e){
e.preventDefault(e);
var redirect_url = $(this).find("[name='redirect_url']").val();
var url = $(this).attr('action');
var method = $(this).attr('method');
var video = document.getElementById('videoToUpload').files[0];
// console.log(video);
var formData = new FormData();
formData.append('_method', 'patch');
formData.append('name', $(this).find("[name='name']").val());
formData.append('description', $(this).find("[name='description']").val());
formData.append('brand', $(this).find("[name='brand']").val());
formData.append('category', $(this).find("[name='category']").val());
formData.append('condition', $(this).find("[name='condition']").val());
formData.append('shipper', $(this).find("[name='shipper']").val());
formData.append('shipping_from', $(this).find("[name='shipping_from']").val());
formData.append('shipping_paid_by', $(this).find("[name='shipping_paid_by']").val());
formData.append('shipping_within', $(this).find("[name='shipping_within']").val());
formData.append('shipping_weight', $(this).find("[name='shipping_weight']").val());
formData.append('shipping_fee', $(this).find("[name='shipping_fee']").val());
formData.append('seller_get', $(this).find("[name='seller_get']").val());
formData.append('price_per_unit', $(this).find("[name='price_per_unit']").val());
formData.append('selling_fee', $(this).find("[name='selling_fee']").val());
formData.append('seller_id', $(this).find("[name='seller_id']").val());
formData.append('is_active', $(this).find("[name='is_active']:checked").val());
console.log(formData);
$.ajax({
type: method,
url: url,
dataType: 'JSON',
data: formData,
contentType: false,
processData: false,
success: function(data){
alert("Products updated successfullly");
console.log(data);
//window.location.href = redirect_url;
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
In my controller
public function update(Request $request, $id)
{
return Response::json([
'message' => $request['name']
], 200);
if(!$request){
return Response::json([
'error' => [
'message' => 'Kindly provide all the required details'
]
], 422);
}
$product = Product::find($id);
$product->name = $request['name'];
$product->sku = $request['sku'];
$product->slug = $request['slug'];
$product->description = $request['description'];
$product->brand = $request['brand'];
$product->condition = $request['condition'];
$product->shipper = $request['shipper'];
$product->shipping_from = $request['shipping_from'];
$product->shipping_fee = $request['shipping_fee'];
$product->shipping_paid_by = $request['shipping_paid_by'];
$product->shipping_within = $request['shipping_within'];
$product->shipping_weight = $request['shipping_weight'];
$product->selling_fee = $request['selling_fee'];
$product->seller_get = $request['seller_get'];
$product->price_per_unit = $request['price_per_unit'];
///$product->seller_id = $request['seller_id'];
$product->is_active = $request['is_active'];
$product->save();
$category = ProductCategory::where('product_id', '=', $id);
$category->update([
'category_id' => $request['category']
]);
return Response::json([
'message' => $product
], 200);
}

crud ajax jquery symfony3 wont work

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...

ajax passing two forms with codeigniter

I have a problem related with passing two forms in ajax to my controller code igniter. My first form is a file var formData = new FormData($('#form-upload')[0]);
and my second form consists of profile data $('#frm_patientreg').serialize()
now my problem is how can I pass these two forms in ajax?
I already tried this code:
var fileToUpload = inputFile[0].files[0];
if(fileToUpload != 'undefine') {
var formData = new FormData($('#form-upload')[0]);
$.ajax({
type: "POST",
url: siteurl+"sec_myclinic/addpatient",
data: $('#frm_patientreg').serialize()+formData,
processData: false,
contentType: false,
success: function(msg) {
alert("Successfully Added");
$('#frm_patientreg')[0].reset();
}
});
}
else {
alert("No File Selected");
}
but it returns me an error.
When I tried to pass data:formData, only, my image file was successfully uploaded, but when I add the $('#frm_patientreg').serialize(), it outputs an error. How can I pass both forms?
Here is my controller:
public function addpatient() {
$config['upload_path'] = './asset/uploaded_images/';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = 1024 * 8;
$this->load->library('upload', $config);
if($this->upload->do_upload("file")) {
$upload_data = $this->upload->data();
$file_name = base_url().'asset/uploaded_images/'.$upload_data['file_name'];
$mypatiendid = $this->genpatient_id();
$patient_bday = $this->input->post('pabdate');
$DB_date = date('Y-m-d', strtotime($patient_bday));
$patient_height = $this->input->post('paheight');
$DB_height = $patient_height . " cm";
$patient_weight = $this->input->post('paweight');
$DB_weight = $patient_weight . " kg";
$data = array (
'patient_id' => $mypatiendid,
'patient_fname' => $this->input->post('pafname'),
'patient_mname' => $this->input->post('pamname'),
'patient_lname' => $this->input->post('palname'),
'patient_address' => $this->input->post('paaddress'),
'patient_contact_info' => $this->input->post('pacontact'),
'patient_bday' => $DB_date,
'patient_age' => $this->input->post('paage'),
'patient_height' => $DB_height,
'patient_weight' => $DB_weight,
'patient_sex' => $this->input->post('psex'),
'patient_civil_status' => $this->input->post('pmartialstat'),
'patient_photo' => $file_name,
);
var_dump($data);
}
else {
echo "File cannot be uploaded";
$error = array('error' => $this->upload->display_errors()); var_dump($error);
}
}
Not tested..but try this:
var FormTwo = new FormData();
$('#frm_patientreg input, #frm_patientreg select').each(function(index){
FormTwo.append($(this).attr('name'),$(this).val());
});
FormTwo.append('file', $('#frm_patientreg input[type=file]')[0].files[0]);
$.ajax({
type: "POST",
url: siteurl+"sec_myclinic/addpatient",
data: {formTwo: FormTwo, formOne: formData},
processData: false,
contentType: false,
success: function(msg) {
alert("Successfully Added");
$('#frm_patientreg')[0].reset();
}
});
change this
data: $('#frm_patientreg').serialize()+formData,
into this
data: $('#frm_patientreg').serialize()+'&'+formData,

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

How can I dynamically post my message in CodeIgniter?

I just want to tell the user either with AngularJS or AJAX or JQuery, or whatever is easiest, that the username and email are already registered.
I already have AngularJS implemented for other checks, just not those that need php.
Here is my php function:
public function user_exists() {
$username = $this->db->escape($this->input->post('username'));
$data = array(
'username' => $username,
'email' => $this->db->escape($this->input->post('email')),
'password' => crypt($this->db->escape($this->input->
post('password'))),
'user_id' => md5('I really like pie, '. $username)
);
$does_user_exist = "SELECT COUNT(`user_id`) FROM `users` WHERE
`username` = " . $data['username'] . " || `email` = " .
$data['email'] . "";
$query = $this->db->query($does_user_exist);
if($query->num_rows() > 0) {
return true;
}
}
Please and thank you.
Why you use $data array in method? To check exists user or not you need use MVC architecture and something like this code.
For model:
class User_Model extends CI_Model
{
public function is_exists($username, $email)
{
$this->db->select('user_id');
$this->db->where(array(
'username' => $username,
'email' => $email
));
$this->db->limit(1);
return $this->db->get('users')->row('user_id');
}
}
This code for controller:
class User extends CI_Controller
{
public function is_exists()
{
$email = $this->input->post('email');
$username = $this->input->post('username');
$this->load->model('user_model');
if(!$this->user_model->is_exists($username, $email))
{
$result = array('status' => 200, 'message' => 'Username and email are free');
}
else
{
$result = array('status' => 400, 'reason' => 'User already exists');
}
echo json_encode($result);
}
}
Ajax query:
$.ajax({
url: 'user/is_exists',
type: 'POST',
dataType: 'JSON',
data: {username: username, email: email},
success: function(data, status, jqXHR){
if(data.status == 200){
alert(data.message);
}
else{
alert(data.reason);
}
}
});
username and email js variables you need get from your regisration form.
Also you can use Ion Auth or Tank Auth extensions
When the user clicks the submit button on the registration form submit it using $.post() in jQuery. The action attribute of the form should map to the appropriate controller/method. The method you call can return a JSON encoded message to display in the browser.
It could look something like this:
$(function() {
$('#registration', 'input[type="submit"]').on('click', function(event) {
event.preventDefault();
var action = $(this).closest('form').attr('action');
var form = $(this).closest('form').serialize();
$.post(action, form, function(data) {
alert(data.message);
});
});
});
In the above example the ID of the form is #registration. The JS var 'data' is the JSON object returned by your PHP method and 'message' is a property of that object containing a message to display to the user.

Categories

Resources