php - codeigniter ajax form validation - php

Hi I’m quite new to jquery -ajax and I’d like some help please to join it with CI.
I have followed this tutorial on Submitting a Form with AJAX and I’d like to add this functionality to my CodeIgniter site. What I’d like to do is when the user submits the form, if there are any validation errors to show the individually on each input field (as in native ci process), or if this is not possible via validation_errors() function. If no errors occured to display a success message above the form.
Here's my code so far:
my view
// If validation succeeds then show a message like this, else show errors individually or in validation_errors() in a list
<div class="alert alert-success">Success!</div>
<?php echo validation_errors(); //show all errors that ajax returns here if not individualy ?>
<?php echo form_open('admin/product/add, array('class' => 'ajax-form')); ?>
<p>
<label for="product_name">Product *</label>
<input type="text" name="product_name" value="<?php echo set_value('product_name', $prod->product_name); ?>" />
<?php echo form_error('product_name'); ?>
</p>
<p>
<label for="brand">Brand</label>
<input type="text" name="brand" value="<?php echo set_value('brand', $prod->brand); ?>" />
<?php echo form_error('brand'); ?>
</p>
...
my controller
public function add($id){
// set validation rules in CI native
$rules = $this->product_model->rules;
$this->form_validation->set_rules($rules);
if ($this->form_validation->run() === true) {
// get post data and store them in db
$data = $this->input_posts(array('product_name', 'brand', 'category_id', 'description'));
$this->product_model->save($data, $id);
// no errors - data stored - inform the user with display success-div
} else {
// validation failed - inform the user by showing the errors
}
//load the view
$this->load->view('admin/products/add', $data);
}
and here’s the js script
$(document).ready(function () {
$('form.ajax-form').on('submit', function() {
var obj = $(this), // (*) references the current object/form each time
url = obj.attr('action'),
method = obj.attr('method'),
data = {};
obj.find('[name]').each(function(index, value) {
// console.log(value);
var obj = $(this),
name = obj.attr('name'),
value = obj.val();
data[name] = value;
});
$.ajax({
// see the (*)
url: url,
type: method,
data: data,
success: function(response) {
console.log(response); // how to output success or the errors instead??
}
});
return false; //disable refresh
});
});
How should I pass my validation results (either success or the post errors) throught the ajax request and display them on my view??
From some little research I did I've found that you can use a single controller, that holds both the native proccess and the ajax request (instead of using 2 controllers), but my main difficulty is, I don't understand how the results of the validation will pass through the js script and display them on my view?? Please note that I don't want to display anything on an alert box, instead show the results on a div or the errors individualy(if possible).
EDIT I did some changes to my application, here's the code so far:
the controller
public function manage($id = NULL){
$this->load->library('form_validation');
$data['categ'] = $this->category_model->with_parents();
//fetch a single product or create(initialize inputs empty) a new one
if (isset($id) === true) {
$data['prod'] = $this->product_model->get($id);
$data['attr'] = $this->attribute_model->get_by('product_id', $id, null, true);
} else {
$data['prod'] = $this->product_model->make_new();
$data['attr'] = $this->attribute_model_model->make_new();
}
if (isset($_POST['general_settings'])) {
if ($this->form_validation->run('product_rules') === true) {
// get post inputs and store them in database
$data = $this->product_model->input_posts(array('product_name', 'brand', 'category_id', 'general_description'));
$this->product_model->save($data, $id);
$status = true;
} else {
// validation failed
$status = validation_errors();
}
if ( $this->input->is_ajax_request() ) {
echo json_encode($status);
exit;
}
redirect('admin/product');
}
//if (isset($_POST['attributes_settings'])) { the same thing here }
// load the view
$this->load->view('admin/products/manage', $data);
}
and the js
success: function(response) {
//console.log(response);
if (data.status === true) {
$('#ajaxResults').addClass('alert alert-success').html(response);
} else {
$('#ajaxResults').addClass('alert alert-error').html(response);
};
}
But I'm having some issues
Although I get the error messages from validation_errors() as an alert-error when there are no errors I get the true in an alert-error too, insted of alert-success.
2.how should I return the success message too? eg. a message saying "Saves were done!".
Althought in a non-ajax-request the data are stored in the database, in case fo ajax the don't store. Any ideas What may be wrong???

HTML:
<div id="ajaxResults"></div>
Javascript ajax:
success: function(response) {
$('#ajaxResults').text(response);
}
this script you've wrote is only if the validation succeeds, right?
Wrong. The code in "success" gets executed any time you get a response back from the server (assuming the HTTP header is 200). Does your javascript knows if the server has any error for you? No.
You need your JavaScript to recognize if the validation failed or succeeded. You have many ways to do that. One of these could be sending the message to display followed by a 0 or 1.
So your PHP will looks like:
return "0 " . $errorMessage;
and
return "1 " . $successMessage;
and your javascript should then recognize, with if statement and substring, if the message starts with 0 or with 1.

Use this way i hope this will work for you
<script type='text/javascript'>
var base_url = '<?=base_url()?>';
function ajax_call()
{
var ids = $("#all_users").val();
$.ajax({
type:"POST",
url: base_url+"expense/home/get_expense",
data: "userid=" + ids,
success: function(result){
$("#your_div_id").html(result);
}
});
}
</script>

Related

Ajax doesn't call server side function when jquery handler is fired

I'm building a simple forum on which I have a user details page with two text fields, one for the user's biography and another for his interests.
When the user clicks on the save icon, a handler on the jquery is suposed to call an ajax call to update the database with the new value of the biography/interests but the ajax call isn't being called at all and I can't figure it out since I don't find any problems with the code and would apreciate if someone could take a look at it.
this is the textarea:
<textarea rows="4" cols="50" id="biography" readonly><?php if($info['bio'] == "") echo "Não existe informação para mostrar";
else echo $info['bio']; ?></textarea>
Here is the icon the user clicks on:
<li style="display:inline;" class="infoOps-li"><img class="info-icons" id="save1" src="assets/icons/save.png" alt=""></li>
this is the jequery with the ajax call:
$("#save1").click(function(){
var bio = $("#biography").val();
alert(bio); //this fires up
$.ajax({
url:"assets/phpScripts/userBioInterest.php", //the page containing php script
type: "post", //request type,
dataType: 'json',
data: {functionName: "bio", info:bio},
success:function(result){
alert(result.abc); //this doesn't fire
}
});
$("#biography").prop("readonly","true");
});
I know that the jquery handler is being called correctly because the first alert is executed. The alert of the ajax success function isn't, so I assume that the ajax call isn't being processed.
On the php file I have this:
function updateBio($bio)
{
$user = $_SESSION['userId'];
$bd = new database("localhost","root","","ips-connected");
$connection = $bd->getConnection();
if($bio == "")
{
echo json_encode(array("abc"=>'empty'));
exit();
}
if($stmt = mysqli_prepare($connection,"UPDATE users SET biografia = ? WHERE user_id = ?"))
{
mysqli_stmt_bind_param($stmt,'si',$bio,$user);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
echo json_encode(array("abc"=>'successfuly updated'));
}
$bd->closeConnection();
}
if(isset($_POST['functionName']))
{
$function = $_POST['functionName'];
echo $function;
if(isset($_POST['info']))
$info = $_POST['info'];
if($function == "bio")
{
updateBio($info);
}
else if($function == "interest")
{
updateInterests($info);
}
}
Can anyone shed some light on why isn't the ajax call being called?
Thank you
EDIT: changed "function" to "functionName" in json data object as suggested.
A possible problem is dued to a wrong parsing of the PHP output (for example due to a PHP error). You are reading the output as JSON, so if the output is not a JSON, success callback will not be triggered.
$("#save1").click(function(){
var bio = $("#biography").val();
alert(bio); //this fires up
$.ajax({
url:"assets/phpScripts/userBioInterest.php",
type: "post", //request type,
dataType: 'json',
data: {function: "bio", info:bio},
success:function(result){
alert(result.abc); //this doesn't fire
},
error: function(result){
alert("An error has occurred, check the console!");
console.log(result);
},
});
$("#biography").prop("readonly","true");
});
Try with this code, and check if an error is printed to the console.
You can use complete too, check here: http://api.jquery.com/jquery.ajax/

Return success/failure variable with ajax from php script

I'm a really new coder and struggling with a task I'm now working on and trying out for days.
I searched Google and Stack Overflow but can't find a (for me understandable) solution to my problem:
I created a Twitter Bootstrap landing page and there a modal shows up when clicked. In this modal I have a form with a newsletter subscription:
<form id="newsletter" method="post">
<label for="email">Email:</label><br/>
<input type="text" name="email" id="email"/><br/>
<button type="submit" id="sub">Save</button>
</form>
<span id="result"></span>
Now I want to insert the data into a mySQL DB and do some basic validation that returns errors or a success message. The script works fine without ajax, but probably needs alterations on what it returns for ajax?
include("connection.php");
if ($_POST['email']) {
if(!empty($_POST['my_url'])) die('Have a nice day elsewhere.');
if (!$_POST['email']) {
$error.=" please enter your email address.";
} else if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$error.=" please enter a valid email address.";
}
if($error) {
$error= "There was an error in your signup,".$error;
} else {
$query="SELECT * FROM `email_list` WHERE email='".mysqli_real_escape_string($link, $_POST['email'])."'";
$result = mysqli_query($link, $query);
$results = mysqli_num_rows($result);
if ($results) {
$error.=" this email address is already registered.";
} else {
$query = "INSERT INTO `email_list` (`email`) VALUES('".mysqli_real_escape_string($link, $_POST['email'])."')";
mysqli_query($link, $query);
$message = "Thanks for subscribing!";
}
}
}
After a lot of reading ajax seems to be the way to do it without the bootstrap modal closing after submit (to suppress default event).
The insertion into the DB works fine, also the validation.
But I can't manage to get the different error messages displayed (stored in the $error variable of the php file) or alternatively the $message in case of success.
This is the jquery script:
$("#sub").submit(function (){
event.preventDefault();
$.ajax( {
url: "newsletter2.php",
type: "POST",
data: {email: $("#email").val()},
success: function(message) {
$("#result").html(message);
},
error: function(error) {
$("#result").html(error);
}
});
I try to display the value of the error and message variable in the php script within the #result span.
Any help is appreciated. Please formulate it very straight forward since I'm really new to this field.
Thank you a lot in advance.
Edit:
Added some to the php file to create an array and store the messages within:
$response = array();
$response['success'] = $success;
$response['error']= $errors;
exit(json_encode($response));
But have still some trouble to get the ajax to work. Tried the shorthand $.post instead of $.ajax but can't them now even to get to work posting data...
$("#sub").submit(function (){
event.preventDefault();
$.post("newsletter.php", {email: $("#email").val() });
});
Quick time is much appreciated. I'm stuck after hours of testing and can't find the error. If I submit the form regularly it works fine, so the php/mysql part isn't the problem.
I also realized that when I click the "#sub" button, it still tries to submit the form via get (URL gets values passed). So I'm not sure if the event.preventDefault(); isn't working? jQuery is installed and working.
The $.ajax error function gets called when there is a connection error or the requested page cannot be found
You have to print some text out with the php and the ajax success function gets this output. Then you parse this output to see how it went.
The best practice is this:
php part:
$response = array();
$response['success'] = $success;
$response['general_message'] = $message;
$response['errors'] = $errors;
exit(json_encode($response));
js/html part:
$.post("yourpage.php", a , function (data) {
response = JSON.parse(data);
if(response['success']){
//handle success here
}else{
//handle errors here with response["errors"] as error messages
}
});
Good luck with your project
You need to echo your messages back to your AJAX. There is no place in you PHP code where the messages are going back to the message variable in your AJAX success.
include("connection.php");
if ($_POST['email']) {
if(!empty($_POST['my_url'])) die('Have a nice day elsewhere.');
if (!$_POST['email']) {
$error.=" please enter your email address.";
echo $error; die;
} else if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$error.=" please enter a valid email address.";
echo $error; die;
}
if($error) {
$error= "There was an error in your signup,".$error;
echo $error; die;
} else {
$query="SELECT * FROM `email_list` WHERE email='".mysqli_real_escape_string($link, $_POST['email'])."'";
$result = mysqli_query($link, $query);
$results = mysqli_num_rows($result);
if ($results) {
$error.=" this email address is already registered.";
echo $error; die;
} else {
$query = "INSERT INTO `email_list` (`email`) VALUES('".mysqli_real_escape_string($link, $_POST['email'])."')";
mysqli_query($link, $query);
$message = "Thanks for subscribing!";
echo $message; die;
}
}
}
I basicly just had the same case. I structured my code a little bit different but it works so...
$("#sub").submit(function (){
event.preventDefault();
$.ajax( {
url: "newsletter2.php",
type: "POST",
dataType: 'json',
data: {email: $("#email").val()},
})
.success(function(message) {
$("#result").html(message);
}),
.error(function(error) {
$("#result").html(error);
})
on server side I used C#(asp.net) and just returned a Json
return Json(new { Message = "Something...", Passed = true}, JsonRequestBehavior.AllowGet);
Oukay, finally I managed to solve the problem with the great inputs here. I did the following:
PHP:
$response = array();
$response['success'] = $success;
$response['error'] = $error;
exit(json_encode($response));
JS:
$("#newsletter").submit(function(event) {
event.preventDefault();
$.ajax({
url: 'newsletter3.php',
method: 'post',
data: {email: $('#email').val()},
success: function(data) {
var response = JSON.parse(data);
console.log(response);
if (response['success']) {
$("#error").hide();
$("#success").html(response['success']);
$("#success").toggleClass("alert alert-success");
} else {
$("#error").html(response['error']);
if(!$("#error").hasClass("alert alert-danger"))
$("#error").toggleClass("alert alert-danger");
}
}
});
});
The functionality is now that you click on a button and a modal pops-up, then you can enter your email and the php script validates if its valid and if it's already in the db. Error and success messages get JSON encoded and then are displayed in a span that changes color according to bootstrap classes danger or success.
Thank you very much for helping me, I'm very happy with my first coding problem solved :)
I use this on my ajax
request.done(function (response, data) {
$('#add--response').html(response);
});
and this on the PHP
die("Success! Whatever text you want here");

Ajax function learning

I need help in Ajax.
I got this code online.
This function is to check the contact.php
I have some few question so someone could assist me.
My questions :
1. Is this code good and possible to run ?
2. Can someone explain me what does the function in line 4 and line 5 does.It seems it send data to the contact.php but what is it returning?
Ajax:
var validateEmailForm = {
dataType: 'json',
submit: function(form) {
var redirect = false;
$.ajax('contact.php', {data:{'email':form.email.value}}).done(function(data) {
if ( typeof(data) == 'object' ) {
if ( data.status == 'valid') {
form.submit();
} else if(data.status !=='valid' {
alert('The e-mail address entered is wrong.');
}
} else {
alert('Failed to connect to the server.');
}
}
}
}
Contact.php:
<?php
error_reporting(0);
$email = $_POST['email'];
if (isset($_$POST['email']))
{
// How to return valid to the ajax
} else {
// How to return invalid to the ajax.
}
?>
You need to return a JSON_encoded array to the ajax function, like below:
$email = $_POST['email'];
$status = false;
if (isset($_$POST['email']))
{
$status = 'success'
} else {
$status = false
}
echo json_encode(array('status' => $status));
?>
Further, add dataType: 'json' to your $.ajax() so that the deferred function automatically parses it as such.
Remove the typeof() as we know what we're expecting in return.
AJAX is much easier than it sounds. You just need to see a few good examples.
Try these:
A simple example
More complicated example
Populate dropdown 2 based on selection in dropdown 1
https://stackoverflow.com/questions/25945137/php-fetch-content-from-one-form-and-update-it-in-other-form/25954450#25954450
The above examples demonstrate a few things:
(1) There are four formats for an AJAX request - the full $.ajax() structure, and three shortcut structures ($.post(), $.get(), and $.load() )
Until you are pretty good at AJAX, I suggest using a correctly formatted $.ajax() code block, which is what the above examples demonstrate. Such a code block looks like this:
$('#formID').submit({
$.ajax({
type: 'post',
url: 'contact.php',
dataType: 'json',
data: 'email=' + form.email.value
}).done(function(data) {
if ( typeof(data) == 'object' ) {
if ( data.status == 'valid') {
form.submit();
} else if(data.status !=='valid' {
alert('The e-mail address entered is wrong.');
return false;
} else {
alert('Failed to connect to the server.');
return false;
}
}
});
});
(2) In an $.ajax() code block, the data: line specifies the data that is sent to the PHP processor file.
(3) The dataType: line specifies the type of data that the ajax code block expects to receive back from the PHP processor file. The default dataType is html, unless otherwise specified.
(4) In the PHP processor file, data is returned to the AJAX code block via the echo command. Whether that data is returned as html, text, or json, it is echoed back to the AJAX routine, like this:
<?php
//perform MySQL search here. For eg, get array $result with: $result['firstname'] and $result['lastname']
$out = '<div id="myresponse">';
$out .= 'First Name: <input type="text" value="' .$result['firstname']. '" />';
$out .= 'Last Name: <input type="text" value="' .$result['lastname']. '" />';
$out .= '</div>';
echo $out;
Please try a couple of the above examples for yourself and you will see how it works.
It is not necessary to use json to send/return data. However, json is a useful format to send array data, but as you can see, you can construct a full html response on the PHP side and echo back the finished markup.
So, to definitively answer your second question, you just need to echo back some data. It is the job of the PHP file to:
(1) receive the data from the AJAX routine,
(2) Use that data in a look up of some kind (usually in a database),
(3) Construct a response, and
(4) echo (NOT return) the response back to the AJAX routine's success: or .done() functions.

redirect to new page of jquery validation passes

I have a jquery something like
$(document).ready(function() {
$('#value').change(function() {
$.ajax({
type:'POST',
url:'../validation.php',
data: {
validate_year:$('#Year').val(),
validate_value:$('#value').val(),
validate_domain:$('#Domain').val(),
},
success: function (data) {
}
})
});
});
in validation.php I have a sql statement which basically uses whatever is in Year, value and domain and then runs a select statement and the result is then rendering into a table in the same validation.php using echo $something in the table <tr>. What I want to do this display the validation.php to the user so the can see this table... because so they can make changes to it such as update and delete.
How can I do this?
Could try something like this
$(document).on('change', '#value', function() {
$.post('/validation.php', {validate_year:$("#Year").val(),
validate_value:$("#value").val(),
validate_domain$("#Domain").val()}, function(data) {
//Take the output of validation.php and put them into a class or id target
$(".target-area").html(data);
}
});
Basically what is happening is that the $.post function is reaching out to a URL that you specify, in this case validation.php. I am guessing that you are trying to return something to the javascript file that indicates whether something is valid or not. So for example
//valiation.php
<?php
$validate_year = $_POST['validate_year'];
$validate_value = $_POST['validate_value'];
$validate_domain = $_POST['validate_domain'];
//Do something here to determine if it is valid or not
//If the result is $valid in this pseudo code example
if($valid) {
echo 'true';
} else {
echo 'false';
}
In this example, the PHP script is returning a value of true or false based on the checks that you made against a database, expected results, etc, etc to the posted variable, in this case it is returned as the data variable in javascript.
So if you did something like this,
$(document).on('change', '#value', function() {
$.post('/validation.php', {validate_year:$("#Year").val(),
validate_value:$("#value").val(),
validate_domain$("#Domain").val()}, function(data) {
//Take the output of validation.php and log it to the console
console.log(data);
}
});
You would see the true or false result from the validation.php file I wrote. You probably want to return something to notify the user whether or not the validation failed or succeeded. So to expand on this, say you had a div on your page setup like this
<div id="validation-result"></div>
Your javscript would interpret the response from validation.php and output something to the user ... like this
$(document).on('change', '#value', function() {
$.post('/validation.php', {validate_year:$("#Year").val(),
validate_value:$("#value").val(),
validate_domain$("#Domain").val()}, function(data) {
//Take the output of validation.php, parse it and update the page
if(data == 'true') {
var content = "Your validation succeeded";
} else {
var content ="Your validation failed";
}
$("#validation-result").html(content);
}
});
And the final result on your page would look like this for true
<div id="validation-result">Your validation succeeded</div>
or this for false
<div id="validation-result">Your validaiton failed</div>
Hope that help clears up the answer a little bit for you

ajax form after 'submit' validation errors

I have created a form using ajax and php. The initial load and entering values into the form are all working fine, but where I am getting errors, is after the submit button has been pressed. Here is the markup for the form, and the ajax and php handlers:
relevant parts of form:
<form id="edit_time">
<!-----form fields here----!>
<button class="saveRecurrence" type="button" onclick="editTimeDriver('.$_GET['driver_id'].')">Save</button>
ajax part:
function editTimeDriver(driver_id) {
var time = "";
if (driver_id)
{
time += "&driver_id="+driver_id;
}
var data = $("#edit_time").serialize();
$.ajax({
url: "ajax.php?action=save_driver_event"+time,
dataType: "json",
type: "post",
data: data,
beforeSend: function()
{
$(".error, .success, .notice").remove();
},
success: function(json)
{
if (json["status"]=="success")
{
alert(json["message"]);
$("#edit_time")[0].reset();
}else{
if(json["error"]["date_from"]){
$("input[name=date_from]").after("<div class="error">"+json_time["error"]["date_from"]+"</div>");
}
}
}
});
}
This then passes to the php part which is:
$json = array();
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$date_from = tep_db_prepare_input($_POST['date_from']);
if (preg_match("/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/", $date_from)) {
$json['error']['date_from'] = 'Start Date is not valid!';
}
if (isset($json['error']) and !empty($json['error'])){
$json['status'] = 'error';
$json['message'] = 'Please check your error(s)!';
}else{
$json['status'] = 'success';
$json['message'] = 'Time Data has been successfully updated!';
}
}
echo json_encode($json);
Now for some reason, if the date_from field is left blank, and the form submitted, it doesn't come back with error message, instead it returns the success message. Can anyone tell me why it is not reading the errors?
Change your code by this one
onclick="editTimeDriver('<php echo $_GET['driver_id'] ?>'); return false;"
The return false statement prevent the form to be submitted using http (as you want to send an ajax request)
And You where doing something weird with your $_GET['driver_id']
Don't forget that php is running server-side

Categories