So I ran into a problem and I couldn't really find a good solution anywhere. And I'm sure more people run into this problem.
I tried to have an Ajax script call to a php-script which echoes a JavaScript function again but this function wont run or activate. It however does show up in the code if you do inspect element.
So the html and Ajax is as follows. Its dummy code since my own is a bit more complicated. so any syntax errors I made here are not the solution since this works for other parts of my code.
<html><headbodyetc>
<div id='change'>
//is supposed to alert or call another js function after
//verifying something with a database for instance.
<button type='button' onclick='ajaxbelow();'>alert</button>
</div>
<script type='text/javascript'>
function ajaxbelow(){
//AJAX code as found on w3schools.com/php/php_ajax_php.asp
//calls the change.php
</script>
</etc></html>
The php code that gets called is very simple.
//This shows up in the html-code after clicking the button but doesnt run.
echo"<script type='text/javascript'>alert('doenst work?')</script>";
So I am looking for a solution which makes me able to run a JavaScript or jquery function after an Ajax call, or the main reason why this doesn't work. Since I couldn't find it.
Inb4 why call the alert via php? Because I need to verify something first with the db on the server-side in my actual code.
So after combining and testing some of the comments I figured out my own answer.
You cant create new javascript within the php echo. You can however echo an onload that calls an existing function. Onload only works for the following tags:
"body", "frame", "frameset", "iframe", "img", "input type="image", "link", "script", "style".
However in this case after testing some of them like "script" and "img" it still didn't work with all tags, but it did with the "style" tag. I didnt test all other tags though.
So that changed my code to:
<html><headbodyetc>
<div id='change'>
//is supposed to alert or call another js function after
//verifying something with a database for instance.
<button type='button' onclick='ajaxbelow();'>alert</button>
</div>
<script type='text/javascript'>
//function to be called
function test(){
alert("now it works");
}
function ajaxbelow(){
//AJAX code as found on w3schools.com/php/php_ajax_php.asp
//calls the change.php
</script>
</etc></html>
and the php-code will then become
echo"<style onload='test();'></style>";
and now it does run the function.
edit this doesn't seem to work for IE, looking for a solution right now.
^
EDIT: By default, IE Browsers "DENY" the ability of scripts to throw prompts. So to enable this functionality, you must go to [Tools/ Internet Options/ Security / Custom Level / "Allow websites to prompt for information using scripted windows"] and enable that... Once you refresh, you will see your alert in IE :)
Just add slashes before single quote as given below
<?php echo '<script type="text/javascript">alert(\'doenst work?\')</script>'; ?>
You could use eval() to evaluate the returned javascript. The script tags wont be required if this method is used.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval
Try this:
http://www.webdeveloper.com/forum/showthread.php?184830-Ajax-echo-script-problem
Basically the reason why nothing happens is because you are just sticking content in the DOM. Javascript is an event driven language and since nothing is telling the javascript to run at this point, its just sitting there doing nothing. If that code were there when the browser loaded the page, then the browser parsing the code is what would tell it to run. So, what you need to do is evaluate any scripts that come back
Related
I have two pages. mobile.html and video.php. mobile.html sends an ajax post request with a single variable. video.php should read that variable and pass it to a JS function in the same page that would change a video control. I tried to use this logic:
mobile.html sends an ajax post request
video.php has PHP code inside a div to read the request and get the variable
reload video.php and allow the JS code in the same page to get the variable from inside the div
pass the variable to the intended JS function in video.php.
execute the function on the video.
here is my code and for simplicity I replaced the video with <p> tag. mobile.html code works fine. my problem is in video.php
mobile.html
$.post("video.php", {gesture: action}, function(response){
$("#result").html('response: '+response);
});
video.php
<html>
<head>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
//a div to hold the value of post variable
<div id="dom-target" style="display: none">
<?php
if ( $_SERVER['REQUEST_METHOD'] == 'POST' )
{
if( isset($_POST["gesture"]))
{//put the variable value inside the div to fitch it later
$gesture = $_POST["gesture"];
echo $gesture;
}
else {
echo "none";
}
}
else {
echo json_encode("PHP no post");
}
?>
</div>
//p content should be updated with the value of $gesture
<p id="update">
should be updated with post variable using JS
</p>
<script>
//get post variable from the div
var div = document.getElementById("dom-target");
var myData = div.textContent;
$("#update").html(myData);
console.log("myData: "+myData);
</script>
</body>
</html>
I have been up over my head for a week trying to work around this problem but I cannot seem to get the result that I want because when I reload the page I find my variable in the ajax callback function :/
the output I am getting currently is "PHP no post" in video.php and myData: "PHP no post" in the console of video.php which is ok because obviously the first time I run the page it is not through a post request. however when I click the button that triggers the post request in mobile.html I get the output of this line console.log("myData: "+myData); with the correct data but in mobile.html console! not in video.php console. meaning that the code is run in the callback function of the ajax post request in mobile.html.
I failed to find a way to update the <p id="update"> in the currently opened video.php page. Now I am not even sure I can do it with PHP since it runs only on a server and JS runs only on the web browser.
My question is: can I do the steps explained above using PHP ?
IF YES can you help me figure out a way to dynamically and instantly update the video.php page using a post call sent from mobile.html ? or any other way that would work with PHP?
IF NOT can you suggest what other languages/platforms I can use to do what I want to do ?
UPDATE:
to have an idea of what I want to achieve, I did two pages using localstorage. open mobil.html in one window and then openvideo.html
in another window side by side. play the video then use the controls on mobile.html and see how it changes the playback in video.html.
I want to be able to do the same thing but remotely using PHP because I have to use a real mobile instead of mobile.html
You are sending your gesture value to the video.php file, but you are not using it to get a new paragraph element with the updated value in it. PHP should do its work on the server and JavaScript strictly on the frontend.
Keep your POST request the same.
$.post("video.php", {gesture: action}, function(response) {
$("#result").html('response: ' + response);
});
But modify the response that server returns. The gesture value is in the $_POST array. From there you can use it to render a new paragraph and echo or return this to the frontend.
<?php
// Set default value.
$gesture = 'none';
if ( isset( $_POST[ "gesture" ] ) ) {
// Overwrite if there is a gesture value.
$gesture = $_POST[ "gesture" ];
}
// Echo a new paragraph with the gesture in it.
echo '<p id="update">' . $gesture . '</p>';
exit;
?>
first just please organize the code a little bit so you can see the code well
you need to put the post request inside a function with a trigger action because with that it would be never called
you need to make sure that you are getting the correct data in 'action' variable (console.log it before the post)
(if $.post is not working for some reason download jquery and use it locally because it might not be in the slim CDN)
Hint:
$( document ).ready(function() {
console.log(gesture); //check this in the console after refreshing the page
$.post("video.php", {gesture: action}, function(response){
$("#result").html('response: '+response);
});
});
I am answering my own question for those who have been rumbling about not understanding how to update a part of a web page in real time without having to reload it. Long story short, To achieve the scenario I mentioned in my question I have to use WebSockets as #EmielZuurbier pointed out in the comments of the first answer, so thanks to him.
There are tons of ways to do that.For beginners, you have to be patient and make sure you understand how it works properly before you jump in coding. Also, know that some codes that are available on the internet work only on the backend and that there are specific ways to make websockets work on a browser. In my case I used Node.js in the server side and isomorphic-ws in the client side in a web browser
here are some helpful references that helped me during the past week:
Here is the official site for Node.js for installation and documentation.
This is a good video to get you started if you are new to WebSockets. it explains Websockets and display real implementation of it.
Here you can find documentatino of WebSocket().
This video demonstrate how to implement a websocket in your local
machine (aka laptop): How to Create a WebSocket Server & Client.
Be aware that the video above will work only on backend which you can run using Terminal on mac or Command line in Windows. To work it on a
browser I used isomorphic-ws which is a wrapper that allows
websockets to work on web browsers.
I wish this could help anyone who was stuck like me on how to implement a real time communication between two ends.
I'm new to JQuery. I'm trying to call vbscript function inside jQuery. I want to call vbscript on button click using jQuery. I tried calling vbscript function "callfun()" using button onclick() method of javascript for button "Say Hello", and it is working. But when I'm trying to call the same vbscript function "callfun()" using jQuery for button "Say MACRO". It is showing nothing.
(THE BELOW CODE REQUIRES ENABLING OF ACTIVEXOBJECTS.)
Steps to run the below code:
Copy and save the below code in notepad and save the file with .html extension.
Open chrome, search for "IE TAB" extension or download from here, install it, and add it to chrome to enable the plugin icon.
Now open the .html file, click on IE TAB extension.
The link or html page will open automatically directly inside the IE TAB plugin and then the html code can be tested.
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type = "text/Vbscript">
Function callfun()
Msgbox("Hello!")
End Function
</script>
<script>
$(document).ready(function(){
$("#mac").click(function(){
callfun();
});
});
</script>
</head>
<body>
<input type = "button" onclick = "callfun()" value = "Say Hello" />
<input type = "button" id="mac" value = "Say MACRO" />
</body>
</html>
I even tried making changes in the jQuery script as:
Adding vbscript label before the function.
<script>
$(document).ready(function(){
$("#mac").click(function(){
vbscript:callfun();
});
});
</script>
Adding jQuery attr() function.
<script>
$(document).ready(function(){
$("#mac").attr("onclick", "callfun()");
});
</script>
Adding language in jQuery attr() function.
<script>
$(document).ready(function(){
$("#mac").attr("language", "vbscript").attr("onclick", "callfun");
});
</script>
But nothing called the vbscript function using jQuery.
Someone PLEASE help me or suggest me a way to get it done.
despite the fact you may be using this legitimately its not a 'nice' way to go about doing whatever your trying to do. and most browsers and even windows itself will try its hardest to block what you are doing on multiple levels because security wise this is a very VERY sketchy way of doing whatever your trying to accomplish lol
so the fact this doesnt work does not surprise me. what i would do is to get a packet sniffer running and read all the http data that occours to get clues on if its properly sent out and how server / page responds.
this probably violates the same-orgin policy DOM model of internet rules and stuff or atleast kinda close to violating it, your work is interesting i used to love vbscript but vbscript is becoming rapidly deprecated too
i dont recomend doing this at all: but just for test, you can lower your IE security settings level temporarily. and see if doing that allows sketchy scripts to go through
When I load the html page the alert("hey") function appears immediately, why does the js function execute despite no onClick call? How do I prevent it from doing so? I'm new to js. Thanks for any help.
<body>
<div id="container"></div>
<script type="text/babel" src="js/es6.js"></script>
<script>
function toggleNav(){
alert("hey");
}
</script>
</body>
Are you sure you get such alert dialog,here i have ran for two times but without such problem,so check your code and clean your browser cache.or you can also change a browser and test it.
and if the question is still there, i think there maybe a closure function in your extra import js file.what i thought were only that, wish i can help you.
The alert Hey is not coming from the toggleNav() function, you should check your head part of HTML to see if there is a javascript file included which could be causing this, or show us what's in your es6.js file, the js function won't be executed unless it is being called like
toggleNav(); in your case.
And even if it was called on the onclick event it wouldn't be executed on the page load. Make sure you reload your page after you saved your changes.
I got some php code like this to redirect my page inside one php function:
<script>
function a(){
<?php
header('Location: http://www.localhost.com/');
?>
}
</script>
I will like to know if there is any way to stop this to redirect inmediatly when i load my page, and if it is possible to do it with some Javascript or JQuery, cause I tried it with JS and I couldn't find a way to do it .
The php end of it will process before the javascript does. I'm not sure why you have it set up this way but you will need to come up with a different way of doing things. Perhaps not using PHP at all would be your best option here and just using a javascript command to change the page instead.
Such as:
<script>
function a(){
window.location = "http://www.localhost.com/";
}
</script>
<button onclick="a()">Go</button>
I don't think you can stop it when it comes from php, but you can have the redirect with javascript. See this for example.
I'm trying to insert reCaptcha code into my page from jQuery, but it doesn't work.
Here is my code:
$("#button").click(function() {
$("#loginBox").html($.getRecaptcha());
})
When I try the following, my code doesn't even run. I think it's trying to execute instead of rendering it.
$.getRecaptcha = function(){
return '<script type="text/javascript"' +
'src="http://api.recaptcha.net/challenge?' +
'k=6Ld3iAsAAAAAAGyX8QT244GagPEpCDSD-96o4gEi"></script>';
}
With the following, the code runs, but when I click to #button I get an empty, full white
browser window.
$.getRecaptcha = function(){
var captcha = $("<script>")
.attr("type", "text/javascript")
.attr("src", "http://api.recaptcha.net/challenge?k=6Ld3iAsAAAAAAGyX8QT244GagPEpCDSD-96o4gEi");
return captcha;
}
I don't want to insert reCaptcha code into my html from the beginning, because it downloads the reCaptcha content from the reCaptcha server even if my users don't want to use it. I could set the visibility of the container that holds the reCaptcha to invisible (display: none;), but it will dowload the content irrespectively of it.
I can insert the "noScript" code that reCaptcha gives us, but it doesn't work either, because it can spot that the browser allow javascript but I use noScript.
Any suggestions?
(I know I put my public reCaptcha key into the code, but it is just for testing purposes, and you could get it from my html or javascript code anyway)
UPDATE:
Krunal Mevada answered my question. But it doesn't work with reCaptcha. reCaptcha offers a reCaptcha AJAX API which is the answer to my specific question. However, with getScript() I can dinamically download the reCaptcha AJAX API javascipt file.
Use getScript method of jQuery.
May be this answer can be useful:
Stack Answer
First code part: insert a space at the end of the first line:
return '<script type="text/javascript" ' +