Data is not posting showing Internal server error - php

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... :)

Related

unable $_GET data in PDO using AJAX for product filtering

Unable to filter product using PDOamd AJAX,
Below code loads data form sql using PDO and AJAX but when i try to filter based on Brand it doesn't work. tried debug var_dump method but nothing helps.
Can someone help me to solve, how do i filter product, is there anything missing in code?
HTML
<div class="md-radio my-1">
<input type="radio" class="filter_all cate" name="cate" id="<?php echo str_replace(' ', '', $row['sca']); ?>" value="<?php echo $row['sca'] ?>">
<label for="<?php echo str_replace(' ', '', $row['sca']); ?>">
<?php echo $row['sca']; ?>
</label>
</div>
SCRIPT
$(document).ready(function () {
var flag = 0;
var fetching = false;
var done = false;
function filter_data() {
// prevent concurrent requests
if (fetching === true) {
return;
}
fetching = true;
var data = {
action: 'fetch_data',
cate: get_filter('cate'),
brand: get_filter('brand'),
model: get_filter('model'),
sort: get_filter('sort'),
date: get_filter('date'),
offset: flag,
limit: 4
};
console.log($.param(data));
$.ajax({
url: "fetch.php?" + $.param(data),
type: 'POST'
})
.done(function (data) {
console.log('data received');
$('.filter_data').append(data); // append
// we reached the end, no more data
if (data === '<h3>No Data Found</h3>') {
done = true;
}
flag += 4;
fetching = false; // allow further requests again
})
.fail(function (error) {
console.log('An error occurred while fetching', error)
// TODO: some error handling
});
}
function get_filter(class_name) {
var filter = [];
$('.' + class_name + ':checked').each(function () {
filter.push($(this).val());
});
return filter;
}
$('.filter_all').click(function () {
filter_data();
});
filter_data(); // commented out for debugging purpose
var $window = $(window);
var $document = $(document);
$window.scroll(function () {
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight - 300 && fetching === false && done === false) {
console.log('infinite scroll');
filter_data();
}
});
});
PHP
<?php
include("$_SERVER[DOCUMENT_ROOT]/include/config.php");
include("$_SERVER[DOCUMENT_ROOT]/include/function.php");
$query = "SELECT * FROM allpostdata WHERE sts = '1' AND mca='Vehicle'";
if (!empty($_GET['cate'])) {
$query .= " AND sca IN (" . str_repeat("?,", count($_GET['cate']) - 1) . "?)";
} else {
$_GET['cate'] = []; // in case it is not set
}
if (!empty($_GET['brand'])) {
$query .= " AND product_brand IN (" . str_repeat("?,", count($_GET['brand']) - 1) . "?)";
} else {
$_GET['brand'] = []; // in case it is not set
}
if (!empty($_GET['model'])) {
$query .= " AND mdl IN (" . str_repeat("?,", count($_GET['model']) - 1) . "?)";
} else {
$_GET['model'] = []; // in case it is not set
}
if (empty($_GET['sort']) || $_GET['sort'][0] == "date") {
$query .= " ORDER BY pdt DESC";
} elseif ($_GET["sort"][0] == "ASC" || $_GET["sort"][0] == "DESC") {
$query .= " ORDER BY prs " . $_GET['sort'][0];
}
if (isset($_GET['limit'])) {
if (!empty($_GET['offset'])) {
$query .= " LIMIT " . $_GET['limit'] . " OFFSET " . $_GET['offset'];
} else {
$query .= " LIMIT " . $_GET['limit'];
}
}
$stmt = $conn->prepare($query);
$params = array_merge($_GET['cate'], $_GET['brand'], $_GET['model']);
$stmt->execute($params);
$result = $stmt->fetchAll();
$total_row = $stmt->rowCount();
$output = '';
if ($total_row > 0) {
foreach ($result as $row) {
$parameter = $row['pid'];
$hashed = md5($salt . $parameter);
$output .= '<a href="/single_view.php?p=' . $row['id'] . '" class="w-xl-20 w-lg-20 col-md-3 col-6 p-1 p-lg-2">
<div class="card border-0 small">
<img class="card-img-top rounded-0" src="/upload/thumb/' . $row["im1"] . '" alt="Card image cap">
<div class="card-body pb-0 pt-2 px-0">
<h6 class="card-title text-dark text-truncate">' . ucfirst(strtolower($row['tit'])) . '</h6>
<h6 class="card-subtitle mb-1 text-muted text-truncate small">' . $row['product_brand'] . ' / ' . $row['mdl'] . '</h6>
<p class="card-text"><strong class="card-text text-dark text-truncate">₹ ' . $row['prs'] . '</strong></p>' . timeAgo($row['pdt']) . '
</div>
</div>
</a>';
}
} else {
$output = '<h3>No Data Found</h3>';
}
echo $output;
?>
You are sending data via GET query parameters despite defining the ajax call as a post. That's a security risk. Try changing your AJAX call to something like this, and replace youyr $_GET stuff to $_POST.
$.ajax({
url: '/your-form-processing-page-url-here',
type: 'POST',
data: data,
mimeType: 'multipart/form-data',
success: function(data, status, jqXHR){
alert('Hooray! All is well.');
console.log(data);
console.log(status);
console.log(jqXHR);
},
error: function(jqXHR,status,error){
// Hopefully we should never reach here
console.log(jqXHR);
console.log(status);
console.log(error);
}
});

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

Database insertion within a foreach loop while still calling in different functions in the sequence

I have a bit of a bug, and I can't tell where the error comes from.
I am building a cart system that will insert multiple data to a database from a cart on submit.
I'm using AJAX for this and I'm have errors, please I need help.
Here are my code snippets:
JavaScript Code
function addSale(payment_type, cash_tendered) {
var cust_name = $("#cust_name").val();
var amt_owed = $("#amt_owed").val();
$.confirm({
title: 'Checkout',
content: '' +
'<form action="" class="formName" role="form">' +
'<div class="form-group">' +
'<label>Payment Type</label>' +
'<select id="eType" class="name form-control">' +
'<option value="cash">Cash</option>' +
'<option value="card">Card</option>' +
'</select>' +
'</div>' +
'<div class="form-group">' +
'<label>Cash Tendered</label>' +
'<input type="number" id="eCash" placeholder="Cash Tendered" class="name form-control">' +
'</div>' +
'</form>',
buttons: {
cancel: function () {
//close
},
formSubmit: {
text: 'Checkout',
btnClass: 'btn-success',
action: function () {
payment_type = this.$content.find('#eType').val();
cash_tendered = this.$content.find('#eCash').val();
if (!payment_type || !cash_tendered) {
$.alert('Please fill all fields.');
return false;
}
$.confirm({
title: 'Do you want to continue?',
type: 'orange',
content: 'Click Ok to add sale',
buttons: {
cancel: function () {
},
proceed: {
text: 'Ok',
btnClass: 'btn btn-success',
action: function () {
var addUrl = "home/addsales";
addUrl += "/" + payment_type;
addUrl += "/" + cash_tendered;
addUrl += "/" + cust_name;
addUrl += "/" + amt_owed;
//
$.ajax({type: 'GET', url: addUrl, data: {},
success: function (result) {
$.alert({
content: result
});
$("#eType").val("");
$("#eCash").val("");
$("#cust_name").val("");
$("#amt_owed").val("");
location.reload();
},
error: function (xhr, status, error) {
$.alert({
content: 'Could not complete the process. ' + error
});
}
});
}
}
}
});
}
}
},
onContentReady: function () {
// bind to events
var jc = this;
this.$content.find('form').on('submit', function (e) {
// if the user submits the form by pressing enter in the field.
e.preventDefault();
jc.$$formSubmit.trigger('click'); // reference the button and click it
});
}
});
}
Here is the Home Controller Code:
private function addsales($payment_type = null, $cash_tendered = null, $cust_name = null, $amt_owed = null) {
if (isset($payment_type, $cash_tendered)) {
$email = $_SESSION[DbStrings::$EMAIL];
$payment_type = $this->test_input($payment_type);
$cash_tendered = $this->test_input($cash_tendered);
$insertedSale = $this->member->insertDailySale($email, $payment_type, $cash_tendered);
$cust_name = $this->test_input($cust_name);
$amt_owed = $this->test_input($amt_owed);
$insertedCredit = 1;
if (isset($cust_name, $amt_owed) && $amt_owed > 0) {
$insertedCredit = $this->member->insertCredit($email, $cust_name, $amt_owed);
}
if ($insertedSale && $insertedCredit) {
$_SESSION['temp_invoice'] = $_SESSION[DbStrings::$INVOICE];
$chars = "003232303232023232023456789";
srand((double) microtime() * 1000000);
$i = 0;
$pass = '';
while ($i <= 7) {
$num = rand() % 33;
$tmp = substr($chars, $num, 1);
$pass = $pass . $tmp;
$i++;
}
$alpha = 'NM-' . $pass;
$_SESSION[DbStrings::$INVOICE] = $alpha;
echo "Your sale has been inserted succesfully";
} else {
echo "There was a problem inserting your sale. Please try again.";
}
} else {
echo 'Please fill all fields';
}
}
And Here is my Model Code that still fetches other functions:
public function insertDailySale($email, $payment_type, $cash_tendered) {
$invoice = $_SESSION[DbStrings::$INVOICE];
$this->db->from(DbStrings::$SALES_ORDER_TABLE_NAME);
$condition = array(DbStrings::$EMAIL => $email, DbStrings::$INVOICE => $invoice);
$this->db->where($condition);
$query = $this->db->get();
$checks = $query->result_array();
foreach ($checks as $queries) {
$productID = $queries[DbStrings::$PRODUCTID];
$quantity = $queries[DbStrings::$SALES_QUANTITY];
$amount = $queries[DbStrings::$SALES_AMOUNT];
$profit = $queries[DbStrings::$SALES_PROFIT];
$product_code = $queries[DbStrings::$PRODUCT_CODE];
$product_name = $queries[DbStrings::$PRODUCT_NAME];
$product_selling = $queries[DbStrings::$PRODUCT_SELLING];
$this->deductInventory($email, $product_code, $quantity);
$this->updateQuantitySold($email, $product_code, $quantity);
$cost_price = $this->product->getCostPrice($product_code);
$data[] = array(
DbStrings::$EMAIL => $email,
DbStrings::$INVOICE => $invoice,
DbStrings::$PRODUCTID => $productID,
DbStrings::$SALES_QUANTITY => $quantity,
DbStrings::$SALES_AMOUNT => $amount,
DbStrings::$SALES_PROFIT => $profit,
DbStrings::$PRODUCT_CODE => $product_code,
DbStrings::$PRODUCT_NAME => $product_name,
DbStrings::$PRODUCT_CP => $cost_price,
DbStrings::$PRODUCT_SP => $product_selling,
DbStrings::$PAYMENT_TYPE => $payment_type,
DbStrings::$CASH_TENDERED => $cash_tendered,
DbStrings::$DATE_CREATED => time()
);
$inserted = $this->db->insert_batch(DbStrings::$DAILYSALES_TABLE_NAME, $data);
}
return $inserted;
}
With the above, i get flagged this error:
There was a problem inserting your sale. Please try again.
Please I need help on this.
The error came from my database structure. Being an internal server error, it came from the DB.
I realized i deleted a column from my database table, and i was still sending data to the removed column.
Thanks guys for the attempt to help.

json - Form success message not showing on successful submission with 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>

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