I want to use form validation methods of CI for validating my input data. As the form submitted via AJAX I'm using serializeArray() to post data to my controller so I don't have to post on by one data or wrinting some each() function. The problem is that form validation look for data in $_POST. Using serialize() didn't help neither. Is there any solution beside extending form validation library?
here my code:
(controller)
$form_data = $this->input->post('form_data');
$this->load->library('form_validation');
$this->form_validation->set_rules('p_company_name', 'نام شرکت', 'required');
if ($this->form_validation->run() == FALSE)
{
echo "fail";die(); // if i use serialize() or serializeArray()
}
else
{
echo "success";die(); // if i use label:value for each form input
}
js code:
$.ajax({
type: "POST",
cache: false,
url: url,
data: {'form_data': form_data},
dataType: "html",
success: function(res, textStatus, xhr)
{
// do something
},
error: function(xhr, textStatus, thrownError)
{
//do something else
},
complete: function()
{
// do some final thing
},
async: true
});
Thanks in advance
post your data as:
data: form.serialize(),
and it will work as normal (form being a normal jquery reference to your page form, not just the word "form")
Related
I am using asp.net MVC 5 and trying to validate form on submission. everything works fine until i added the below line of code to validate form using ajax call.
$('#signupform').validate({
submitHandler: function (form) {
$.ajax({
type: 'POST',
data: JSON.stringify({ type: "WhatsNew", code: $('#PrimaryCode').val() }),
url: '#Url.Action("CheckCode", "Home")',
dataType: 'json',
contentType: 'application/json'
})
.done(function (response) {
if (response == 'success') {
alert('success');
}
else {
alert('failed');
}
});
return false; // required to block normal submit since you used ajax
}
});
the above code simply blocking the submission of form.
You prevented submission by return false; in order to ajax-validate the form, but the form is not submitted after successful validation.
Add a form submit trigger inside .done();
if (response == 'success') {
// since validation is success, submit form here (e.g. YourForm.submit())
}
Possible walk through:
Before submitting the form inside .done(); make sure you remove/unbind validate from you form.
Follow this link: click here for another couple of ways.
I'm trying to return a callback from an AJAX submitted form. The user submits a form, the server processes and returns the valid response, i.e. an error message and also a JavaScript function that could perform an action. I'm using Zepto.js faling back to jQuery depending on browser.
My ajax request is:
$.ajax({
success: function(data, status, xhr) {
data.callback();
},
url: form.attr('action'),
data: form.serialize(),
dataType: 'json'
});
On the server I want to return something like:
// PHP code
?>
{
return: false,
error: 'Sorry, we couldn’t find an account with that username or password.',
callback: function() {
console.log('this is the callback');
}
}
<?php
// more PHP code
When returned to the browser callback function should fire. I want the server to return the callback so I can use the same JavaScript code and have it respond accordingly to the server response.
Would I need to change the dataType to script? However I thought this was just for loading .js files, not blocks of code.
Any help appreciated.
The general feeling here is I am approaching this in the wrong way. So revised code:
$.ajax({
success: function(data, status, xhr) {
var callback = data['callback'];
callback();
},
url: form.attr('action'), // in this example it's badLogin
data: form.serialize(),
dataType: 'json'
});
// callback specified in PHP
badLogin: function() {
console.log('bad login');
}
And my PHP
if (!$valid) {
?>
{
"return": false,
"error": "Sorry, we couldn’t find an account with that username or password.",
"callback": "badLogin"
}
<?php
}
Thanks for pointing me in the right direction.
You can always return the code as a string and use eval() if you are absolutely sure that the string will always be correct and no code can be injected.
I want to validate a form with the jQuery form validation plugin but I was not able to send a custom Ajax request with the validation handler:
$('#headForm').validate(
{
//submitHandler: submit,
errorClass: "invalid",
rules: {
title: {maxlength: 50}
},
messages: {
title: {maxlength: 'Max 50 chars'}
}
});
My orginal submit handler looked like this:
$('#headForm').submit(function(event)
{
event.preventDefault();
$.ajax(
{
type: "PUT",
url: "/target",
data: $('#headForm').serialize(),
dataType: "json",
success: function()
{
alert("ok");
}
});
});
I tried to move it to a usual function and register it as a submitHandler in the validation block, but it didn't work.
function submit() { // impossible to pass the event!
$.ajax( ...
}
How can I combine jQuery validation with a custom Ajax request?
Possible form validation bug:
I've removed the validation code to see whether the submission works without it. And it did not unless I removed the link to jQuery form validation library! So it seems like validation is breaking jQuery core. Have I already said that I love dynamic typing ... ;-)
Did you define a parameter in the submit() function?
(I'm guessing that you didn't, and that could be why it didn't work)
I think you just need to specify the 'form' parameter, and then call serialize() on that parameter, as follows:
submitHandler: function(form) {
$.ajax({
type: "PUT",
url: "/target",
data: form.serialize(),
dataType: "json",
success: function()
{
alert('ok');
}
});
}
See the docs: http://docs.jquery.com/Plugins/Validation/validate#options
I have the following AJAX function with JQuery:
var formData = $('#FonykerEditForm').serialize();
$.ajax ({
type: 'POST',
url: '<?php echo $html->url('/fonykers/edit',true); ?>',
data: formData,
dataType: 'json',
success: function(response) {
message.html(response.msg);
message.fadeIn();
if(!response.ok) {
message.removeClass('success');
message.addClass('error');
} else {
message.removeClass('error');
message.addClass('success');
username = $('#FonykerUsername').val();
email = $('#FonykerEmail').val();
}
$('#save-account-button').removeAttr('disabled');
$('.input-text').removeClass('ok');
$('.input-combo').removeClass('ok');
},
error: function (xhr, ajaxOptions, thrownError){
alert(xhr.statusText);
alert(thrownError);
$('#save-account-button').removeAttr('disabled');
}
});
The problem I'm having is that a type file field in my form is not getting submitted along with the rest of the data of the form, how can I include the file in the data of the ajax request?
I tried this link and this works fine for me.
http://portfolio.planetjon.ca/2014/01/26/submit-file-input-via-ajax-jquery-easy-way/
Example:
$( '#my-form' ).submit( function( e ) {
$.ajax( {
url: 'http://host.com/action/',
type: 'POST',
data: new FormData( this ),
processData: false,
contentType: false
} );
e.preventDefault();
} );
Like I said in the comment above, sending files via ajax is not straightforward. If you wish to try it anyway. The normal approach I've seen is to create a new iframe, add a file input field to it, select your file and submit it programmatically. This way, the iframe does the submission in the background.
Take a look at how this plugin does it:
https://github.com/valums/file-uploader/blob/master/client/fileuploader.js#L995
https://github.com/FineUploader/fine-uploader
Basically an AJAX will submit data in the form of key/value pairs.. Since files are binary data, you can't submit files using Ajax.. You'll need to submit the data using a standard form submit instead and on the server since accept a form/multipart
I have a simple one text input form that when submitted, needs to fetch a php file (passing the inputs to the file) and then take the result (just a line of text) and place it in a div and fade that div into view.
Here is what I have now:
<form id=create method=POST action=create.php>
<input type=text name=url>
<input type="submit" value="Create" />
<div id=created></div>
What I need is the results of create.php?url=INPUT, to be dynamically loaded into the div called created.
I have the jquery form script, but I haven't been able to get it to work right. But I do have the library loaded (the file).
This code should do it. You don't need the Form plugin for something as simple as this:
$('#create').submit(function() { // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: $(this).attr('method'), // GET or POST
url: $(this).attr('action'), // the file to call
success: function(response) { // on success..
$('#created').html(response); // update the DIV
}
});
return false; // cancel original event to prevent form submitting
});
This works also for file upload
$(document).on("submit", "form", function(event)
{
event.preventDefault();
var url=$(this).attr("action");
$.ajax({
url: url,
type: 'POST',
dataType: "JSON",
data: new FormData(this),
processData: false,
contentType: false,
success: function (data, status)
{
$('#created').html(data); //content loads here
},
error: function (xhr, desc, err)
{
console.log("error");
}
});
});
You must use AJAX to post the form if you don't want the page to be refreshed.
$('#create').submit(function () {
$.post('create.php', $('#create').serialize(), function (data, textStatus) {
$('#created').append(data);
});
return false;
});