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
Related
I am building an inline code validation for a web form. With my current script, When a bad code is entered and it is being corrected (same length), POST data is not using the latest value. For example, I first enter "QFFE" and then correct it to "QFFF", but the latter is not stored in $_POST. See Firebug extract ("QFFF" passed but "QFFE" processed):
Here is the code (AJAX part):
var data = {};
$(document).ready(function() {
$('input[type="submit"]').on('click', function() {
resetErrors();
var url = 'process.php';
$.each($('form input, form select'), function(i, v) {
if (v.type !== 'submit') {
data[v.name] = v.value;
}
}); //end each
console.log(data);
$.ajax({
dataType: 'json',
type: 'POST',
url: url,
data: data,
cache: false,
success: function(resp) {
if (resp === true) {
//successful validation
alert("OK, processing with workflow...");
// $('form').submit();
return false;
} else {
$.each(resp, function(i, v) {
console.log(i + " => " + v); // view in console for error messages
var msg = '<label class="error" for="'+i+'">'+v+'</label>';
$('input[name="' + i + '"], select[name="' + i + '"]').addClass('inputTxtError').after(msg);
});
var keys = Object.keys(resp);
$('input[name="'+keys[0]+'"]').focus();
console.log('QD: error val');
}
return false;
},
error: function() {
console.log('there was a problem checking the fields');
}
});
return false;
});
});
function resetErrors() {
$('form input, form select').removeClass('inputTxtError');
$('label.error').remove();
}
And here my PHP script (process.php):
<?php
//List of accepted codes
$code_list = array("QWOLVE", "QFFF");
session_start();
if(isset($_POST)){
if (empty($_POST['promo_code'])) {
$_SESSION['errors']['promo_code'] = 'Please enter a promo code to access the beta site';
}elseif(! in_array($_POST['promo_code'], $code_list)){
$_SESSION['errors']['promo_code'] = $_POST['promo_code']." is not a valid code";
unset($_POST);
}
if(count($_SESSION['errors']) > 0){
//This is for ajax requests:
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
echo json_encode($_SESSION['errors']);
// header('Location: redirect.php');
exit;
}
//This is when Javascript is turned off:
echo "<ul>";
foreach($_SESSION['errors'] as $key => $value){
echo "<li>" . $value . "</li>";
}
echo "</ul>";exit;
}else{
//Form validation successful - process data here:
echo json_encode(true);
}
}
?>
How can I make sure that the process.php is always using the latest form data?
I'm not sure why you store errors in the the session, but since you don't seem to clear that session, the next time you call the POST method $_SESSION['errors'] will still have the previous error in it (QFFE), hence the output.
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>
What is the correct way to handle Ajax success callback events using jquery?
In my code, when I run instead of displaying data, it alerts object:object. However, if I use say msg.box it returns the data correctly.
I am trying to create an if statement where if text equals a certain word then the variable from json is placed in the html of the result div BA_addbox.
I cannot seem to get this to work and would be grateful if someone could point out my error. I have only included the relevant code as the form is posting the correct data and the php code is catching all the posts. Many thanks.
ajax code
$.ajax({
type: "POST",
url: "/domain/admin/requests/boxes/boxesadd.php",
data: formdata,
dataType: 'json',
success: function(msg){
if(msg == "You need to input a box") {
$("#BA_addbox").html(msg.boxerrortext);
}
else {
$("#BA_addbox").html(msg.box);
}
//alert(msg);
console.log(msg);
//$("#BA_addbox").html(msg.box);
//$("#formImage .col_1 li").show();
//$("#BA_boxform").get(0).reset();
//$("#boxaddform").hide();
}
});
boxesadd.php
$box = mysql_real_escape_string($_POST['BA_box']);
$boxerrortext = "You need to input a box";
if (isset($_POST['submit'])) {
if (!empty($box)) {
$form = array('dept'=>$dept, 'company'=>$company, 'address'=>$address, 'service'=>$service, 'box'=>$box, 'destroydate'=>$destroydate, 'authorised'=>$authorised, 'submit'=>$submit);
$result = json_encode($form);
echo $result;
}
else
{
$error = array('boxerrortext'=>$boxerrortext);
$output = json_encode($error);
echo $output;
//echo "You need to input a box";
}
}
In javascript associative arrays are called objects, so there's no bug in the transmitted data.
Why do you compare msg to "You need to input a box"? You cannot compare object and string, this makes no sense.
if(typeof msg.boxerrortext !== "undefined" && msg.boxerrortext == "You need to input a box") {
$("#BA_addbox").html(msg.boxerrortext);
} else {
$("#BA_addbox").html(msg.box);
}
Try this instead:
if(msg.boxerrortext) {
$("#BA_addbox").html(msg.boxerrortext);
}
else {
$("#BA_addbox").html(msg.box);
}
Hope this will help !!
I am attempting to add data to my database from my HTML code via the use of JQuery, AJAX/JSON and PHP using an MVC model. Below is a small sample of what I am looking to achieve.
In my front end I have a checkbox with different options and a button named 'Add'. The selected elements from here are picked up by a Javascript function, which I have tested properly, once this is done I call another Javascript function to do the AJAX/JSON . What I am still fresh on is the actual AJAX/JSON process that sends the data to PHP.
My Javascript function:
function add_fruits(fruit_name, fruit_type){
var success = "Fruit added";
var error = "Fruit not added";
var params = {
'fruit_name' : fruit_name,
'fruit_type' : fruit_type
};
$.ajax({
type: "POST",
url: "add_fruits.php",
async: false,
data: params,
success: function(success){
alert(success);
},
error: function(error){
alert(error);
}
});
}
My PHP function:
<?php
header("Access-Control-Allow-Origin: *");
header('Content-type: application/json');
require_once 'lib/connection_files.php';
if($_SERVER['REQUEST_METHOD'] =='POST')
{
$fruit_name = no_sql_injection($_POST['fruit_name']);
$fruit_type = no_sql_injection($_POST['fruit_type']);
$fruits = new fruits();
$result = $fruits->add_fruits($fruit_name, $fruit_type);
$tmp = mysql_num_rows($result);
if($result == 1)
{//RESULT must return 1 to verify successful insertion to database
//send confirmation to front end
}
else
{
//send error message to front end
}
}
else{
//tell front end there was error sending data via AJAX
}
?>
Note that the add_fruits() function takes care of doing the Queries to the database, I did not include it here because it is irrelevant to my issue.
Just do echo in your PHP:
PHP
else {
//send error message to front end
echo "Error Adding Fruits";
}
JS
success: function(data) {
if (data == "1") {
//data added to db
}
else {
alert(data);
}
}
I'm implementing reCaptcha, and I'm using an Ajax call to a PHP page of mine to check the validity of the captcha, without a page refresh.
I have this jQuery code:
$.post('php/captcha.php', $('#captchaPost').serialize(), function(data){
if(data != "Valid")
{
$('#captchaError').show();
$captchaFlag = "Invalid";
}
else
{
$('#captchaError').hide();
$captchaFlag = "Valid";
}
});
And this PHP code for the post handler:
<?php
require_once('recaptchalib.php');
$privatekey = "1234567890";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_REQUEST["recaptcha_challenge_field"],
$_REQUEST["recaptcha_response_field"]);
if (!$resp->is_valid)
{
// What happens when the CAPTCHA was entered incorrectly
echo "Error";
}
else
{
echo "Valid";
}
?>
I checked the response using Firebug and the PHP script always returns "Error", even when I type in the correct Captcha. The form seems to POST correctly, according to the server, although I don't see how to check what was posted in the form. I am not using the PHP function to build the reCaptcha form; I got the HTML from Google's docs on this. Any help?
Try using this code:
function validateCaptcha()
{
challengeField = $("input#recaptcha_challenge_field").val();
responseField = $("input#recaptcha_response_field").val();
var html = $.ajax({
type: "POST",
url: "php/captcha.php",
data: "recaptcha_challenge_field=" + challengeField + "&recaptcha_response_field=" + responseField,
async: false
}).responseText;
if(html != "Valid")
{
$('#captchaError').show();
$captchaFlag = "Invalid";
}
else
{
$('#captchaError').hide();
$captchaFlag = "Valid";
}
}
It doesn't look like you were sending the data correctly in your jQuery.
Edit
Also make sure to call validateCaptcha() on the button. For instance:
onSubmit="javascript:validateCaptcha()"