Insert code with JS just like echo in php - javascript

I want to get some code snippets from a PHP server to be "injected" in HTML. Basically when I open page.php I get some text like "_off".
The injection works with this code, however I can't use php in this html since it is local.
<img src="images/test
<?php
{ echo "_off"; }
?>
.jpg">
JavaScript seems to be the logical step. But if I just enter this at the position where I want the text of course it doesn't work:
<script type="text/javascript"> $.get( "page.php", function( data ) { document.write(data); } ); </script>
Any ideas?

You need to use $('#someElement').html(data) or $('#someElement').text(data) if you want to write the data to a specific place on the page. You should avoid using document.write
Here is a fiddle to demonstrate: https://jsfiddle.net/yd9mx4d3/

Related

Is it possible to change HTML within PHP code?

What is the easiest way to run Javascript code inside PHP, preferably without using external libraries? Specifically, I need the innerHTML of a div to change depending on some calculations performed using the user's form inputs that were captured earlier with $_POST in a separate form. How can I get the following JS code to run inside the following PHP code? (My most basic attempt was using echo command, but it's throwing up errors)
HTML:
<div id="output">
</div><!--#output -->
PHP (desired JS included):
if (count($valid_locations)<$num_of_locations){
echo '<script>const output = document.querySelector("#output");</script>;';
echo '<script>output.innerHTML = "<div class="alert-danger"> Trip unable to be created. Please adjust the budget/number of travelers/duration etc.</div>;";</script>';
}else{
createTrip($trips);
}
Right now, the IF condition is True and the code does run, but it echos ";" for some reason. I have verified that the condition is met and it runs by adding in a simple echo "this runs";, which did appear upon refresh. I just don't understand why it's outputting to the default echo space and the script isnt running to change the innerHTML of the output div. Is this even possible to do with PHP? If so, what's the best way? (doesn't need to be secure, won't be used publicly). I've heard of a few things such as ajax but it seems so complicated. Any explanations on stuff like that specific to this scenario would be greatly appreciated.
Following up on the comments, you don't need JS to achieve what you want. You could just use PHP
<?php
$output = null;
if (!empty($_POST)) {
//...
//... do stuff
//...
if (count($valid_locations)<$num_of_locations){
$output = 'Error occured - bla bla bla';
}
}
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php if (isset($output)) {?>
<div id="output"><?= $output; ?></div>
<?php } ?>
</body>
</html>

Trouble posting variable from JS to PHP

I am trying to send a JS a variable to a php file. It is not happening. And there are many questions answered out there on similar situation. I probably am making some similar mistake. Though, I am not able make out what it is.
The Codes are as follows;
main.php
<script type="text/javascript"> var socialurl= "<?php echo $url;?>";</script>
JS
jQuery(function(){
alert('socialurl');
$("#smshare").click(function(){
$("#smp").slideToggle("fast");
$.post("social-media-share.php", {socialurl: socialurl });
$("#smp").load("social-media-share.php");
});
});
social-media-share.php;
<?php
$socialurl=$_POST['socialurl']
echo $socialurl."<br>";
include('conn.php');
$socialurl = $conn->real_escape_string(trim($_POST['socialurl']));
?>
<img src='images/share.png' width="30" height="30" alt='WhatsApp Share'>
The file social-media-share.php is called into the main.php with JS. Prior to which the JS variable socialurl is defined in the main.php
The variable value pops up in alert in the JS but it is not getting posted to social-media-share.php
I am sure I must be making some silly mistake. But for the life of me am not able to find out what.
Any help will be greatly appreciated.
I think the problem is you're posting to the page, but then loading it again via a GET request and so you're not loading the results of the post request itself.So unless the GET on social-media-share.php is displaying a database result I'm not sure you're actually loading what you want.
jQuery(function(){
alert('socialurl');
$("#smshare").click(function(){
$("#smp").slideToggle("fast");
$.post("social-media-share.php", {socialurl: socialurl });
$("#smp").load("social-media-share.php");
});
});
This bottom line is doing the wrong thing. $("#smp").load("social-media-share.php");
you actually want a callback function in you .post that loads the response from that
http://api.jquery.com/jQuery.post/
$.post( "social-media-share.php", {socialurl: socialurl })
.done(function( data ) {
//you might need to do some other stuff to data here
$("#smp").html(data);
});
Alternatively you might have an error in your social-media-share.php script so you could try doing a var_dump($_POST); to see what variables are actually being posted

Call javascript function within a PHP form

The architecture I use to load contents onto a common area on the web page is as below
I have a java script function within the form as shown below called javaScriptFunc which never gets invoked.
Is it possible to invoke a java script function within a form?
Please do let me know if more clarity is needed. I'll try to clarify. I'm stuck with this for a while now. I'd appreciate any help please
I think you are missing some PHP tags if I understand what you are trying to do correctly. Try this:
<form method="post" action="" id='somdId'>
<?php
require_once 'some_php_file.php';
if (isLoggedIn()) {
// Some PHP code here
?>
<script>
javaScriptFunc(<?php echo formatJson(someArgs); ?>);
</script>
<?php
}
?>
Not very clear what you want. You need to echo the script like this
echo ("<script type='text/javascript'>javaScriptFunc(" . formatJson(someArgs) . ");</script>");
provided you have already defined the function javaScriptFunc somewhere else in script.
For some reason, I the JS function doesn't seem to fire from within a form. I've worked around by re-writing the load logic to load the whole PHP page instead of a form. just a different way of doing things.

Insert javascript string into HTML with PHP in WP

I need to create some widget for WP and in widget's setting will be textarea, where user can insert some JS code. And then my widget must inject this code to WP's footer.php with this function:
add_action( 'wp_footer', 'inject_js', 10 );
In my inject_js I have:
function inject_js () {
echo esc_attr( get_option('js_code') );
}
Everything is working good and the code inserts into HTML, but I faced one problem. In my HTML I get something like this:
<!-- BEGIN JS widget -->
<script type="text/javascript">
var __cp = {
id: "J4FGckYPdasda21OaTnqo6s7kMgeGXdTBAb6SgXMD-A"
};
As I understand I got the code from user's textarea in string type and I must do something with the quotes and other symbols, but I really don't know how to solve this issue, because I am new to PHP.
What PHP function must I use or it's possible to do with some WP functions?
I tried:
echo htmlspecialchars(esc_attr( get_option('js_code') ));
and
echo addslashes(esc_attr( get_option('js_code') ));
But nothing helped.
You are seeing the effect of esc_attr - the function is html encoding (amoungst other things) the string.
It is designed for untrusted user input. As your code is specifically designed to accept javascript from a trusted source (the site owner), dont use it.
echo get_option('js_code');
wrap your code in this :- like this:
html_entity_decode(esc_attr( get_option('js_code')));

Load Text data as JSON in textarea, and prevent execute this (javascript)

I have a stupid problem load data from DB into textarea using Jquery-ajax.
The problem is, when i try to load the data (send by a echo json_encode() in PHP from DB in TEXT utf8_general_ci) into a textarea i cant use htmlentities (because in textarea show characters not the text) if i put javascript in the database, and then, load into textarea, this load correct the chars, but.. execute the code and show me the result of javascript.
Example:
<?php
if (!empty($_GET['json'])) {
$array = array(
'text1' => 'hello world!',
'text2' => '<script>alert("bu")</script>',
);
echo json_encode($array); die();
}
?>
<script type="text/javascript" src="jquery-1.6.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url: "?json=true",
type: "POST",
dataType: "json",
success: function(data){
$('textarea[name=area]').val(data.text2);
}
});
});
</script>
<textarea name="area" cols="80" rows="6"></textarea>
I try with .val(), .html(), data.text2.tostring() (fail), and nothing work, always execute the code.. I think its a simple fail, but dont find a solution if i need to show the correct code in textarea and no special chars.. Any idea?
The TEXTAREA doesn't have value. It has the data between the tags. Try using:
$('textarea[name=area]').html(data.text2);
This code works for me:
http://jsfiddle.net/8WXyk/1/
anyway I don't know if it's a feasible solution for your needs.
Basically the code:
Receives an escaped content from server
Unescapes and and inject it into textarea (you should use .html() as pointed out by Asken)
This code uses the unescape function from the "unescape" plugin, which can be found here:
http://plugins.jquery.com/files/jquery.unescape.js_0.txt
Try:
$('textarea[name=area]').val(data.text2);
instead of HTML. This will blank out the text area and allow you to insert the new value.

Categories

Resources