json - Form success message not showing on successful submission with PHP - php

I have difficulty in showing success message on form. Its showing all the error messages but not the success message.
On controller file its showing when I comment $this->model_catalog_outofstockquery->addQuery($this->request->post);
but this line is necessary.
On submitting form the entries are successfully loading to the database.
I have already call model from the constructor
My code on controller file is-
public function write() {
$this->load->language('product/outofstock_enquiry');
$json = array();
if ($this->request->server['REQUEST_METHOD'] == 'POST') {
if ((utf8_strlen($this->request->post['name']) < 3) || (utf8_strlen($this->request->post['name']) > 25)) {
$json['error'] = $this->language->get('error_name');
}
if (!filter_var($this->request->post['email'], FILTER_VALIDATE_EMAIL)) {
$json['error'] = $this->language->get('error_email');
}
if ((!filter_var($this->request->post['quantity'],FILTER_VALIDATE_INT))) {
$json['error'] = $this->language->get('error_quantity');
}
if (!isset($json['error'])) {
$json['success'] = $this->language->get('text_success');
$data['product_id'] = $this->request->post['product_id'];
$data['product_name'] = $this->request->post['product_name'];
$data['name'] = $this->request->post['name'];
$data['email'] = $this->request->post['email'];
$data['quantity'] = $this->request->post['quantity'];
$data['notify'] = 0;
$this->model_catalog_outofstockquery->addQuery($this->request->post);
}
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
The script on the view file under the form is
<script type="text/javascript"><!--
$('#button-submit').on('click', function() {
$.ajax({
url: 'index.php?route=product/outofstock_enquiry/write&product_id=<?php echo $product_id; ?>',
type: 'post',
dataType: 'json',
data: 'name=' + encodeURIComponent($('input[name=\'name\']').val()) + '&email=' + encodeURIComponent($('input[name=\'email\']').val()) + '&product_name=' + encodeURIComponent($('input[name=\'product_name\']').val()) + '&quantity=' + encodeURIComponent($('input[name=\'quantity\']').val()) ,
data: $("#form-ask").serialize(),
beforeSend: function() {
$('#button-submit').button('loading');
},
complete: function() {
$('#button-submit').button('reset');
},
success: function(json) {
$('.alert-success, .alert-danger').remove();
if (json['error']) {
$('#outofstock_enquiry').after('<div class="alert alert-danger"><i class="fa fa-exclamation-circle"></i> ' + json['error'] + '</div>');
}
if (json['success']) {
$('#outofstock_enquiry').after('<div class="alert alert-success"><i class="fa fa-check-circle"></i> ' + json['success'] + '</div>');
$('input[name=\'name\']').val('');
$('input[name=\'email\']').val('');
$('input[name=\'product_name\']').val('');
$('input[name=\'quantity\']').val('');
$('input[name=\'product_id\']').val('');
}
}
});
});
//--></script>

Related

CodeIgniter AJAX JSON validator with form validation

I am trying to make AJAX form validation work in CodeIgniter.
If you have the same title don't add The data from the form always reports as successful, even if the result is negative.
Is there a mistake in my logic?
Save controller:
public function save(){
$options = array();
$data['title'] = $this->input->post('title');
$data['description'] = $this->input->post('description');
$data['sale_price'] = $this->input->post('sale_price');
$data['purchase_price'] = $this->input->post('purchase_price');
$data['add_timestamp'] = time();
$data['options'] = json_encode($options);
$this->form_validation->set_rules("title", "Title", "required|trim|is_unique[product.title]");
$this->form_validation->set_rules("description", "Description", "required|trim");
$this->form_validation->set_rules("sale_price", "Price", "required|trim");
$this->form_validation->set_message(
array(
"required" => "<b>{field}</b> is not null.",
'is_unique' => 'A %s content has already been added in thistitle.!'
)
);
$validate = $this->form_validation->run();
if($validate){
$insert = $this->db->insert('product', $data);
// alert
if($insert){
$alert = array(
"title" => "Success Sir",
"text" => "Content successfully added",
"type" => "success"
);
}else {
$alert = array(
"title" => "Error Sir",
"text" => "Content failed to load content,
"type" => "danger"
);
}
}
JSON, AJAX, jQuery:
function ajax_set_full(type, title, noty, form_id, id) {
// ajax func
ajax_load(base_url + '' + user_type + '/' + module + '/' + type + '/' + id, 'list', 'form');
}
function form_submit(form_id, noty, e) {
var alerta = $('#form'); // alert div for show alert message
var form = $('#' + form_id);
var can = '';
if (!extra) {
var extra = '';
}
form.find('.summernotes').each(function () {
var now = $(this);
now.closest('div').find('.val').val(now.summernote('code'));
});
//var form = $(this);
var formdata = false;
if (window.FormData) {
formdata = new FormData(form[0]);
}
var a = 0;
var take = '';
form.find(".required").each(function () {
var txt = '*' + req;
a++;
if (a == 1) {
take = 'scroll';
}
var here = $(this);
if (here.val() == '') {
if (!here.is('select')) {
here.css({borderColor: 'red'});
if (here.attr('type') == 'number') {
txt = '*' + mbn;
}
if (here.closest('div').find('.require_alert').length) {
} else {
here.closest('div').append(''
+ ' <span id="' + take + '" class="label label-danger require_alert" >'
+ ' ' + txt
+ ' </span>'
);
}
} else if (here.is('select')) {
here.closest('div').find('.chosen-single').css({borderColor: 'red'});
if (here.closest('div').find('.require_alert').length) {
} else {
here.closest('div').append(''
+ ' <span id="' + take + '" class="label label-danger require_alert" >'
+ ' *Required'
+ ' </span>'
);
}
}
var topp = 100;
if (form_id == 'product_add' || form_id == 'product_edit') {
} else {
$('html, body').animate({
scrollTop: $("#scroll").offset().top - topp
}, 500);
}
can = 'no';
}
if (here.attr('type') == 'email') {
if (!isValidEmailAddress(here.val())) {
here.css({borderColor: 'red'});
if (here.closest('div').find('.require_alert').length) {
} else {
here.closest('div').append(''
+ ' <span id="' + take + '" class="require_alert" >'
+ ' *' + mbe
+ ' </span>'
);
}
can = 'no';
}
}
take = '';
});
if (can !== 'no') {
if (form_id !== 'vendor_pay') {
$.ajax({
url: form.attr('action'), // form action url
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: formdata ? formdata : form.serialize(), // serialize form data
cache: false,
contentType: false,
processData: false,
beforeSend: function () {
console.log(formdata);
var buttonp = $('.enterer');
buttonp.addClass('disabled');
buttonp.html(working);
},
success: function () {
ajax_load(base_url + '' + user_type + '/' + module + '/' + list_cont_func + '/' + extra, 'list', 'first');
if (form_id == 'vendor_approval') {
noty = enb_ven;
}
iziToast.show({
color: 'dark',
icon: 'fa fa-info',
title: 'Bilgi',
message: 'İşlem Başarılı!',
position: 'topCenter', // bottomRight, bottomLeft, topRight, topLeft, topCenter, bottomCenter
progressBarColor: 'rgb(0, 255, 184)',
/*onOpening: function(){
setTimeout(function(){
window.location.reload(1);
}, 5000);
console.log('Page Refresh!');
},
onClosing: function(){
// console.log('goodbye');
}*/
});
$('.bootbox-close-button').click();
('form_submit_success');
other_forms();
},
error: function (e) {
console.log(e)
}
});
} else {
//form.html('fff');
form.submit();
//alert('ff');
return false;
}
} else {
if (form_id == 'product_add' || form_id == 'product_edit') {
var ih = $('.require_alert').last().closest('.tab-pane').attr('aria-labelledby');
$("[id=" + ih +"]").click();
}
$('body').scrollTo('#scroll');
return false;
}
}
The error message always returns positive.
after run the validation, you need specify the array to be validated
public function save(){
$data = array();
$data['title'] = $this->input->post('title');
$data['description'] = $this->input->post('description');
$data['sale_price'] = $this->input->post('sale_price');
$data['purchase_price'] = $this->input->post('purchase_price');
$data['add_timestamp'] = time();
$this->form_validation->set_rules("title", "Title", "required|trim|is_unique[product.title]");
$this->form_validation->set_rules("description", "Description", "required|trim");
$this->form_validation->set_rules("sale_price", "Price", "required|trim");
$this->form_validation->set_message(
array(
"required" => "<b>{field}</b> is not null.",
'is_unique' => 'A %s content has already been added in thistitle.!'
)
);
$this->form_validation->set_data($data);
$validate = $this->form_validation->run();
You have to call the set_data() method before defining any validation rules.
Ref: https://codeigniter.com/userguide3/libraries/form_validation.html#validating-an-array-other-than-post

Data is not posting showing Internal server error

On click of buy now button product should add to cart button but it's not showing cart button even control is not going inside success function it is showing Internal server error when i refresh my page in cart button product is showing but it should work on click. How to resolve this?
Error in console showing like below:
Failed to load resource: the server responded with a status of 500
(Internal Server Error)
HTML code:
<button type="button" id="button-cart" data-loading-text="Loading..." class="btn btn-primary btn-lg btn-block buynow"><span class="bagImg mybtm"><i></i>Buy Now</span></button>
Jquery code:
$('#button-cart').on('click', function() {
$.ajax({
url: 'index.php?route=checkout/cart/add',
type: 'post',
data: $('#product input[type=\'text\'], #product input[type=\'hidden\'], #product input[type=\'radio\']:checked, #product input[type=\'checkbox\']:checked, #product select, #product textarea'),
dataType: 'json',
beforeSend: function() {
$('#button-cart').button('loading');
},
complete: function() {
$('#button-cart').button('reset');
},
success: function(json) {
console.log(json);
$('.alert, .text-danger').remove();
$('.form-group').removeClass('has-error');
if (json['error']) {
if (json['error']['option']) {
for (i in json['error']['option']) {
var element = $('#input-option' + i.replace('_', '-'));
if (element.parent().hasClass('input-group')) {
$('.breadcrumb').after('<div class="alert alert-danger">' + json['error']['option'][i] + '</div>');
} else {
$('.breadcrumb').after('<div class="alert alert-danger">' + json['error']['option'][i] + '</div>');
}
}
}
if (json['error']['recurring']) {
$('select[name=\'recurring_id\']').after('<div class="text-danger">' + json['error']['recurring'] + '</div>');
}
// Highlight any found errors
$('.text-danger').parent().addClass('has-error');
}
if (json['success']) {
$('.breadcrumb').after('<div class="alert alert-success">' + json['success'] + '<button type="button" class="close" data-dismiss="alert">×</button></div>');
$('#cart-total').html(json['total']);
$('#cart > ul').load('index.php?route=common/cart/info ul li');
}
$('html, body').animate({ scrollTop: 0 }, 'slow');
window.location.href='checkout/checkout';
},
error: function(json){
console.log(json);
}
});
});
Controller function:
public function add() {
$this->load->language('checkout/cart');
$json = array();
if (isset($this->request->post['product_id'])) {
$product_id = (int)$this->request->post['product_id'];
} else {
$product_id = 0;
}
$this->load->model('catalog/product');
$product_info = $this->model_catalog_product->getProduct($product_id);
if ($product_info) {
if (isset($this->request->post['quantity'])) {
$quantity = (int)$this->request->post['quantity'];
} else {
$quantity = 1;
}
if (isset($this->request->post['option'])) {
$option = array_filter($this->request->post['option']);
} else {
$option = array();
}
$product_options = $this->model_catalog_product->getProductOptions($this->request->post['product_id']);
foreach ($product_options as $product_option) {
if ($product_option['required'] && empty($option[$product_option['product_option_id']])) {
$json['error']['option'][$product_option['product_option_id']] = sprintf($this->language->get('error_required'), $product_option['name']);
}
}
if (isset($this->request->post['recurring_id'])) {
$recurring_id = $this->request->post['recurring_id'];
} else {
$recurring_id = 0;
}
$recurrings = $this->model_catalog_product->getProfiles($product_info['product_id']);
if ($recurrings) {
$recurring_ids = array();
foreach ($recurrings as $recurring) {
$recurring_ids[] = $recurring['recurring_id'];
}
if (!in_array($recurring_id, $recurring_ids)) {
$json['error']['recurring'] = $this->language->get('error_recurring_required');
}
}
if (!$json) {
$this->cart->add($this->request->post['product_id'], $this->request->post['quantity'], $option, $recurring_id);
$json['success'] = sprintf($this->language->get('text_success'), $this->url->link('product/product', 'product_id=' . $this->request->post['product_id']), $product_info['name'], $this->url->link('checkout/cart'));
unset($this->session->data['shipping_method']);
unset($this->session->data['shipping_methods']);
unset($this->session->data['payment_method']);
unset($this->session->data['payment_methods']);
// Totals
$this->load->model('extension/extension');
$total_data = array();
$total = 0;
$taxes = $this->cart->getTaxes();
// Display prices
if (($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) {
$sort_order = array();
$results = $this->model_extension_extension->getExtensions('total');
foreach ($results as $key => $value) {
$sort_order[$key] = $this->config->get($value['code'] . '_sort_order');
}
array_multisort($sort_order, SORT_ASC, $results);
foreach ($results as $result) {
if ($this->config->get($result['code'] . '_status')) {
$this->load->model('total/' . $result['code']);
$this->{'model_total_' . $result['code']}->getTotal($total_data, $total, $taxes);
}
}
$sort_order = array();
foreach ($total_data as $key => $value) {
$sort_order[$key] = $value['sort_order'];
}
array_multisort($sort_order, SORT_ASC, $total_data);
}
$json['total'] = sprintf($this->language->get('text_items'), $this->cart->countProducts() + (isset($this->session->data['vouchers']) ? count($this->session->data['vouchers']) : 0), $this->currency->format($total));
} else {
$json['redirect'] = str_replace('&', '&', $this->url->link('product/product', 'product_id=' . $this->request->post['product_id']));
}
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
Resolved It... There was nothing wrong with the script / code.. On server enabled 755 permission through out the site and made 777 for Cache / Upload folders... That did the trick....
Thx all for the help and response... :)

ajax function doesn't work when referred to from instagram

My function seems to return nothing for the destination element when the link is referred to from Instagram. It works fine if I directly visit the page.
function getTeamsByLeague(league) {
//console.log("League Set: " + league);
$.ajax({
url: "<?php echo SITE_BASE_URL; ?>json.php",
data: {method: "getteamsbyregion", league: league},
success: function (data) {
if (data && data.length > 0) {
$("#destination").empty();
var selected = "";
$.each(data, function (index, item) {
if (item.team == teamSelected) {
selected = " selected";
$("#latitude").val(item.lat);
$("#longitude").val(item.lng);
} else {
selected = "";
}
$("#destination").append('<option ' + selected + ' value="' + item.lat + ',' + item.lng + '">' + item.team + '</option>');
if (index == 0) {
$("#latitude").val(item.lat);
$("#longitude").val(item.lng);
}
});
}
},
type: "GET",
dataType: "json"
});
}

pass URL built in php as json to ajax for opening in new tab

how to return URL built in php as json object to ajax to open it in the new tab?
so far all my attempts to do so were unsuccessful. Please help
here is my JS file
$(document).ready ( function() {
$('.promoCode').click(function() {
// Store values in variables
var form = $(this).closest('form');
var name = form.find('input[name=name]');
var id = form.find('input[name=id]');
var submitted = form.find('input[name=submitted]');
var visitor = form.find('input[name=visitor]');
// Organize data
var data = 'name=' + name.val() + '&id=' + id.val() + '&submitted=' + submitted.val() + '&visitor=' + visitor.val();
var request = $.ajax({
type: "POST",
url: "/includes/_db_get_promo_code.php",
data: data,
cache: false,
success: function (html) {
myWindow = window.open(encodeURIComponent(true),
"_blank");
myWindow.focus();
if (html == "true") {
} else {
form.find('.error').fadeIn(500).delay(4000).fadeOut(500);
}
},
error: function(jqXHR, textStatus, error) {
alert("Form Error: " + error);
}
});
return false;
});
});
and here is my PHP file
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/includes/sitewide-variables.php");
// Check if form was submitted
if ($_POST['submitted'] && $_POST['visitor'] == '') {
// Check if all required fields are filled in
if (empty($_POST['name']) && empty($_POST['id'])) {
echo "Error: You must fill in all required fields.";
// If not, exit!
exit();
}
// If valid, store values in variables
$id = stripslashes($_POST['id']);
$name = stripslashes($_POST['name']);
if($name){
$query = 'SELECT * FROM files_paid WHERE parentpageID = :promoproductID';
$res = $db->prepare($query);
$res->execute(array(':promoproductID' => $id));
foreach ($res as $info);
if($info['promoCode'] == $_POST['name']){
$redirect_link = 'http://'.$info['promobuylinkID'].'.myid.pay.clickbank.net';
$todayis = date("l, F j, Y, g:i a") ;
$to = "My Email Address";
$subject = "Promotional Purchase";
$message = "$todayis [EST] \n
Promo Code: $name \n
";
// Send email
$sent = mail($to, $subject, $message);
if($sent) {
echo json_encode($redirect_link);
} else {
echo "Error: Mail could not be send.";
exit();
}
} else {
echo "Error: There was a problem with submitting the form";
exit();
}
}
}
?>
I am only getting true in the new window.
Thanks in advance
I have have found the problem.
First, I was missing dataType: "json", in ajax.
and after that I only had to return html to get to the point where I needed to get.
So the JS file now looks like this
$(document).ready ( function() {
$('.promoCode').click(function() {
// Store values in variables
var form = $(this).closest('form');
var name = form.find('input[name=name]');
var id = form.find('input[name=id]');
var submitted = form.find('input[name=submitted]');
var visitor = form.find('input[name=visitor]');
// Organize data
var data = 'name=' + name.val() + '&id=' + id.val() + '&submitted=' + submitted.val() + '&visitor=' + visitor.val();
var request = $.ajax({
type: "POST",
url: "/includes/_db_get_promo_code.php",
data: data,
dataType: "json",
cache: false,
success: function (html) {
if (html) {
window.open(decodeURIComponent(html),"_blank").focus();
} else {
form.find('.error').fadeIn(500).delay(4000).fadeOut(500);
}
},
error: function () {
alert("Your Coupon Code is not valid");
}
});
return false;
});
});
All works just fine.

Ajax request returns nothing. why?

Below is the ajax request.
$.post('delete.php', {'deletearray':deletearray, 'dir':dir}, function(deleted, undeleted){
if(undeleted == 0) {
alert('All ' + deleted + ' files delted from the server');
} else {
alert(deleted + ' files deleted and ' + undeleted + ' files could not be deleted');
}
}, 'json');
and here goes the delete.php
<?php
if(isset($_POST['deletearray'])) {
$files = $_POST['deletearray'];
$dir = $_POST['dir'];
$deleted = 0;
$undeleted = 0;
foreach($files as $file) {
if(unlink($dir.$file) && unlink($dir.'thumb/'.$file)) {
$deleted ++;
} else {
$undeleted ++;
}
}
echo json_encode($deleted, $undeleted);
}
return;
?>
Up on running the code it deletes the files successfully but no message displays.
I also tried changing the ajax request as:
$.post('delete.php', {deletearray:deletearray, dir:dir}, function(deleted, undeleted){
alert("php finished");
}, 'json');
still it does not display the message. So i guess something is wrong in the delete.php file. Please help.
First thing-
Use $_POST['deletearray'] instead of $_POST[deletearray]
Second thing-
You cannot return different variables from the PHP scrtipt, every thing you print there is returned in the ajax callback, so just write this-
PHP
json_encode(array('totalDeleted' => $deleted, 'totalUndeleted' => $undeleted));
AJAX
...
function(response){
response=JSON.parse(response);
console.log(response);
}
The best way to do jquery + ajax + php is as next:
jquery:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
function do_ajax() {
//set data
var myData = new Array();
myData.push({name:'deletearray',value:'deletearray'});
myData.push({name:'dir',value:'dir'});
//ajax post
$.ajax({
dataType: 'json',
url: 'delete.php',
type: 'post',
data: myData,
success: function(returnData) {
if(returnData.undeleted == 0) {
alert('All ' + returnData.deleted + ' files delted from the server');
} else {
alert(returnData.deleted + ' files deleted and ' + returnData.undeleted + ' files could not be deleted');
}
}
});
}
</script>
PHP:
<?php
$myData = $_POST;
if(isset($myData['deletearray']) AND isset($myData['dir'])) {
$files = $myData['deletearray'];
$dir = $myData['dir'];
$deleted = 0;
$undeleted = 0;
foreach($files as $file) {
if(unlink($dir.$file) && unlink($dir.'thumb/'.$file)) {
$deleted ++;
} else {
$undeleted ++;
}
}
print(json_encode(array('deleted' => $deleted, 'undeleted' => $undeleted)));
exit();
}
?>
You should use json_encode like following:
json_encode(array('deleted' => $deleted, 'undeleted' => $undeleted));
And you have to get vars with data.undeleted and data.deleted
$.post('delete.php', {'deletearray':deletearray, 'dir':dir}, function(data) {
if(data.undeleted == 0) {
alert('All ' + data.deleted + ' files delted from the server');
} else {
alert(data.deleted + ' files deleted and ' + data.undeleted + ' files could not be deleted');
}
}, 'json');

Categories