Execute <script> from separate .php file - javascript

Been working on (what seemed like) a simple issues for a few days now and could use some help.
I call a php file on a button-click, do a bunch of server-side operations, and wish to change a few things in the HTML at the end of the php (change images, changing text, enabling buttons, etc.)
So, what I'm trying to do (for the test case here) is change an image twice. It works fine in the first set of code (script in the html file), but it doesn't work in the second set of code (script in the php file). I.e., I see oldImage when the page loads, secondImage when I click the button, but I never see newImage.
<button onclick="test()">Try The Test</button>
<img id="myImage" src="oldImage.jpg">
<script>
function test()
{
var img = document.getElementById('myImage');
img.src = 'secondImage.jpg';
xmlhttp=new XMLHttpRequest();
xmlhttp.open("testPhp.php",true);
xmlhttp.send();
}
</script>
Here's myPhp.php (all on one line in my code; two lines here, for readability):
$script = "<script> var img = document.getElementById('myImage');
img.src = 'newImage.jpg'; </script?";
echo $script;
Any ideas on why the script in myPhp.php doesn't work?
EDIT:
I changed the HTML portion to this, then changed myPhp.php to echo "Hello World", which shows up just fine within myDiv. However, I can't seem to echo the script. Is there any way to do this?
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","portTester.php",true);
xmlhttp.send();

If your ajax call returns markup, for it to have any effect, it has to be added to the DOM.
But I wouldn't recommend doing it this way. Instead, have your PHP file return the information (not a script), and then have the code receiving the information (in the onreadystatechange handler of the XHR object) read that information and take the relevant action.
For example, your PHP could simply return:
newImage.jpg
Then your ajax call would be:
function test()
{
var img = document.getElementById('myImage');
img.src = 'secondImage.jpg';
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange = handleReadyStateChange;
xmlhttp.open("testPhp.php",true);
xmlhttp.send();
function handleReadyStateChange() {
if (xmlhttp.readyState === 4 && xmlhttp.status >= 200 && xmlhttp.status < 400) {
// Request is complete and successful
img.src = xmlhttp.responseText;
}
}
}
If you need to send back richer information (as is frequently the case), look at using JSON.

You're not doing anything with the response to your AJAX call. In other words: You are calling the PHP script, the reply is printed, but is thrown away, because your Javascript isn't doing anything with it. You must add some code to interact with the reply. Here's a hint: Don't try to output Javascript from PHP, output something that you USE in your Javascript.
Add this to your Javascript after the xmlhttp.send() call:
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("myImage").src = xmlhttp.responseText;
}
}
And in your PHP script, put just this:
echo 'newImage.jpg';

One possible issue is that you are missing the semi-colon after your test() in the onclick. Also, your </script> tag is malformed; it reads </script? while it should read </script>. Also, where into the DOM is this echoing? It should go into the head of your document. Right now, it looked unspecified.

Related

how to fix xmlhttprequest function problem when inserting data

my code works only if i add this code:
document.write(str);
which open a new page and write in it insert data in database
but if i try to the code without it like this :
function addcourse2(str,cn)
{
xmlhttp=new XMLHttpRequest();
//document.write(str);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4 && xmlhttp.status == 200) {
alert('response:'+xmlhttp.responseText);
} else {
alert('failure!');
}
};
xmlhttp.open("GET","tpages/addcourse2.php?q="+str+"&p="+cn,true);
xmlhttp.send();
}
here i get alert message failure and nothing gets inserted into database
i need and explanation to this a way to fix it
looking at your comments i understand that the page is refreshing after you click the button before the state is reaching 4 then this is the button code to prevent it from refreshing
add return false;
<button "onclick='addcourse2("value1","value2");return false;'>add course</button>
Let's try to describe.
Note: as document.write writes to the document stream, calling document.write on a closed (loaded) document automatically calls document.open.
https://developer.mozilla.org/en-US/docs/Web/API/Document/write
So, this AJAX script with document.write work as from new page and each case calls to URL ""tpages/addcourse2.php?q="+str+"&p="+cn"
If commented document.write Then browser may be cached URL and browser read from cache and doesn't call same URL. So, you can use unique URL string and test so.
Also, may be was an other case.

Calling php function inside Javascript code

I know that this question has been asked before but all of them are using jQuery library and i would like to use Javascript only, no libraries so please bear with me.
This link shows the PHP function being called from jQuery.
How can I call PHP functions by JavaScript?
The code is calling a function that displays images.
I have the following code and I don't understand how to call the function from the mainfile.php and not functions.php.
mainfile.php
<button id="btn">Click</btn> // button that calls ajax file
<div id="div"></div> // div where it should appear
<script>
function loadXML(method, url, div, index)
{
var xmlhttp;
try
{
xmlhttp = new XMLHttpRequest();
}
catch(e)
{
try
{
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
catch(e)
{
alert('sorry');
}
}
xmlhttp.onreadystatechange = function()
{
if( xmlhttp.readyState === 4 && xmlhttp.status === 200 )
{
if( index === null || index === 'undefined' || xmlhttp === '')
{
document.getElementById(div).innerHTML = xmlhttp.responseText;
}
}
};
xmlhttp.open(method, url, true);
xmlhttp.send(null);
}
document.getElementById('btn').addEventListener('click', function()
{
loadXML('GET', 'imgs.php', 'div', null);
}, false);
</script>
functions.php
<?php
function getImgs($dir, $type)
{
$images = glob($dir . $type);
print_r($images); // for now i'm printing the array the way it is to see the function work
}
getImgs('images/', '.*JPG'); // calling function from php file works
?>
I would like to call the function from inside mainfile.php without using any jQuery library, only plain Javascript, it should be possible considering that the libraries are made with Javascript. I don't know where to call the function from inside mainfile.php. Any help would be appreciated.
The reason I am getting files from php is because it is easier to load them into the DOM, I need to make an image gallery so I would like to know if it will be possible to manipulate the images when they are loaded into the DOM using AJAX.
You can only do it by Making an AJAX request to a php page while passing in a parameter to initialise the function.
That means your AJAX will send in for example "functionName" to the php page "functionsListPage.php"
The GET will be recieved :
if (isset($_GET['functionName']))
functionExec();
This is the only way so you are not calling direct from the client however you are indicating to the server you want to run a predefined request.
You cannot call a PHP function directly from the clientside.
It's just like the answer from #Pogrindis, but i think so explanation is needed
It is possible to do it with with plain JavaScript with a little workaround!
What you need to do is the following in JavaScript after the xmlhttp.open();
var functionname = getImgs;
xmlhttp.open();
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
xmlhttp.send(functionname);
What this does is simple: it sends the data to the server, so you php file can get this parameter!
In your called php file you need something like this:
if( isset($_POST['functionname']) )
{
if($_POST['functionname']) == 'getImgs'
{
getImgs();
}
}
Of course you need to make sure that you post the data with post in this case, if you want to use get you need to change the php to $_GET
Notice: This is totally unsafe right now! No escaping from the coming data and anything else.

Function delivers value, before ajax request changed it

I am running an ajax request to retrieve a value of either 0,1, or 2 based upon some mysql code in the "check_answer_status.php" file. For test purposes, I have included the alert to check whether the general ajax and mysql request works fine and it does, hence the value contained within "Questiions.answerStatus" at the time of the alert is correct. However, my problem is that the function "checkAnswerStatus" has already executed and did not change the inital value of "answerStatus" (which I set to 50 for test purposes).
Context: sometime later in the code I want to execute code dependent on the value of the variable "answerStatus".
I believe I need to somehow include something like an "oncomplete" or something comparable, but I do not know how to do that. Can anyone help me out? Many thanks!
var = Questions = {
answerStatus:50,
checkAnswerStatus : function(question){
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
test = xmlhttp.responseText;
Questions.answerStatus = test;
alert(Questions.answerStatus);
}
}
xmlhttp.open("POST","../../include/check_answer_status.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("q="+question);
},
The request you make is asynchronus (the third parameter of the xmlhttp.open function). If you changed it to:
xmlhttp.open("POST","../../include/check_answer_status.php",false);
it should work.
Another options is to pass a callback to your checkAnswerStatus function, and call the callback when the request finishes. Example:
checkAnswerStatus : function(question, callback){
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
test = xmlhttp.responseText;
Questions.answerStatus = test;
callback(Questions.answerStatus); //call the function
}
}
xmlhttp.open("POST","../../include/check_answer_status.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("q="+question);
}
and then you will call the function like this:
Questions.checkAnswerStatus("bla bla", function(answerStatus) {
alert(answerStatus);
});
in addition to Nemos answer I would recommend you read following resources from MDN:
More technical API documentation for a brief overview of all the possibilities:
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
More real life usecases:
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
Hope this helps

Replace current page with ajax content

I have a page with a dialog window which sends ajax post data to server and receives a response. During development, there can be two responses - one regular (this is not the question) or one with an error. Server returns code 500 and a page with lot of debug informations. This is a regular page returned from a framework and contains some javascript code. I want to be able to display this error page in case it happens.
The problem is, I can not simply attach the returned result to body element or open a new link in a new page and load this error again. I simply get a html page instead of data and I have to display the page (in current window or in another one).
I am using jQuery.
Configure jQuery ajax setup as follows:
$.ajaxSetup({
error: handleXhrError
});
where handleXhrError function look like this:
function handleXhrError(xhr) {
document.open();
document.write(xhr.responseText);
document.close();
}
See also:
Handling of server-side HTTP 4nn/5nn errors in jQuery
You may also try to use data URL's, the latest versions of the major browsers supporting it:
function utf8_to_b64( str ) {
return window.btoa(unescape(encodeURIComponent( str )));
}
function loadHtml(html)
{
localtion.href='data:text/html;base64,'+utf8_to_b64(html);
}
This way, you can load any html page you want in runtime.
In your ajax callback:
success: function (data) {
$("html").html($(data).find("html").html());
}
That will replace the entire page's HTML content with the one received from your AJAX request. Works in Chrome... not sure about IE.
Despite that, I'm not sure why you'd want to include the <head> section... but you can easily modify the above to display just what's in the body of the AJAX response, and append it to a div or even a lightbox. Much nicer.
Here is an example of how to change either if the response is a url or a html content (using django\php)
var xmlhttp;
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
var replace_t = '{{ params.replace_t }}';
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
if(replace_t == 'location')
window.location.replace(xmlhttp.responseText);
else if(replace_t == 'content')
{
document.open();
document.write(xmlhttp.responseText);
document.close();
}
}
}
xmlhttp.open("GET",SOME_ASYNC_HANDLER_URL,true);
xmlhttp.send();
I found this solution. I don't know if it si correct, but for Opera and Firefox it is working.
var error_win = window.open(
'',
'Server error',
'status=0,scrollbars=1, location=0'
);
error_win.document.write(XMLHttpRequest.responseText);
Have you tried just simply creating an element and inserting the returned error page into the element? I do this with error pages and jQuery.
var errorContainer = $( '<div/>' );
errorContainer.html( errorTextResponse );
errorContainer.appendTo( $( 'body' ) );
I may be misunderstanding, but do you know what elements from the result you specifically want to display? You could trying something like this:
success: function(data){
//store the response
var $response=$(data);
//use .find() to locate the div or whatever else you need
var errorMessage = $response.find('#warning').text();
alert(errorMessage);
}
Is that what you were looking for?
I don't think there's any way to do that. Iframes are meant for loading other pages and there's no other sandbox in which to dump a standalone page -- that's what frames were designed for.
It might be difficult with the framework you're using, but it's probably worthwhile to have it generate different errors for your Ajax requests. My Ajax pages will only ever send
{"exit": 1, "message": "As in the shell, a non-zero exit is an error and this is why..."}
Just figured this out
as easy as
document.body.innerHTML = YourAjaxrequest.responseText;
_______________________________________________^ up here is what over writes your current HTML page with the response.
request.onreadystatechange = function() {
if (request.readyState == 1) {
document.getElementById('sus').innerHTML = "SENDING.......";
}
if (request.readyState == 3){
document.getElementById('sus').innerHTML = "SENDING >>>>>>>>>>>>>";
}
if (request.readyState == 4 && request.status == 200) {
//document.getElementById('sus').innerHTML = request.responseText;
document.body.innerHTML = request.responseText;
}
}
request.send(formD);
},false);

XMLHTTPrequest request not working

I tried the following code to send request to jsp page on a click of button. I checked on Httpfox but no request is going. I just used the whole of this code in the body of the html code. Am I doing some silly mistake. Kindly suggest..
<button type="button" onClick="handleButtonClick();">Click Me!</button>
<script type="text/javascript">
function handleButtonClick()
{
// Declare the variables we'll be using
var xmlHttp, handleRequestStateChange;
// Define the function to be called when our AJAX request's state changes:
handleRequestStateChange = function()
{
// Check to see if this state change was "request complete", and
// there was no server error (404 Not Found, 500 Server Error, etc)
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var substring=xmlHttp.responseText;
// Do something with the text here
alert(substring);
}
}
xmlhttp = new XMLHttpRequest();
xmlHttp.open("GET", "http://csce:8080/test/index.jsp?id=c6c684d9cc99476a7e7e853d77540ceb", true);
xmlHttp.onreadystatechange = handleRequestStateChange;
xmlHttp.send(null);
}
</script>
Well, in JavaScript, variables are case-sensitive. You have xmlHttp and xmlhttp; those should be the same.
You've also got <pre><code> at the beginning of your <script> block, which is a JavaScript syntax error.
Since no request is being made, I am not convinced you can actually make requests to "http://csce:8080" as FireFox may not see that URL as being on the same subdomain (You cannot make Ajax requests for resources not on the same domain as the requestor).
Suppose you made the URL relative. Is a request even generated then? If so, that is likely your problem.
Quote: xmlhttp = new XMLHttpRequest();
Two things. First, you might want to use a more robust method of getting an XMLHttpRequest object. Second, javascript is case-sensitive; xmlhttp != xmlHttp
xmlHttp = (function (x,y,i) {
if (x) return new x();
for (i=0; i<y.length; y++) try {
return new ActiveXObject(y[i]);
} catch (e) {}
})(
window.XMLHttpRequest,
['Msxml2.XMLHTTP','Microsoft.XMLHTTP']
);
Quote: http://csce:8080/test/ind...
Keep in mind that cross-domain xmlhttp is verboten. Unless you're serving from csce:8080, that ain't gonna work.

Categories

Resources