Lee
Lee

Reputation: 20934

Getting response from Using dataType script with jQuery on ajax request

Not sure if this should work but from a jquery ajax request with the response I want to evaluate the script being passed back. Here goes for an example.

$.ajax({
    url: some/path,
    dataType: 'script'
});

Then with my response I'm using php to spit out the javascript.

<?php
header("content-type: application/javascript");

$str = <<<EOF
    alert('help');
EOF;
echo $str;

If I'm correct I should get a alert pop-up after performing the request.

I can see from the response headers it correct:

Accept:application/json, text/javascript, */*; q=0.01 

And response is:

alert('help');

But no alert box is being triggered. Am I missing something or can this not be done this way?

Hope you can advise.

TY

Upvotes: 1

Views: 6252

Answers (1)

MD SHAHIDUL ISLAM
MD SHAHIDUL ISLAM

Reputation: 14523

You should call success function in $.ajax

and execute the response

page1.php

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" 
type="text/javascript"></script>

<script>

  $.ajax({

      url: "page2.php",

      dataType: 'script',

      success: function(resp) {

          resp;  //this is your response which is contains alert('help')

      }

    });

</script>

page2.php

<?php

header("content-type: application/javascript");

$str = <<<EOF
    alert('help');
EOF;

echo $str;

?>

Upvotes: 1

Related Questions