Cannot put checking in ajax - javascript

I have a bootbox dialog with a button. There is a problem with the 1st ajax function in there.
I would like to check whether the value returned from model and controller is 0 or 1 and stop the callback function from posting data to database if the value it returns is 1. However, once I put this check , it doesn't work before putting the first ajax function with the check, everything works perfectly. Now, I cannot even save any data to the database.
buttons: {
success: {
label: "Save",
className: "btn-success",
callback: function() {
console.log('save');
console.log($('#re_confirm')[0].checked);
...
...
...
var check;
$.ajax({
url: "<?php echo base_url(); ?>index.php/home/check_occupied",
type: "post", // To protect sensitive data
data: {
"table_id" : valueid2,
"session_id" : table_column_14,
//and any other variables you want to pass via POST
},
success:function(response){
// Handle the response object
check=response;
},
});
if(check!=0)
return;
$.ajax({
url : "<?php echo base_url(); ?>index.php/home/update_booking",
type: "post",
data: {
"table_id" : $('#idtable').val(),
},
success: function(response){
...
}
});
}
},
...
,
...
}
});

$.ajax is asynchronous
your code is easily fixed though:
$.ajax({
url: "<?php echo base_url(); ?>index.php/home/check_occupied",
type: "post", // To protect sensitive data
data: {
"table_id": valueid2,
"session_id": table_column_14,
//and any other variables you want to pass via POST
},
success: function(response) {
// Handle the response object
if (response == 0) {
$.ajax({
url: "<?php echo base_url(); ?>index.php/home/update_booking",
type: "post",
data: {
"table_id": $('#idtable').val(),
},
success: function(response) {
...
}
});
}
},
});

Related

Getting array data from PHP to jQuery for outputting

Here is the partial code from the remove PHP file:
if($action == 'trackings_get') {
$result = $trackings->get(getCourierSlugByID($GLOBALS['tracking_id']), $GLOBALS['tracking_id']);
$result_history = $result['data']['tracking']['checkpoints'];
echo json_encode($result_history);
// debugging
//pretty_print($result_history);
}
Here is the JS from the remote site i am trying to call the data for:
$.ajax({
url: '/login/tracking.php',
type: 'POST',
dataType: "json",
data: {
action: action,
tracking_id: tracking_id
},
success: function(json){
//debug
alert(JSON.stringify(json));
}
});
try this
function test(){
$.ajax({
url: 'url',
type: 'POST',
dataType: "json",
data: {
action: action,
tracking_id: tracking_id
},
success: function(json){
}
});
}
i try this code in inspect element in this page https://tracking.ambientlounge.com/
function test(){
$.ajax({
url: 'your url',
type: 'POST',
dataType: "json",
data: {
action: "action",
tracking_id: "tracking_id"
},
success: function(json){
//debug
console.log(json);
}
});
}
result is array . dont need JSON.stringify .

Wordpress ajax request return 0

Hello I have a problem with wordpress I can not get an ajax call and I can not find the reason. My query returns me all the time 0.
my javascript code :
updateButton.onclick = function (e) {
var donne = {
'action': 'my_action',
'lodges': updateDeleteArray
};
$(function () {
$.ajax({
type: "POST",
data: donne,
url: ajaxurl,
contentType: "application/json",
dataType: 'json',
success: function (data) {
console.log(data);
},
});
});
};
my php code :
add_action('wp_ajax_my_action', 'my_action');
add_action('wp_ajax_nopriv_my_action', 'my_action');
function my_action() {
echo 'salut';
die();
}
Try deleting contentType and dataType, because you are not returning a JSON into your function.
Or
modify your function like this
function my_action() {
echo json_encode('salut');
die();
}
hope it helps

Correct way of calling ajax responses inside arrays

i have this ajax call
$.ajax({
type: 'POST',
url: "<?php echo $_SERVER_ADDR . PUBLIC_PATH . 'presupuestos/buscant/'; ?>",
data: { 'arregloid':sel_articulos, 'idpre':$('#presupuestos_id').val()},
dataType: "json",
success: function(responses) {
$.each(responses, function(ii, response) {
$("[name='#pre_detalle["+response["idart"]+"[canart]]']").val(response['canart']);
$("#pre_detalle_precio["+response["idart"]+"]").val(response["precio"]);
console.log(response["idart"]);
console.log(response["canart"]);
console.log(response["precio"]);
});
},
complete: function () {
$('#spinner').hide();
actTotales();
},
error: function() {
}
});//ajax 2
i need to assign to 2 text inputs with ids:
id="pre_detalle_precio[x]" and id="pre_detalle_[x][canart]
being x the article id being returned by the ajax this three responses:
response["idart"];
response["canart"];
response["precio"];
i can see the responses being returned correctly with console.log but can't alter the values of the input boxes.
i think you are missing underscore
$("[name='#pre_detalle_["+response["idart"]+"[canart]]']").val(response['canart']);
$("#pre_detalle_precio_["+response["idart"]+"]").val(response["precio"]);
as in id="pre_detalle_precio[x]" and id="pre_detalle_[x][canart]
try now

Retrieve JSON from javascript to php (OpenCart controller)

There is a nice JSON object in console.log, but can't seem to retrieve it in controller.
function checkOut(data) {
$.ajax({
url: 'index.php?route=sale/customer/checkout&token=<?php echo $token; ?>&customer_id=<?php echo $customer_id; ?>&products=' + data,
type: 'post',
dataType: 'html',
data: 'products=' + encodeURIComponent(data),
cache: false,
beforeSend: function() {
$('.success, .warning').remove();
$('#button-checkout').attr('disabled', true);
$('#checkout').before('<div class="attention"><img src="view/image/loading.gif" alt="" /> <?php echo $text_wait; ?></div>');
},
complete: function() {
$('#button-checkout').attr('disabled', false);
$('.attention').remove();
},
success: function(html) {
console.log(data);
$('#checkout').html(html);
}
});
}
Sending data via get only seems to send a string, [object Object].
Change the dataType to json and all the html in result page disappears.
Experimented with $.parseJSON(data);, which returns null value in console.log.
What's the method to retrieve the data object so it can be json_decode($data, TRUE)d and available as a php array?
Try This
$.ajax({
url: 'index.php?route=sale/customer/checkout&token=<?php echo $token; ?>&customer_id=<?php echo $customer_id; ?>',
type: 'post',
dataType: 'json',
data: {
products: data
},
success: function (data) {
alert(data);
}
});

Posting JSON with jquery ajax to PHP

I have a simple php file that decode my json string, passed with ajax, and stamp the result, but I can't keep the $_POST variable, why???
I try to inspect with fireBug and I can see that the POST request is sent correctly, when the php script is called, he respond Noooooooob to me, it seem any POST variable is set.
All I want is to have my array =)
JSON String generated by JSON.stringify:
[
{
"id":21,
"children":[
{
"id":196
},
{
"id":195
},
{
"id":49
},
{
"id":194
}
]
},
{
"id":29,
"children":[
{
"id":184
},
{
"id":152
}
]
},
...
]
JavaScript
$('#save').click(function() {
var tmp = JSON.stringify($('.dd').nestable('serialize'));
// tmp value: [{"id":21,"children":[{"id":196},{"id":195},{"id":49},{"id":194}]},{"id":29,"children":[{"id":184},{"id":152}]},...]
$.ajax({
type: 'POST',
url: 'save_categories.php',
dataType: 'json',
data: {'categories': tmp},
success: function(msg) {
alert(msg);
}
});
});
save_categories.php
<?php
if(isset($_POST['categories'])) {
$json = $_POST['categories'];
var_dump(json_decode($json, true));
} else {
echo "Noooooooob";
}
?>
Your code works if you remove dataType: 'json', just tested it.
$('#save').click(function() {
var tmp = JSON.stringify($('.dd').nestable('serialize'));
// tmp value: [{"id":21,"children":[{"id":196},{"id":195},{"id":49},{"id":194}]},{"id":29,"children":[{"id":184},{"id":152}]},...]
$.ajax({
type: 'POST',
url: 'save_categories.php',
data: {'categories': tmp},
success: function(msg) {
alert(msg);
}
});
});
it's work for me you can try this.
JavaScript
$('#save').click(function() {
$.ajax({
type: 'POST',
contentType: 'application/json',
url: 'save_categories.php',
dataType: 'json',
data: JSON.stringify({'categories': $('.dd').nestable('serialize')}),
success: function(msg) {
alert(msg);
}
});
});
you need to write the below code on save_categories.php
$_POST is pre-populated with form data.
To get JSON data (or any raw input), use php://input.
$json = json_decode(file_get_contents("php://input"));
$categories = $json->categories;
dataType is json, so jQuery posts this:
{"categories":"[{\"id\":21,\"children\":[{\"id\":196},{\"id\":195},{\"id\":49},{\"id\":194}]},{\"id\":29,\"children\":[{\"id\":184},{\"id\":152}]},...]"}
This is not standard urlencoded, so $_POST is empty.
You can set data to your complex structure, and jQuery will correctly encode it:
$('#save').click(function() {
$.ajax({
type: 'POST',
url: 'save_categories.php',
dataType: 'json',
data: $('.dd').nestable('serialize'),
success: function(msg) {
alert(msg);
}
});
});
And in php: $categories = json_decode(file_get_contents('php://stdin'));
Try this:
$('#save').click(function() {
var tmp = JSON.stringify($('.dd').nestable('serialize'));
// tmp value: [{"id":21,"children":[{"id":196},{"id":195},{"id":49},{"id":194}]},{"id":29,"children":[{"id":184},{"id":152}]},...]
$.ajax({
type: 'POST',
url: 'save_categories.php',
dataType: 'json',
data: 'categories=' + encodeURIComponent(tmp),
success: function(msg) {
alert(msg);
}
});
});
I changed just this line:
data: 'categories=' + encodeURIComponent(tmp),
because thats the way, how you have to write data there. I tested it, its working...

Categories

Resources