I have the problem when i echo this:
echo "Logged in! <script> alert('hello'); </script>";
The message "Logged in!" appears, but not the alert. How can i fix it so i get the alert? I can't use header(); because i already echod things out!
I also tried multiple thing like:
echo "Test message <script> window.location.href = 'index.php';"
Same thing again, Test message was echo'd, but the script wasn't run.
I hope someone can help me!
Edit:
NOTE: All of this code is in a xml file that i get that response of and put that in a div. So the script is in a message that i get with responseXML and output the data in a div.
Question i have in 1 sentence: How can you run a javascript function in a ajax call without jquery?
I'm guessing you call this script through ajax after the page is already loaded. In this case it's not surprising the script isn't running because the browser runs the scripts as it reads them and isn't on standby for another script tag to appear.
If this is the case, you can solve this by adding some event listener or even better, call a desired function in the end of the ajax response.
Your PHP looks fine, but you might need to change the way that you collect the JavaScript.
Consider this example:
http://jsfiddle.net/0vcewvkc/1/
If you are collecting JavaScript only, you can wrap the response in a jQuery tag ($()), and then append it to your document.
$("#go").click(function() { // call the function here
// your ajax code would go here, but either way you will end up with a string of JavaScript
var response = '<script>alert("hi");</' + 'script>';
// use jQuery to append this script to your document's body, like so:
$(response).appendTo(document.body)
});
Update
To do this without jQuery, the end of your AJAX call would have this code:
var response = 'alert("hi");'; // note that we have removed the <script> tag
var s = document.createElement("script");
s.innerHTML = response;
document.getElementsByTagName('body')[0].appendChild(s);
try the following this should work
<?php
echo 'Logged in ';
?>
<script> alert("hello")</script>;
<?php
// the rest of your php code
?>
Related
I want to display a JSON object on a html page. When I enter
productArray[0][0].xyz
into the Firefox console then I get a value back.
Question:
How can I display the value which is stored in this variable on a HTML page?
I have tried this (didn't work):
<div id="test">
<script>
window.onload = function()
{
var out = productArray[0][0].xyz;
document.getElementById("test").innerHTML = out;
}
</script>
Since it's working in console in browser, I guess it's a timing problem. You're probably trying to use the value in the json before the json data is loaded and ready to use.
Assuming you're running an xhttp request or ajax call or something you'll have to run the code AFTER data is loaded. Which often means running it inside successmethod.
Maybe this post and answer helps you locate the problem? NB: This uses Ajax, so feel free to update your post with some more information so we can help you with your solution / technologies.
Ajax success function
Assuming that missing div close tag is a typo most probably the productArray is not populated by the time your code executes. Can you post a more detailed snippet ?
var out = "your value";//productArray[0][0].xyz commented to show you running code uncomment it when you use this in you code. ;
document.getElementById("test").innerHTML = out;
<div id='test'></div>
You actually forgot to close the DIV tag.
I have two php files. The first is named index.php, the second one is named data.php. I tried to get the contents from the file data.php into index.php. Initially it gave me an error using the include_once statement but I now got it to work with:
<?php $str = sprintf(include_once ("/www/index1.php"));
echo $str; ?>
Now, I want this part to refresh every minute without reloading the complete page.
I tried inserting into index.php the following:
<!-- Div refresh function -->
<script type="text/javascript">
var auto_refresh = setInterval(
(function () {
$("#data").load("/www/data.php"); //Load the content into the div
}), 60000);
</script>
<div id="data"><?php $str = sprintf(include_once ("/www/data.php"));
echo $str; ?></div>
I admit, it looks a bit wrong and guess what, it doesn't work. I this is because it tries to load data.php in de script-part and afterwards I try to include the file again in the < div>-statement. I can't get it to work.
I have looked a various examples but can't find any using the sprintf function. I must admit that my knowledge of java, ajax and or json is not great.
Hope someone can help!
Javascript is a front end script. If you want to load something via ajax, you should know its based on js. While js is based on web browser. So make sure you can access that url from browser first.
You can access /www/data.php from php, but if you want to load it in js, make sure it can be visit from web first. How can you visit your index.php?
If you can visit index.php via http://xx.com/index.php, then change $("#data").load("/www/data.php"); to $("#data").load("http://xx.com/data.php");, you will find it works.
Update: Based on your comment, try $("#data").load("data.php");
Also, you can use developer tools to debug it. If js gets error, you will see it.
You're doing something wrong.
What you need to do:
Create file with needful data (for example data.php).
Create file for loading data-file (for example loader.php). If you are using php (I see you are), you can file_get_contents for data.php and then echo it.
On page, where you want to get your data, use something like this:
JS:
function loadData() {
$("#data-container").load("loader.php", function() {
console.log("Load was performed.");
});
}
loadData(); // load first then refreshing every 1 min:
setInterval(loadData, 60000);
HTML:
<div id="data-container"></div>
So, what all of this doing here?
First, script on your page create request to loader.php;
Second, loader.php executes (I hope your server execute php, huh?) and get content of data.php (so in this context data.php can have any file name extention; data.txt, data.log, etc); then it echo that content;
Third, script on your page get echoed (by loader.php) content of data.php and paste it in your #data-container.
These steps repeat again every 1 min.
Note: If data.php in your context is not a programming code (just some data), you can create just data.html and load it directly in jQuery script. It's not need any php-loader files, etc.
I've encountered a problem when appending script to html. Here is a sample code:
<script>$('body').append("<script type=\"text\/javascript\" src=\"http:\/\/localtest\/test.php\"><\/script>");</script>
test.php source
<?php sleep(1); ?>
document.write('<div></div>');
HTML inside append function can be any html, not necessarly a script. It works unless I got HTML mentioned in example.
Result
JS code from test.php is not executed because it's blocked by browser (I'm using FF): "A call to document.write() from an asynchronously-loaded external script was ignored."
I'm not able to modify test.php content, it's loaded from external server.
Wy it is executed async? How to force sync execution?
I think you must use
$(window).ready(function() {
//put your code here
});
berfore appending.
So, complete code would be like this
<script type="text/javascript">
$(window).ready(function() {
$('body').append("<script type=\"text\/javascript\" src=\"http:\/\/localtest\/test.php\"><\/script>");
});
</script>
I want to know why I can use .load to load a very specific bit of information to a page but then when I try to read back the loaded information I am just returned null
this is the jquery I am using to load this bit of information
$(function(){
$('#code').load('stuff.html #specificstuff');
});
And this is the code I am using to repeat what is in #code
var content = document.getElementById('#code');
document.write(content);
But when this is run, I am just getting back null
document.getElementById('#code');
should be
document.getElementById('code');
That being said... I have no clue why you are using document.write in the first place.
And you need to wait for the load to finish, so it would make more sense to do:
$('#code').load('stuff.html #specificstuff', function(){
var content = document.getElementById('code').html();
document.write(content);
});
$.load() is asyncronous, so your code:
var content = document.getElementById('#code');
document.write(content);
gets executed before the actual content is loaded.
Put it in a callback function like this:
$(function(){
$('#code').load('stuff.html #specificstuff', function(){
var content = document.getElementById('code');
document.write(content);
});
});
so it gets executed after the content has done loading.
That said, document.write(content); in this case is useless, as $('#code').load() replaces the content of the element with id="code" with the content of the element #specificstuff of the file stuff.html.
I'm trying to get the lines of code below to help me write "<?php include('like.php'); ?>" on a page only when the visitor isn't using a a mobile device but it doesn't seem to be working. Any ideas on how to get it to work?
<script type="text/javascript">
<!--
if (screen.width > 699 {
document.write("<?php include('like.php'); ?>")
}
//-->
</script>
By the time JavaScript is writing to the document, it's too late - PHP has already sent everything to the browser. Your next best approach would be to make an AJAX call to fetch the content and append it to the DOM.
Assuming you're willing to use a JavaScript framework like jQuery, it's quite simple:
if (screen.width > 699) {
$.ajax({
url : '/like.php',
dataType : 'html',
success : function(data) {
$('#myContainer').html(data);
}
});
}
http://api.jquery.com/jQuery.ajax/
As others have mentioned, you can not have JavaScript include a piece of PHP-code and have it executed. As PHP is run server-side, before the page is served to the client, injecting the code like you suggest would just write <?php include('like.php'); ?> as plain text to the document.
You could however load the content of like.php through Ajax and inject it into the DOM, if a certain criteria is met.
With a library like jQuery, it is quite easy, as it provide a method .load() that let you load content into the DOM like that. You could do it something like this:
// Wait for the DOM to be ready
$(function () {
// Check the width of the screen
if (screen.width > 699) {
// Load the content and add the HTML to an element
$('#id-of-element-to-add-content-to').load('like.php');
}
});
In the above example, the content of like.php will be loaded into the HTML-element with id id-of-element-to-add-content-to, but you could use any selector you like, that match your need. If you want to replace the entire body of the page, your could do $('body').load('like.php'); instead.
More about the available jQuery selectors: http://api.jquery.com/category/selectors/
javascript executes on the browser and php executes on the server so, you need to add an if condition and then include
you could test the user agent server side and append that line if not from a mobile device