how to get validation errors through ajax in codeigniter - php

I'm trying to use ajax within my submit form in a codeigniter. I have it to where the ajax call is made, bu the validation errors are not displaying. I can't figure out why. Please help.
I do have some returns in there, but they do nothing.
if ($this->form_validation->run() == FALSE)
{
echo(json_encode("validate"=>FALSE));
}
else
{
$this->load->model('adduser_model');
$data['query']=$this->adduser_model->adduser();
}
}
view code:
<script>
//CHECKS ONE FIELD AT A TIME
$(function(){
$(".field").each(function(){
$(this).keyup(function(){
var id = $(this).attr("id"); //VALUE OF INPUT ID Ex: <input id="name">
var v = $(this).val(); //INPUT TEXT VALUE
var data = id+"="+v; //DATA TO GO TO THE AJAX FILE Ex:(name=wcet)
$.ajax({
type: "POST",
url: "prog/validate", //AJAX FILE
data: data+"&single=true",
success: function(e){ //"e" IS THE DATA FROM "validate.php"
$("span#"+id).html(e); //ECHOS DATA FROM "validate.php" NEXT TO THE INPUT IF NEEDED
}
});
});
});
});
</script>
<BODY>
<?php $this->load->helper('form');
echo form_open('prog/validate'); ?>
<tr><td align="right">Name: </td><td align="left"><input class="field" name="name" id="name"> <span id="name"></span><br></td></tr>
<tr><td align="right">email: </td><td align="left"><input class="field" name="email" id="email"> <span id="email"></span><br></td></tr>

If you have some returns that means the function was successful. Even if you didn't have the response you expected, the $this->form_validation->run() will be false ONLY if the $ajax call couldn't fire at all (404, 500 errors).
You can also trying catching the error via failure: function () {}, for example:
$.ajax({
type: "POST",
url: "prog/validate", //AJAX FILE
data: data+"&single=true",
success: function(e){ //"e" IS THE DATA FROM "validate.php"
$("span#"+id).html(e);
},
failure: function(e) {
// check against error messages
}
});

Related

Undefined index error in php using ajax

<form role="form" method="post" action="test.php">
<label for="contact">Mobile No:</label><br>
<input type="tel" class="form-control" name="contact" title="Mobile number should not contain alphabets. Maxlength 10" placeholder="Enter your phone no" maxlength="15" required id='contact_no'>
<br><br>
<button type="submit" class="btn btn-success" name="submit" id="submit">Submit</button>
<button type="reset" class="btn btn-default" id='reset'>Reset</button>
</form>
Ajax and Javascript Code
script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(){
var dialcode = $(".country-list .active").data().dialCode;
var contact = $("#contact_no").val().replace(" ","");
var countrycode = $('.country-list .active').data().countryCode;
var cn;
var cc;
var dc;
$.ajax({
url: "test.php",
type: "POST",
data: {'cc' : contact},
success: function(data)
{
alert("success");
}
});
});
});
</script>
The variables show the values if displayed by alert message but are not passed on to the test.php page. It shows undefined index error at the following statement
test.php is as follows
<?php
if(isset($_POST['submit'])){
$contact = $_POST['cc']; //it shows the error here
}
echo $contact;
I had referred to many websites which show the same thing. It dosent work for me. I think the syntz of ajax is correct and have tried all possibilities but still dosent work. Please help
You're posting {cc: contact}, but you're checking for $_POST['submit'] which isn't being sent. The callback also doesn't stop the event, so you might want to return false (stops default and propagation). Something like this should do the trick:
$('#submit').on('click', function()
{
//do stuff
$.ajax({
data: {cc: contact},
method: 'post',
success: function()
{
//handle response here
}
});
return false;
});
Then, in PHP:
if (isset($_POST['cc']))
{
//ajax request with cc data
}
Also not that this:
$("#contact_no").val().replace(" ","");
Will only replace 1 space, not all of them, for that you'll need to use a regex with a g (for global) flag:
$("#contact_no").val().replace(/\s+/g,"");
You are using ajax to form submit
and you use $_POST['submit'] to check it would be $_POST['cc']
test.php
<?php
if(isset($_POST['cc'])){// change submit to cc
$contact = $_POST['cc'];//it shows the error here
}
echo $contact;
#Saty answer worked for me, but my code on ajax was a bit different. I had multiple form data wrapped up into a form variable, that was passed to the php page.
const form = new FormData();
form.append('keywords', keywords);
form.append('timescale', timescale);
form.append('pricing_entered', pricing_entered);
$.ajax({
url: "../config/save_status.php",
data: form,
method: "POST",
datatype: "text",
success: function (response, data) {
}
Then my php was:
if (isset($_POST['data'])) {
// all code about database uploading
}

Update textarea From User Input by jQuery and Ajax

I am trying to update a value in my php file and present it in a textarea using jquery and ajax. to make it short, I have:
1- A Form with User Input and Submit button and a Text area
2- A PHP file called data.php
3 -and the html file
Here is my codes
<form>
<input type="text" name="name"><br>
<textarea name="wstxt" id="wstxt" cols="40" rows="5"></textarea>
<input type="button" name="txta-update" id="txta-update" value="Update Textarea" />
</form>
PHP is as simple as:
<?php
$name = "Jordano";
echo $name;
and here is the jquery
$(document).ready(function() {
$('#txta-update').click(function() {
$.ajax({
type: "GET",
url: "data.php",//get response from this file
success: function(response){
$("textarea#wstxt").val(response);//send response to textarea
}
});
});
});
can you please tell me how I can send the input value to php and update the textarea from new value?
Thanks
Update
Send data like this
data:{name:$('input[name="name"]').val()}
you js file becomes
$.ajax({
type: "GET",
url: "data.php", //get response from this file
data:{name:$('input[name="name"]').val()},
success: function (response) {
$("textarea#wstxt").val(response); //send response to textarea
}
});
or
$(document).ready(function () {
$('#txta-update').click(function () {
var name_val = $('input[name="name"]').val();
$.ajax({
type: "GET",
url: "data.php", //get response from this file
data: {
name: name_val
},
success: function (response) {
$("textarea#wstxt").val(response); //send response to textarea
}
});
});
});
To get value in PHP
<?php
$name = $_GET['name'];
echo $name;
?>

Ajax call only if the jquery validation is valid

I have a form and ajax call.data are filled in form and goes to remote at the same time user is created in my database using ajax call.but the problem is with validation,which validation should apply here
for example i apply any jquery validation i need to test if the form is valid and then i can call ajax if the form is valid other wise the database will be filled with blank data
i tried with bvalidator but i don't know how to detect the form is valid or invalid using any jquery validator library
<form id="inform" action="http://site.com">
<input type="text" id="name" />
<input type="text" id="email" />
<input type="button" name="subaction" id="infuse" />
</form>
<script language ="javascript" type = "text/javascript" >
$na= jQuery.noConflict();
$na(document).ready(function(){
$na('#infuse').click(function(){
var name= $na('#name').val();
var email = $na('#email').val();
$na.ajax({
type: "POST",
url: '<?php bloginfo('template_url')?>/user_create.php',
data: 'name='+name+'&email='+email,
cache: false,
success: function(result){
jQuery('.err_msg').html(result);
jQuery("#inform").submit();
}
});
});
});
</script>
You could do something like this
<script language ="javascript" type = "text/javascript" >
$na= jQuery.noConflict();
var name;
var email;
var options10 = {
// shows or hides error all messages container after validation completes
onAfterAllValidations: function(elements, formIsValid){
// if validation failed
if(!formIsValid)
callAjax();
else{
//do something
}
}
};
function callAjax(){
$na.ajax({
type: "POST",
url: '<?php bloginfo('template_url')?>/user_create.php',
data: 'name='+name+'&email='+email,
cache: false,
success: function(result){
jQuery('.err_msg').html(result);
jQuery("#inform").submit();
}
});
}
$na(document).ready(function(){
$('#inform').bValidator(options10);
$na('#infuse').click(function(){
name= $na('#name').val();
email = $na('#email').val();
});
});
</script>
I haven't checked this, but hopefully , this works. The important point is, you could use the callbacks : onAfterAllValidations.

CodeIgniter and AJAX form submit

I am trying to save data submitted from a form into my mysql database and and then update the div element with the last posted item prepended to the list in the div.
Right now I am only trying to get a response back, I'm not worried about having the formatting correct at the moment.
My problem is the form won't submit with e.preventDefault(); in place, but without it the form does the normal method of posting to the db then refreshing the page.
Here is my AJAX call:
$(document).ready(function() {
$('form#feedInput').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "<?php echo site_url('dashboard/post_feed_item'); ?>",
data: $('.feed-input').val(),
dataType: "html",
success: function(data){
debugger;
$('#feed-container').prepend(data);
},
error: function() { alert("Error posting feed."); }
});
});
});
I don't think it's necessary for me to post my controller code, seeing as how my issue is the form won't make it past the e.preventDefault(); function.
How can I get this form to submit via AJAX if the e.preventDefault() function is stopping it before it can reach the $.ajax() function?
The data attribute of the ajax call is invalid. It should be either in JSON format { key: $('.feed-input').val() } or in query format 'key='+$('.feed-input').val().
Also there is an unnecessary debugger variable in the success method.
A working code could be:
$('form#feedInput').submit(function(e) {
var form = $(this);
e.preventDefault();
$.ajax({
type: "POST",
url: "<?php echo site_url('dashboard/post_feed_item'); ?>",
data: form.serialize(), // <--- THIS IS THE CHANGE
dataType: "html",
success: function(data){
$('#feed-container').prepend(data);
},
error: function() { alert("Error posting feed."); }
});
});
Html part in view
<form id="comment" method="post">
<h2>Enter Your Details</h2>
<center><div id="result"></div></center>
<div class="form_fld">
<label>Name</label>
<input type="text" placeholder="Enter Your Full Name" name="name" required="">
</div>
<div class="form_fld">
<label>Email ID</label>
<input type="text" placeholder="Enter Email ID" name="email" required="">
</div>
<div class="form_fld">
<label>Contact Number</label>
<input type="text" placeholder="Enter Contact Number" name="contact" required="">
</div>
<div class="form_fld">
<label>Developer</label>
<select name="developer">
<option>Lotus</option>
<option>Ekta</option>
<option>Proviso</option>
<option>Dosti</option>
<option>All</option>
</select>
</div>
<div class="form_fld">
<button type="submit" id="send">Submit</button>
</div>
</form>
After Html Part Just put ajax request
<script type="text/javascript" src="<?php echo base_url('assets/'); ?>js/jquery.js"></script>
<script>
$(function(){
$("#comment").submit(function(){
dataString = $("#comment").serialize();
$.ajax({
type: "POST",
url: "home/contact",
data: dataString,
success: function(data){
// alert('Successful!');
$("#result").html('Successfully updated record!');
$("#result").addClass("alert alert-success");
}
});
return false; //stop the actual form post !important!
});
});
</script>
Within Controller
public function contact()
{
$ip = $_SERVER['REMOTE_ADDR'];
$data = array('name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'number' => $this->input->post('contact'),
'developer' => $this->input->post('developer'),
'ip' => $ip,
'date' => date("d/m/Y"));
$result = $this->User_model->contact($data);
print_r($result);
}
You don't have to use preventDefault(); you can use return false; in the end of function submit() but I doubt this is the problem.
You should also use url encoding on $('.feed-input').val() use encodeURIComponent for this.
You should also check if you have errors in your console.
To determine if default action is prevented you can use e.isDefaultPrevented(). By default action in this case I mean submit action of the form with id feedInput.
You didn't name your param in data. Check jquery ajax examples.
You are probably getting an error e.preventDefault(); is not stopping the ajax.
$.ajax({
type: "POST",
url: "<?php echo site_url('dashboard/post_feed_item'); ?>",
data: $("#form").serializeArray(),
success: function(resp){
$('#container').html(resp);
},
error: function(resp) { alert(JSON.stringify(resp)); }
});

Issues submitting form with jquery

I have been trying to submit a form with jquery ajax but have been having issues.
When i check through firebug i see the value posted but it shows error from the url. I have this html
<form method="post" name="tForm" id="tForm">
<table>
<tr>
<td>Age</td>
<td><input name="age" id="age" value="" /></td>
</tr>
<tr>
<td><input type="button" id="submit" value="submit"/></td>
</tr>
</table>
</form>
</body>
My js file that submits the form has this piece of code
$(document).ready(function() {
$('#tForm').submit(function(){
var age = $('#age').val();
var msg ='';
$.ajax({
url:'testp.php',
type:'post',
data: {age:age},
beforeSend:function(){
alert(age);
},
success:function(data){
msg=data;
alert(msg);
},
complete:function(){
alert(msg);
}
})
})
});
My testp.php file just has this
<?php
echo 'ok';
?>
You need to stop the event from propogating. Your form attempts to submit in the standard method and since your form doesn't have an action you receive the error.
$(document).ready(function() {
$('#tForm').submit(function(){
var age = $('#age').val();
var msg ='';
$.ajax({
url:'testp.php',
type:'post',
data: {age:age},
beforeSend:function(){
alert(age);
},
success:function(data){
msg=data;
alert(msg);
},
complete:function(){
alert(msg);
}
})
return false;
})
});
Use $('#tForm').submit(function(e){ ... and then call e.preventDefault(); to prevent the form from being submitted in a regular (non-ajax) request.
However, I'd suggest you to have a look at the jQuery form plugin which saves you some work.

Categories