I'm trying to change the value on an input using javascript file called from Ajax, obviously, it's NOT Working :/
I have a page where I have:
<input type="text" id="hello">
$.ajax({
url : 'index.php',
type : 'GET',
data: "value=test",
success : function (result) {
},
error : function () {
}
});
in the index.php, I have:
echo "
<script>
parent.document.getElementById('hello').value = 'Please work';
</script>
";
I even tried "window.parent.docu....", still no luck. Any way there's a way to do it via the PHP file? Thanks a bunch!!
Please note, I do NOT want to this in the callback because i don't want users to see the handling of all the variables etc etc I want all that info to be done in PHP and then when it's complete fill out the variables on the main page.
CodePudding user response:
This sort of thing trips up a lot of PHP coders. PHP rendering happens on the server. By the time the page has been delivered to the user, it's just HTML and javascript; further attempts to modify the page via PHP will not work; echoing a new line of js will not append it to the document and execute it the way you're expecting it to.
Instead, you need to have your PHP script return the text you want inserted, and use javascript in the rendered page to insert it:
$.ajax({
url : 'index.php',
type : 'GET',
data: "value=test",
success : function (result) {
document.getElementById('hello').value = result;
},
error : function () {
}
});
CodePudding user response:
You really should not proceed with this design. Use callbacks correctly and properly decouple your interface from your backend instead.
However, if you want to cut corners here, you should be able to parse the resultant HTML string (provided its validity), then insert the parsed content into the DOM which should achieve what you seem to want:
$.ajax({
url : 'index.php',
type : 'GET',
data: "value=test",
success : function (result) {
document.appendChild(new DOMParser(result, "text/html").getRootNode().body);
},
error : function () {
}
});
CodePudding user response:
Seeing your comment about not wanting to us JavaScript because users can then see the code, and preferring it in the PHP (server side)... you can skip Ajax altogether and just put something like...
<input type="text" id="hello" value="<?php echo $variableWithData; ?>" />
... into the PHP page, and the HTML the gets sent to the client will just have something like...
<input type="text" id="hello" value="please work" />