javascript - JS is not being executed after ajax call -
i'm calling php script includes js code calling xmlhttprequest.send. unfortunatly javascript code in called php script not being executed.
the calling routine:
var formdata = new formdata(); formdata.append("uploadfilename", file); var ajax = new xmlhttprequest(); ajax.upload.addeventlistener("progress", progresshandler, false); ajax.addeventlistener("load", completehandler, false); ajax.addeventlistener("error", errorhandler, false); ajax.addeventlistener("abort", aborthandler, false); ajax.open("post", "mod/intern/uploader_upload_done.php"); ajax.send(formdata);
any javascript in called script fails, alert() call.
file uploader_upload_done.php:
<?php echo date(); ?> <script>alert("hallo");</script>
when calling uploader_upload_done.php directly, works should.
what doing wrong?
as understand make ajax call php file, , expect javascript there executed. should take account there difference between making call , opening url directly in browser; means downloading html + css + javascript code, , browser automatically interpreting it. when perform ajax call, asking server execute php code, , after that, downloads rest (html + css + javascript), not interpreting it.
if want execute javascript code being returned php file, embed page doing ajax call. this, can use:
function evaljsfromhtml(html) { var newelement = document.createelement('div'); newelement.innerhtml = html; var scripts = newelement.getelementsbytagname("script"); (var = 0; < scripts.length; ++i) { var script = scripts[i]; eval(script.innerhtml); } }
however, using eval can dangerous. author's demo: http://plnkr.co/edit/la7opkrfatgohwcanlrl?p=preview
this function useful when php file returns complete html document (i.e., html file head, body, etc.); gets script tags , executes javascript content.
if php file returns javascript code, can execute directly (again, consider not using eval in production environments). is:
var jscode = doajaxcall(); eval(jscode);
as suggested other users, consider using communication schema (e.g., json file indicate should executed, instead of passing code executed).
Comments
Post a Comment