如何在javascript函数中使用“get_template_directory_uri”

This is a part of my WordPress PHP file code, in this I wrote a JavaScript code and I would like to display the names, images from the query. Names are displayed but images are not displaying, then I added get_template_directory_uri(), after adding get_template_directory_uri() it is showing error in console like this "Uncaught Syntax Error: missing ) after argument list". All images are stored in WordPress theme image folder. How to write javascript code to display images? Please Help me out from this problem.

Thanks.

function partyFunction(){
debugger;
$postdata = {};
$postdata["partyId"]=$("#partydropdown").val();
$.post('<?php echo get_template_directory_uri() ? 
>/GetPartiesData.php',$postdata,function (data) {
debugger;
console.log(data);
var stringreplace = data.replace(/['"]+/g, '');
console.log(stringreplace);
var res = stringreplace.split(",");
  console.log(res);
  $("#partyBody").empty();
  $("#partyBody").html('');
  $("#partyBody").append("<tr>"+
    "<td>"+res[1]+"</td>"+
    "<td><img src='"+<?php echo get_template_directory_uri() ? 
 >/img/++res[2]+"' style='padding:5px;vertical-align: middle;border-style: 
 none;width:129px;height:109px;' ></td>"+
 "<td><img src='"+res[3]+"' style='padding:5px;vertical-align: 
 middle;border-style: none;width:129px;height:109px;' ></td>"+
 "<td><a href='"+res[4]+"' target='_blank'>click here</a></td>"+
 "</tr>");
 });
 }

Uncaught SyntaxError: missing )

<img src='"+<?php echo get_template_directory_uri() ?>/img/++res[2]+"'

Replace with:

<img src='<?=get_template_directory_uri()?>/img/"+res[2]+"'

You missed semicolon the end of statement:

<?php echo get_template_directory_uri(); ?>
-                                      ^ just missed 

P.S. you have used same line more than once, kindly ensure all lines have been modified.

Method 1:

Assign it to a global variable in your php file then call it in javascript

like this at top of your .php file

<script>
  template_directory = "<?php echo get_template_directory_uri() ?>"
</script>

then use template_directory like this

$.post(template_directory+'/GetPartiesData.php',$postdata,function (data) {

same like this use in image src also.


Method 2:

Use wordpress enqueue functions

wp_register_script( 'template-directory', 'myscript_url' );
wp_enqueue_script( 'template-directory' );
wp_localize_script( 'template-directory', 'directory_name', array( 'templateUrl' => get_stylesheet_directory_uri() ) );

and use this in your script use like this

template_directory = directory_name.templateUrl;

$.post(template_directory+'/GetPartiesData.php',$postdata,function (data) {
//Add code in function.php 
function theme_directory_uri(){
wp_localize_script( 'ajax-login-script', 'uri_object', array( 
    'theme_directory_uri' => get_template_directory_uri()
));
}
add_action('init', 'theme_directory_uri');
//get in javascript

var theme_uri = uri_object.theme_directory_uri;