Delete address Ajax Opencart 2.1.x - php

I am trying to delete address by using ajax call and data type as json:
Ajax call is as below:
$(".delete a").on('click', function() {
url: 'index.php?route=account/address/delete',
type: 'post',
data: "address_id="+addid,
dataType: 'json',
success: function(html) {
$("#msg").html('Deleted Address Successfully ');
},
error: function(xhr, ajaxOptions, thrownError) {
delcheckbox.html('<i class="fa fa-trash-o"></i>');
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
and in account/address/delete i wrote a new Post request condition as below:
public function delete() {
/* Opencart Pre written functions are here */
if (isset($this->request->post['address_id'])&&$this->validateDelete()) {
$json = array();
$this->model_account_address->deleteAddress($this->request->post['address_id']);
/* Unset Session variables same as get function of opencart */
/*to get json as response*/
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
}
When i execute ajax call then address is deleted successfully but as a reponse the error block of ajax is shown and error says as below screeenshot
Please suggest.
and please explain how operations pre.customer.delete.address and post.customer.delete.address work??

You are getting a page returned in your response. This indicates you might be getting a 404, another kind of error, or are calling onto a function that renders a page. Make sure none of this is happening.

Related

500 error when passing variables to function

I have the below function in my WordPress functions file, and if I run it as below without the two parameters it works fine, but when I pass the parameters the error handler in the jQuery returns status 500.
If I don't pass the parameters to the PHP function I get status 200 from jQuery, but it's coming from the error handler, and not from the success handler. Why so?
function subscribe_funk(){//$payment_method, $customer_handle){
return "This is a test";
die();
}
It gets called from this ajax:
function subscribe(data) {
jQuery.ajax({
url: PT_Ajax.ajaxurl,
type: "POST",
data: {'action': 'subscribe_funk', 'payment_method': data.payment_method, 'customer_handle': data.customer},
cache: false,
dataType: 'json',
beforeSend: function(){
console.log('Before send subscribe');
},
complete: function(){
},
success: function (response) {
console.log('Message from success handler: ');
console.log(response);
},
error: function(xhr, status, error){
console.log("Message from error handler:")
var errorMessage = xhr.status + ': ' + xhr.statusText
console.log(errorMessage);
}
});
}
Your function expects 2 parameters, however WP/ajax is not passing them directly.
You need to fetch them from $_POST array yourself:
function subscribe_funk(){
$payment_method = $_POST['payment_method'];
$customer_handle = $_POST['customer_handle'];
return "This is a test";
die();
}
Also, you may want to sanitize the post data with sanitize_text_field() or similar function.
Here is a relevant thread in WP StackExchange: how to pass parameters from jQuery ajax to a PHP function

Issues with Jquery/PHP ajax form submission

I am using the following code to post form data to a php file..
jQuery("#form-submit").click(function(data){
var url = "save-data.php";
jQuery.ajax({
type: "POST",
data: jQuery('#my-form').serialize(),
url: url,
cache : "false",
success: function(data){
jQuery("#dl-message").html(data);
jQuery("#dl-message").css('background-color', '#0C3');
jQuery('#dl-message').slideToggle('slow', function() {
jQuery('#dl-message').delay(2000).slideToggle('slow', function() {
//Animation Complete
});
});
},
error: function ( jqXHR, textStatus, errorThrown){
jQuery("#dl-message").html('There was an error saving your form: ' + errorThrown);
jQuery("#dl-message").css('background-color', '#F33');
jQuery('#dl-message').slideToggle('slow', function() {
jQuery('#dl-message').delay(2000).slideToggle('slow', function() {
//Animation Complete
});
});
}
});
return false;
});
and then in my php file I am simply looking for $_POST['field-name'] to see if the contents of the form were posted. The ajax call returns successful, however no data from the form seems to be posted to the PHP file. When I call...
$name = $_POST['name'];
echo "Your name is: " . $name;
I get nothing.... Does anyone see anything wrong with my ajax call at all?
Thanks so much for your time...
So it seems the post was empty at the first place (btw you can include your last three posts inside the question by editing it). Are you sure your form's id is 'my-form'?

Ajax Doesn't give me anything in the console?

Updated Question to better reflect the communities support
Based on community support I have changed the Ajax function to be as such:
(function($){
$(document).ready(function(){
$('a').click(function(e){
var el = $(this).prev('input[type="checkbox"]');
if(el.is(':checked')){
el.prop('checked',false);
}
$.ajax({
url : "http://localhost/wordpress/wp-content/themes/Aisis-Framework/CoreTheme/AdminPanel/Template/Helper/UncheckPackageThemeHelper.php",
type : 'GET',
data : { 'element_name' : el.prop('name') },
success: function(data, textStatus, jqXHR){
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown ){
console.log(jqXHR, textStatus, errorThrown);
}
});
e.preventDefault();
});
});
})(jQuery);
The resulting PHP Class is as such:
class CoreTheme_AdminPanel_Template_Helper_UncheckPackageThemeHelper{
private $_element_name = null;
public function __construct(){
if(isset($_GET['element_name'])){
$this->_element_name = $_GET['element_name'];
echo $this->_element_name;
}
}
}
The network tab shows that I have some out put from activating the Jquery which I have shown below:
The Console is spitting out no errors, yet not echoing the element name. I have read up on the Jquery Ajax API and everything I have been doing, thus far, seems to be correct. Yet I am not getting the desired out put.
Note: The response tab is empty.... In other words I am not getting a response back.
You're not passing in the event to your click handler.
Use.
$('a').click(function(e){
// Your code
});
$.ajax({
url : "<?php echo CORETHEME_ADMIN_TEMPLATE_HELPER_URL . 'UncheckPackageThemeHelper.php'; ?>",
type : 'GET',
data : { 'element_name' : el.prop('name') },
success: function(result) {
console.log(result)
},
error: function(jqXHR, textStatus, errorThrown ){
console.log(jqXHR, textStatus, errorThrown);
}
});
Simplify the situation. Just for a moment, change your AJAX processor file (UncheckPackageThemeHelper.php) to read like this:
UncheckPackageThemeHelper.php
<?php
$test = $_POST['element_name'];
$r = 'PHP received: [' .$test. ']';
echo $r;
die();
Also, change your AJAX success function to read like this:
success: function(result) {
alert(result);
},
At least, this will show you that your AJAX is getting through.
Then, start adding things back into your AJAX processor file (one or two at a time) and keep echoing something out so that you can discover where the error is happening.
So I was doing a lot of things wrong. But this is the only way it works, for me - please post your comments if you have better solution.
In the class, I have to do this:
class CoreTheme_AdminPanel_Template_Helper_UncheckPackageThemeHelper{
private $_element_name = null;
public function __construct(){
if(isset($_GET["element_name"])){
$this->_element_name = $_GET["element_name"];
echo json_encode($this->_element_name);
}
}
}
new CoreTheme_AdminPanel_Template_Helper_UncheckPackageThemeHelper();
The class cannot be instantiated in the .phtml file with the resulting Ajax or the request is never sent back. Also notice the json_encode You cannot pass regular variables back to Ajax - when in a class (I think) - How ever when not in a class it seems to work - clarification is needed.
The Ajax then looks like this:
(function($){
$(document).ready(function(){
$('a').click(function(e){
var el = $(this).prev('input[type="checkbox"]');
if(el.is(':checked')){
el.prop('checked',false);
}
$.ajax({
url : "http://localhost/wordpress/wp-content/themes/Aisis-Framework/CoreTheme/AdminPanel/Template/Helper/UncheckPackageThemeHelper.php",
type : 'GET',
data : { 'element_name' : el.prop('name') },
success: function(data, textStatus, jqXHR){
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown ){
console.log(jqXHR, textStatus, errorThrown);
}
});
e.preventDefault();
});
});
})(jQuery);
The Data that comes back is what I expect: "aisis_options[package_RelatedPosts]"
There ar a couple of issues with this answer - One I dont understand why I have to instantiate the class inside the file its written in, and two not sure why I have to encode the response in a class, but not when its just a "script kiddy" file.

GET request not returning data on success

Ok this problem is starting to get annoying!
I have this jquery ajax request code:
$.ajax({
type: "GET",
url: "/nameCheck.php",
data: {addressName: ""+addressName+"", customer: customer},
success: TEST,
error: reportProblem
});
the nameCheck.php looks like this:
include_once("db_connect.php3");
$addressName = $_GET["addressName"];
$customer = $_GET["customer"];
$search = mysql_query("select count(*) from Address where AddressName=".quote_correct($addressName)." and CustomerNumber=$customer",$database);
$rows=mysql_fetch_array($search);
$number_of_rows = $rows[0];
// note quote_correct is just a function to clean up the users input
if ($number_of_rows>1)
{
$message ="NO";
}
else
{
$message ="OK";
}
echo $message;
?>
and on success the TEST function looks like this
function TEST(data,status){
alert(data+" - "+ status);
}
Through a log file I set up in the php code - I see the process of checking to see if the customer name exists is working and I get the proper response of OK or NO.
The ajax call is a success too - and the TEST function is called - but no data is present..
Does anyone know why this isn't working?
Try having your ajax call look like this:
$.ajax({
type: "GET",
url: "/nameCheck.php",
data: { addressName: "" + addressName + "", customer: customer },
success: function (data) {
alert(data);
},
error: function(xhr, status, error) {
}
});
I usually also state in my get/post calls the return type. (json,html...) and does the returning php function know what to return?
You need to set the content-type header in your PHP. The default response is txt/html, jQuery wants JSON.
header('Content-type: application/json');

Get jQuery Error if PHP Breaks

I have a PHP script that breaks if a variable is not populated and it isn't added to the database, but jQuery handles this as a success and I get this error:
TypeError: Result of expression 'data' [null] is not an object.
Here's the jQuery script:
$.ajax({
type: "POST",
url: "/clase/do-add",
data: $("#adauga").serialize(),
dataType: "json",
error: function (xhr, textStatus, errorThrown) {
alert('Try again.');
},
success: function(data) {
var dlHTML = '<dl id="' + data.id + '"> [too long] </dl>';
$('form#adauga').after(dlHTML);
$('#main dl:first').hide().fadeIn();
adaugaClasaSubmit.removeAttr('disabled');
adaugaClasa.removeAttr('readonly');
adaugaClasa.val("").focus();
}
});
The problem is that jQuery's concept of "error" is an HTTP error, not an error that you have noted yourself. If the HTTP response code is <400, jQuery will use your success callback. Your options are (a) to use PHP to give an error in your HTTP response
header("HTTP/1.0 500 Internal Server Error");
or (b) to do your error handling in the success handler:
success: function(data) {
if (!data) {
// do your error code here
} else {
// do your success code here
}
}
I prefer the first option, with HTTP response codes, to allow your code to make the best logical sense to a future editor (which may be you!).
success: function(data) {
if(data!=null){
...
}
}
try this

Categories