Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can a file that is called by ajax call another file using ajax?

I need a PHP file that is called by ajax to call another file by AJAX when the value of a select changes.

Example:
-File1.php
Show header and more.
Makes an Ajax call to file2.php

File2.php
Shows services with editable fields with their data.
Makes an Ajax call to file3.php when I change the value of a specific select

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

File3.php
Save the data of that editable field

I mention this because it doesn’t work from File1.php, but if I do it directly from File2.php it does work.It seems that the javascript in File2.php does not work if called via AJAX.

>Solution :

No, because AJAX runs in the browser using JS.

If you send a HTTP request via AJAX to execute a PHP script then, as always it runs on the server. But in the AJAX scenario, even if that PHP script contains some JS, that JS is never loaded into a browser (because AJAX causes an asynchronous background request, rather than a page load into a browser tab), so of course the JS code would never run.

Note that even if you then insert the the whole of File2’s output into the DOM using JS when your first AJAX call ends, that won’t automatically cause the JS within it to be evaluated and executed – see here for more info.

(N.B. A PHP script called via AJAX could make another HTTP request using something like cURL but it doesn’t sound like it would be helpful in the scenario you’ve described.)


It seems like your design should probably be something like:

File1.php is the one displayed in the browser. This should contain (or link to) all the JS code required for this feature.

File2.php is called via AJAX, and returns some data (perhaps in JSON format) and then the code in File1 builds some HTML and to display that data.

Then when the "change" event occurs on a specific select, some JS code (which is already loaded via File1) runs and makes the AJAX request to File3.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading