No response for ajax reauest
No response for ajax reauest
Hi
Trying to follow the course instructions, (Udemy) I wrote the following script, which works as expected, that is, it returns (displays) the number of reservations made at the requested site and date.
<?php
$currDir = dirname(__FILE__) . '/..';
include("$currDir/defaultLang.php");
include("$currDir/language.php");
include("$currDir/lib.php");
/* Grant access a usuarios que pueden acceder */
$od_from = get_sql_from('Reservas');
if (!$od_from){
header('HTTP /1.0 401 ACCESO NO AUTORIZADO!');
exit;
}
// echo "Acces granted!<br>";
$idSitio = intval($_REQUEST['idSitio']);
$enFecha = $_REQUEST['enFecha'];
$nSitios = sqlValue("SELECT COUNT(*) FROM Reservas WHERE Sitio ='{$idSitio}' AND Fecha='{$enFecha}'");
// Now, $nSitios contains the number of reservations for this date and Sitio
echo $nSitios;
?>
</code>
If I call the script "manually" in my browser
http://localhost/cczres/hooks/ajax-vali ... 2023/05/31
it shows 1, or 0 , as appropriate. Until here, no problem.
But, my ajax request
/* Esta funcion muestra un error y selecciona el campo donde ocurre */
function show_error(field, msg){
modal_window({
message: '<div class="alert alert-danger">' + msg + '</div>',
title: 'Error in ' + field,
close: function(){
$j('#' + field).focus();
$j('#' + field).parents('.form-group').addClass('has-error');
}
});
return false;
}
/* Transforma el input del usuario en un objeto Date de JS */
function get_date(date_field){
var y = $j('#' + date_field).val();
var m = $j('#' + date_field + '-mm').val();
var d = $j('#' + date_field + '-dd').val();
var date_object = new Date(y, m - 1, d);
if(!y) return false;
return date_object;
}
/* jscript to validate */
$j(function(){
$j('#update, #insert').click(function(){
// Fecha must be a date not before today when the user insert or update the reserva
// Get Sitio from input form
var enSitio = $j('#Sitio').val();
var numSitio = Number(enSitio);
// Get date from input form
var y = $j('#Fecha').val();
var m = $j('#Fecha-mm').val();
var d = $j('#Fecha-dd').val();
// and format
if (m < 10){
m = '0' + m;
}
if (d < 10){
d = '0' + d;
}
strDate = y + '/' + m + '/' + d;
console.log(strDate);
debugger;
if (!y){
return show_error('Fecha', 'Fecha Incorrecta!'); // This is only to follow as in the course
}
else {
$j.ajax({
url: 'hooks/ajax-validaSitio.php',
data: { NumSitio: NumSitio, enFecha: strDate},
success: function(data){
$j('#Comentarios').val('Answer is ' + data);
console.log(data);
debugger;
}
});
}
});
})
And, no matter I do, I never get an "success" answer from my $j.ajax request
All the code inside the function(data){ ...} Never is executed
What am I doing wrong ??
And, how can I debug java script & php code??
Trying to follow the course instructions, (Udemy) I wrote the following script, which works as expected, that is, it returns (displays) the number of reservations made at the requested site and date.
<?php
$currDir = dirname(__FILE__) . '/..';
include("$currDir/defaultLang.php");
include("$currDir/language.php");
include("$currDir/lib.php");
/* Grant access a usuarios que pueden acceder */
$od_from = get_sql_from('Reservas');
if (!$od_from){
header('HTTP /1.0 401 ACCESO NO AUTORIZADO!');
exit;
}
// echo "Acces granted!<br>";
$idSitio = intval($_REQUEST['idSitio']);
$enFecha = $_REQUEST['enFecha'];
$nSitios = sqlValue("SELECT COUNT(*) FROM Reservas WHERE Sitio ='{$idSitio}' AND Fecha='{$enFecha}'");
// Now, $nSitios contains the number of reservations for this date and Sitio
echo $nSitios;
?>
</code>
If I call the script "manually" in my browser
http://localhost/cczres/hooks/ajax-vali ... 2023/05/31
it shows 1, or 0 , as appropriate. Until here, no problem.
But, my ajax request
/* Esta funcion muestra un error y selecciona el campo donde ocurre */
function show_error(field, msg){
modal_window({
message: '<div class="alert alert-danger">' + msg + '</div>',
title: 'Error in ' + field,
close: function(){
$j('#' + field).focus();
$j('#' + field).parents('.form-group').addClass('has-error');
}
});
return false;
}
/* Transforma el input del usuario en un objeto Date de JS */
function get_date(date_field){
var y = $j('#' + date_field).val();
var m = $j('#' + date_field + '-mm').val();
var d = $j('#' + date_field + '-dd').val();
var date_object = new Date(y, m - 1, d);
if(!y) return false;
return date_object;
}
/* jscript to validate */
$j(function(){
$j('#update, #insert').click(function(){
// Fecha must be a date not before today when the user insert or update the reserva
// Get Sitio from input form
var enSitio = $j('#Sitio').val();
var numSitio = Number(enSitio);
// Get date from input form
var y = $j('#Fecha').val();
var m = $j('#Fecha-mm').val();
var d = $j('#Fecha-dd').val();
// and format
if (m < 10){
m = '0' + m;
}
if (d < 10){
d = '0' + d;
}
strDate = y + '/' + m + '/' + d;
console.log(strDate);
debugger;
if (!y){
return show_error('Fecha', 'Fecha Incorrecta!'); // This is only to follow as in the course
}
else {
$j.ajax({
url: 'hooks/ajax-validaSitio.php',
data: { NumSitio: NumSitio, enFecha: strDate},
success: function(data){
$j('#Comentarios').val('Answer is ' + data);
console.log(data);
debugger;
}
});
}
});
})
And, no matter I do, I never get an "success" answer from my $j.ajax request
All the code inside the function(data){ ...} Never is executed
What am I doing wrong ??
And, how can I debug java script & php code??
Re: No response for ajax reauest
how can I debug java script [...] code?
A 60 seconds introduction
Open your browser's developer tools (usually
F12
key), reload the page and check request and response in Network tab. In Network tab you can use Filter option to just see calls to YOURSCRIPTNAME.php
. When selecting the line for your (AJAX-) script call, check Payload and Response.For debugging javascript just add the line
debugger;
somewhere in your (javascript) code. Keep your developer tools open. Reload the page. Whenever execution reaches that line, execution will stop and code will be shown in developer tools. You can step line by line with F10
key. Other useful keys are F11
and F8
. For debugging variables, use
console.log('hello world');
or console.log(myVariable);
an watch the output in Console tab.More about developer tools:
https://developer.chrome.com/docs/devtools/
This works in modern Chrome, Firefox, Edge at least, should also work in Opera. Browsers/operating systems may have different options and/or keyboard shortcuts.
Remember that your browser may cache old script versions. Disable caching in your developer tools or reload without cache (depending on your browser.
CTRL+R
or SHIFT+F5
may work) to ensure you get latest javascript code on reload.Kind regards,
<js />
My AppGini Blog:
https://appgini.bizzworxx.de/blog
You can help us helping you:
Please always put code fragments inside
<js />
My AppGini Blog:
https://appgini.bizzworxx.de/blog
You can help us helping you:
Please always put code fragments inside
[code]...[/code]
blocks for better readabilityRe: No response for ajax request
Hi
It has been one of the most profitable minutes of my life. Thank you very much for the help and advices. I have made a lot of progress, although I still have the following problem;
I know it is working, because I can see
But I can't access the value that contains data in any way. If I try something like
The if never execute!. I tried var result = parseFloat(data); but same result
How can I retrieve the data value??
Thks for your invaluable help !
It has been one of the most profitable minutes of my life. Thank you very much for the help and advices. I have made a lot of progress, although I still have the following problem;
Code: Select all
$j.ajax({
url: 'hooks/ajax-validaSitio.php',
data: {mySitio: mySitio, enFecha: enFecha},
success: function(data){
alert(data);
$j('#Comentarios').val(data);
}
});
But I can't access the value that contains data in any way. If I try something like
Code: Select all
if (data){
return show_error('Sitio', 'Sitio is already reserved!);
}
How can I retrieve the data value??
Thks for your invaluable help !
Re: No response for ajax reauest
Maybe I have misunderstood your question, but you already do retrieve the data value!How can I retrieve the data value?
Yoursuccess: function(data) { alert(data); $j('#Comentarios').val(data); }
alert(data)
shows 19
. This means you have successfully requested from the server and your server has responded the correct value. If, immediately after that, the field
Comentarios
does not show "19", there must be a problem with the command $j('#Comentarios').val(data)
. In your screenshot we cannot see the field
Comentarios
you are refering to, so we have to guess.There may be several reasons, these come into my mind immediately:
- the field's
id
is different thanComentarios
- the field does not exists at the moment you receive data
- the field is not an
<input/>
control - there is another javascript code overwriting the value later
- the field is static, for example due to missing permissions.
In these cases you should try with$j('#Comentarios').text("my new value")
instead ofval(...)
.
<input type="text" id="Comentarios" ...more... />
, then .val("new value")
should work and "19" should be inserted into the input control. Testing
- You should try setting
.val("...")
on document.ready, just without any AJAX and see if this works at all. - You can also try logging current value before changing it with
console.log($j('#Comentarios').val());
---
Thanks, happy to hear that!It has been one of the most profitable minutes of my life
Feel free to Buy me a coffee
Kind regards,
<js />
My AppGini Blog:
https://appgini.bizzworxx.de/blog
You can help us helping you:
Please always put code fragments inside
<js />
My AppGini Blog:
https://appgini.bizzworxx.de/blog
You can help us helping you:
Please always put code fragments inside
[code]...[/code]
blocks for better readabilityRe: No response for ajax reauest
Your console should have shown a red error for this line, because there is a single quoteif (data) { return show_error('Sitio', 'Sitio is already reserved!); }
'
missing at the end before the );
.Your server responds with a string, I guess. What does it respond if not reserverd? Empty string?
Try this:
Code: Select all
$j.ajax({
url: 'hooks/ajax-validaSitio.php',
data: {mySitio: mySitio, enFecha: enFecha},
success: function(data){
if (data != '') {
alert('Sitio is already reserved');
}
}
});
Code: Select all
if (parseInt(data) > 0) {
// your alert here
}
Code: Select all
$j.ajax({
url: 'hooks/ajax-validaSitio.php',
data: {mySitio: mySitio, enFecha: enFecha},
success: function(data) {
debugger;
console.log(data);
console.log(data == '');
console.log(data != '');
console.log(parseInt(data));
// and so on...
}
});
F10
) and always check console output. Only continue with writing more code if the existing code is valid.Kind regards,
<js />
My AppGini Blog:
https://appgini.bizzworxx.de/blog
You can help us helping you:
Please always put code fragments inside
<js />
My AppGini Blog:
https://appgini.bizzworxx.de/blog
You can help us helping you:
Please always put code fragments inside
[code]...[/code]
blocks for better readabilityRe: No response for ajax request
Me again!
Thanks for the patience. I think I found the cause of my problem. The script doesn't seem to run in sequence. When executing it line by line, I observe that the code OUTSIDE the ajax request is executed FIRST, (when data is equal to "")
and only after that, the ajax request is executed, (and now yes, returns "12/r/n")
but then, the function returns and I never get anything in var t. And if I try to put a value ( var n = data;) inside the function(data) Always n it is undetermined
The strange thing is that I follow almost line by line the exercise of the course (Udemy) and there it does seem to work!
Of course, I will don't forget your coffee!
Thanks for the patience. I think I found the cause of my problem. The script doesn't seem to run in sequence. When executing it line by line, I observe that the code OUTSIDE the ajax request is executed FIRST, (when data is equal to "")
and only after that, the ajax request is executed, (and now yes, returns "12/r/n")
but then, the function returns and I never get anything in var t. And if I try to put a value ( var n = data;) inside the function(data) Always n it is undetermined
The strange thing is that I follow almost line by line the exercise of the course (Udemy) and there it does seem to work!
Of course, I will don't forget your coffee!
Re: No response for ajax reauest
Update
Forgive me. I come from strongly typed and secuencial languages (C & SQL). A from Ajax is for Asynchronous. So I have no way of knowing when it will return my value.
Any advice?
The answer can be found here;
https://stackoverflow.com/questions/142 ... ect=1&lq=1
Sorry for my lack of experience! I'm a newby in javascritp!
Forgive me. I come from strongly typed and secuencial languages (C & SQL). A from Ajax is for Asynchronous. So I have no way of knowing when it will return my value.
Any advice?
The answer can be found here;
https://stackoverflow.com/questions/142 ... ect=1&lq=1
Sorry for my lack of experience! I'm a newby in javascritp!
Re: No response for ajax reauest
ExactlyA from Ajax is for Asynchronous
For sure you can! You have to check data inSo I have no way of knowing when it will return my value
success
event of your AJAX call. That function gets executed when your client has successfully received a response from your server after serversidely processing the AJAX call. See the example in my last post:
Code: Select all
$j.ajax({
url: 'hooks/ajax-validaSitio.php',
data: {mySitio: mySitio, enFecha: enFecha},
success: function(data){
if (data != '') {
alert('Sitio is already reserved');
}
}
});

Kind regards,
<js />
My AppGini Blog:
https://appgini.bizzworxx.de/blog
You can help us helping you:
Please always put code fragments inside
<js />
My AppGini Blog:
https://appgini.bizzworxx.de/blog
You can help us helping you:
Please always put code fragments inside
[code]...[/code]
blocks for better readabilityRe: No response for ajax reauest
Of course, I can see data and his value, but..
When the value returns, it is not useful to me, since if it returns "0\n\r" this should be treated as 0 and ALLOW the reservation. Any value <> 0 should NOT be allowed to reserve. But, when this happen, the whole function has yet returned!
The problem is that the code that follows the function, which is where I can do the processing to see if it's 0 or <> 0, is executed immediately after the ajax call (and ajax hasn't responded yet).
And this is how ajax works, so there is no much to do... (the sync option has been deprecated)
There is a "callback" workaround discussed here ...
https://stackoverflow.com/questions/144 ... s-or-error
but looks complicated for a newby javascript
By the way, the reason why the Udemy example code works correctly is because at the moment they do it THEY ARE NOT SAVING the form. I programmed my function when the user clicks on insert or update, so, the execution is not awaiting forn any additional input and goes on ...
Fortunately, I found an easier way to solve it, using the "before insert" function provided by AppGini hooks.
Great learning! Thks for all your help and support!!
See you in my next question !
When the value returns, it is not useful to me, since if it returns "0\n\r" this should be treated as 0 and ALLOW the reservation. Any value <> 0 should NOT be allowed to reserve. But, when this happen, the whole function has yet returned!
The problem is that the code that follows the function, which is where I can do the processing to see if it's 0 or <> 0, is executed immediately after the ajax call (and ajax hasn't responded yet).
And this is how ajax works, so there is no much to do... (the sync option has been deprecated)
There is a "callback" workaround discussed here ...
https://stackoverflow.com/questions/144 ... s-or-error
but looks complicated for a newby javascript
By the way, the reason why the Udemy example code works correctly is because at the moment they do it THEY ARE NOT SAVING the form. I programmed my function when the user clicks on insert or update, so, the execution is not awaiting forn any additional input and goes on ...
Fortunately, I found an easier way to solve it, using the "before insert" function provided by AppGini hooks.
Great learning! Thks for all your help and support!!
See you in my next question !
