Ajax call to the whole page

I have html/php file lets call it file1.php that has js included myscript.js
Is it possible to have ajax call inside myscript.js that will call this very same script. Something like this…

                  $.ajax({
                    type:"POST",
                    url : "file1.php",
                    ....
                    ....
           

Would this work? Because the way I understand this every time makes call to this script it will return the whole page file1.php?
Am I understanding this wrong?

PHP and JS have different execution times.

If you AJAX call a PHP page it’s not going to run any of the JS. All the PHP parser is looking for is anything inside <?php ?> tags. Once it’s done with those blocks, it ships whatever is left off to the browser that called it.

Once your AJAX request comes back, you’re now in JS’s execution time, and what you do with it is your own business, but i’d be leary of blindly executing whatever code the remote page gives back.

2 Likes

As @m_hutley pointed out that’s not how it works… but you can dynamically load scripts by creating new script elements, e.g.

var script = document.createElement('script')

script.src = 'myscript.js'
document.head.appendChild(script)

But why would you want to re-load and execute the very same script that’s already running? Just wrap the desired parts in functions and call these as you need them… and if you need data from the backend, create a regular endpoint for that.

Well what i am trying to do is this…

I want myscript.,js that is included in myfile1.php to pass form data from myfile1.php to backend where sql query will be executed based on the form data. I would like this database results to be returned to AJAX and appended to some HTML element

Okay… I think i’m understanding you a bit better.

You have a file, myfile1.php.
in myfile1.php, you call myjs.js (presumably in a <script src='myjs.js' /> tag)
myfile1.php contains form elements.
myjs.js contains code that (presumably when you click a button that says ‘submit’ or somesuch) fires an ajax call to another file. Lets call it backend.php.

So; what happens in Execution Time evaluation is:

  • Browser goes to myfile1.php.
  • PHP engine on the server parses myfile1.php, replacing or otherwise dealing with the <?php ?> blocks.
  • The resulting HTML is sent to the browser.
  • The browser begins parsing the Javascript in the result.
  • Form gets filled out by user.
  • User clicks button, invoking the function that contains an AJAX call.
  • Browser sends form data to backend.php, and returns immediately to its execution cycle (see asynchronicity). The AJAX function awaits a response in the meantime.
  • PHP engine on the server parses backend.php, replacing or otherwise dealing with the <?php ?> blocks. Presumably, this involves the database SQL query, and printing the results into the HTML in some form.
  • The resulting HTML is sent to the browser.
  • The Javascript AJAX call, which has been waiting for the response, handles it (presumably under it’s success: clause)
  • How it handles it is up to you, you can easily append the result to an HTML element.

Ok in the part above…What happens if backend file has multiple functions…so backend.php looks like this…

 function function1 (){
     echo "i am function that actually needs to work on form data";
 }

function function2(){
    echo "I am function that does something totally different and not related";
}

function1();
function2();

So in above what will be returned to AJAX?

Well, your PHP calls both functions. Echo outputs HTML. So what will be returned is
“i am function that actually needs to work on form dataI am function that does something totally different and not related”

Ok what would happen in this case…sorry I am answers to these are obvious but I am just trying to understand this…

 function function1 (){
     return $array1;
 }

function function2(){
    return $array2;
}

function1();
function2();

Nothing, because the function calls arnt being caught. I think where you’re trying to get to is something along the lines of this (And i’m going to convert to JSON, so that the ajax response can handle it better, unless you’re looking for a straight append.)

 function function1 (){
     return $array1;
 }

function function2(){
    //Does some stuff. We dont care what it's doing, really.
}

echo json_encode(function1());
function2();

So AJAX depends solely to what is in echo?

the response depends on what is OUTPUT. PHP has several output functions. echo is the primary one. print_r is another. Anything not inside <?php ?> blocks is also output.

<html><head></head><body>
<p>This is some text that will be output because it's outside the PHP tags.</p>
<?php doAFunction(); //This may or may not echo something. Depends on what's in doAFunction. ?>
<?php echo "So is this."; 
$array = ['a','b'];
print_r($array); //This gets ouput too...?>
</body></html>

Lets assume doAFunction doesnt output anything.
That would result in the output seen by the AJAX call of:

<html><head></head><body><p>This is some text that will be output because it's outside the PHP tags.</p>So is this.['a','b']</body></html>

(actually that might be a slight lie because i think print_r inserts line breaks. But it’s close enough.)

ok so in your js file where you have AJAX success: how would you check if you received this array [‘a’,‘b’]?

If I was trying to pass an object like an array, i’d be doing it as JSON. $.ajax contains a definition, ‘dataType’, which tells the command what sort of output to expect. I’d set that to ‘json’, and then do something like

<?php //First line of file.
$db = do_a_connect();
$array = do_my_database_query($db); //This function should return an array, even if it's an empty one.
echo "{'result':".json_encode($array)."}";
 //EOF 
?>

Note that i’ve had to wrap the array in a bit of extra string, as PHP doesnt know how to resolve a non-associative array into a JSON object [nor should it].
and then when the ajax comes back, catch the result as

success: function(data) {
   if(data.result.length == 0) {
     //empty result
   } else {
    //There was a result. Do a thing.
  }
}

or a forEach, depending on if you have specific behavior you want to model on an empty result.

This is my AJAX call…

$('form').click(function(e){
          e.preventDefault();
          var myData = $('form').serialize();

          console.log("I am just before ajax call " + myData);
                    $.ajax({
                    type:"POST",
                    dataType: 'json',
                    url : "myphp.php",
                    data: myData , // do I need to pass data if im GET ting?
                    success : function(data){
                       console.log("Success");
                    },
                    always: function() {
                       
                    }
                });//end ajax   
          console.log("Clicking on submit review form");

I see “Success” in my console but do not see anything if I put line console.log(data); right after it.

I can see POST request and response with correct datain my web dev tool but I am confused why console.log(data); doesnt show anything in console.

This is what I see in XHR response…

result':[{"rev_id":"54","user_id":"35","rest_id":"7","star_num":"3","title":"This is some title","review":"Great!!!!."}]}

is there a {’ before what you posted there? Cause if not, that’s missing.

This is php part → echo "{'result':".json_encode($r)."}";

This is response…

{'result':[{"rev_id":"67","user_id":"35","rest_id":"7","star_num":"3","title":"This is some title","review":"Great!!!."}]}

data only exists until the end of that function. console.log(data) instead.

Its funny how only way I can get it “success” in my console is if I block this in AJAX

  //dataType: 'json',