Page 1 of 1

JQuery ajax call issue

Posted: 2025-04-22 04:11
by dlee
I added a button in the header-extra.php file:

Code: Select all

<button class="btn btn-primary" onclick="dlg()">Print Reservations</button>
i added this code to the footer-extra.php file:

Code: Select all

<script>
function dlg(){
	var currentMemberID = '<?=getLoggedMemberID()?>';
	if (currentMemberID != 'guest'){
		alert(currentMemberID); //here just to see if function is working
		$j.ajax({
				type: "POST",
				url: "../../test.php",
				data: "cs="+currentMemberID,
				datatype: "text"
		});
	}
}
</script>
Code in test.php:

Code: Select all

<?php

	$callsign = $_POST['cs'];
	
	echo '<script>alert('.$callsign.')</script>';
	echo $callsign;
	
	echo 'test'; //just to see if it works at all

?>
test.php is in the /garc/hooks/rpts/ folder
When I click the "Print Reservations" button the alert(curentMemberID) fires but the app never goes to test.php. Any ideas why it doesn't?
Any help with this is greatly appreciated
TD

Re: JQuery ajax call issue

Posted: 2025-04-22 04:40
by jsetzer
Debugging
  1. Check Network-tab in dev-tools (F12) to see if JavaScript code was able to POST to ../../test.php. Maybe ../../test.php is not correct, see Tip #1 below.
  2. Network-tab will show the (success?) status and the string-response of test.php.
  3. Fetching a string from the server does not mean the (string-) return value becomes javascript-code in your browser. It is just a string.
Tips
  • For building the complete URL in JavaScript you can use AppGini.config.url variable.
  • You may use jQuery.getScript('URL', (response)=> { /* YOUR CODE */ }) instead (see https://api.jquery.com/jQuery.getScript).
  • Caution When executing this again and again, be careful with event-handlers. You may attach them multiple times and they will fire multiple times unless you unbind them correctly.
  • When dynamically loading additional resources you need to care for browser cache or you will probably not get latest script from server but cached script.
I'm just curious:
Is there a special reason for dynamically loading a script instead of statically loading using <script src="https://MYSERVER/MYPATH/test.js.php"></script>?

Hope this helps.

Re: JQuery ajax call issue

Posted: 2025-04-22 13:07
by D Oliveira
Make sure the ajax path matches the file: (if your main file is inside /hooks this piece needs review)

url: "../../test.php", => /garc/hooks/rpts/ test.php

generally it's best to implement CSRF token validation or fetch the user's ID on the back-end code but depending on your use case you could be fine.

Re: JQuery ajax call issue

Posted: 2025-04-23 17:07
by dlee
Thanks to all who replied, it is greatly appreciated! Since I am in a rush to complete this project I just used $_GET instead for now. In the future I will try using $_POST with ajax again.