Load Text data as JSON in textarea, and prevent execute this (javascript) - 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.

Related

Insert code with JS just like echo in php

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/

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')));

Pass variables from HTML form -> ajax load()

What I am trying to do
I have a HTML form which looks like this:
[input text field]
[submit button].
I want the output results to display in only a small part of the page (don't want to refresh the entire page after the button is clicked).
What I have done so far
I am using jquery load() as follows:
<script type="text/javascript">
function searchresults(id) {
$('#myStyle').load('displaysearchresults.php?id=' + id ; ?>);
}
</script>
Results will appear in a div which is exactly what I want:
<div id='myStyle'></div>
The problem
The script above works just fine (I used a variation of it elsewhere). But I have 2 problems:
1-How to call the load() script from the form. I tried this but it doesn't work:
<form id="form" name="form" method="post" action="searchresults('1')">
2-If I am not able to call the load() script from the form, how do I pass what is into the input text field to the load() script so in the end it can be proceessed by the displaysearchresults.php file???
Thanks
Currently its not working since you have a typo:
function searchresult(id) {
/^ no s
$('#myStyle').load('displaysearchresults.php?id=' + id ; ?>);
}
Here:
action="searchresults('1')"> // this should be on the onsubmit
^
Since you're intention is to submit the form without reloading, you could do something like:
$('#form').on('submit', function(e){
e.preventDefault();
$.ajax({
url: 'displaysearchresults.php',
data: {id: 1},
type: 'POST',
success: function(response) {
$('#myStyle').html(response); // assuming the markup html is already done in PHP
}
});
});
Of course in the PHP side, just call it like a normal POST variable:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$id = $_POST['id'];
// other stuff you have to do
// echo markup stuff
exit;
}
Ok I have been able to do what I wanted to do, i.e., displaying search results in part of the page without reloading.
Actually it is not necessary to use the ajax load() function. You can do it with the script below:
<form id="form" method="POST">
<input type="text" id="textbox" name="textbox" />
<input type="submit" name="test" />
</form>
<div id="myStyle"></div>
<p>
<script src="jquery-1.10.2.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
$('#form').on('submit', function(e){
e.preventDefault(); // prevent the form from reloading
$.ajax({
url: 'displaysearchresults.php',
type: 'POST',
dataType: 'html',
data: {text:$('#textbox').val()},
success: function(response) {
$('#myStyle').html(response);
}
});
});
});
</script>
So what is this doing:
It will "read" what the user entered in the textbox,
When the user click the "submit" button, it will put that into a POST variable and send it to "displaysearchresults.php" without reloading the page,
The search results will be displayed between the "mystyle" div.
Pretty nice.
Note for beginers: do not forget to copy the jquery file to your root folder otherwise ajax just won't work.

How to execute javascript without click or onload event from php?

I have one javascript named func.js, in that there is one function called show which takes 2 arguments, what I need to do is I want to call that function from php, I can't use any click or onload event here my script looks like this
<html>
<head></head>
<script type='text/javascript' src='path/to/func.js'></script>
<body>
some div etc
<form method='post' action="" >
.....
.....
</form>
</body>
</html>
<!-- after submit of form validation is in php -->
<?php
/* here I want to call javascript, where arguments are php variables
show('argument1','argument2'); */
// I tried to echo like this
echo "<script>show('$argument1',$argument2')</script>";
?>
So what's the solution for my case ?
The code you have should work… most of the time. Unfortunately, you haven't told us why it doesn't work - is there a PHP error? Is there a JS error? — and you haven't shown us either the resulting JavaScript that PHP is outputting or the contents of the variables so we can figure it out for ourselves.
The two most likely explanations (and the only ones that occur to me at the moment) for the problem are:
There is a problem with the data in the variables
That the variables contain characters which cannot appear inside JavaScript strings or ' characters which must be escaped inside JavaScript strings.
JSON is a sufficient subset of JavaScript that the json_encode function will escape (and quote) most data so it is suitable for use in JS.
<script>
show(<?php echo json_encode($argument1); ?>, <?php echo json_encode($argument2); ?>)
</script>
There is a problem with your timing
You have an HTML comment saying "after submit of form validation is in php", but there is nothing in the code you have shared to enforce that.
You need to have something like if (isset($_POST['some_data_from_your_form'])) { ... } wrapped around the generation of the script so it only appears when the form is submitted and not when it initially loads.
If that doesn't work, then you really do need to look at what the variables are, what the generated JS is, and what your JavaScript error console says.
Script elements are not allowed after the end of the HTML element. While browsers will recover from that error, you really should move the script inside the BODY.
It could be to do with the data inside the arguments, what sort of data is it?
echo "<script>show('".str_replace("'", "\'", $argument1)."', '".str_replace("'", "\'", $argument2)."')</script>";
If you're passing information such as J'min it will cause an issue. Does the data have multiple lines? Then it needs to be filtered.
First of all, your tags are broken
<script type='text/javascript' href='path/to/func.js'</script>
You should change href to src and close the script tag, so it becomes
<script type='text/javascript' src='path/to/func.js'>
Also, javascript is client-sided which means you can't call javascript functions in PHP.
I think a good solution here would be to use an AJAX call to validate your form.
Have you tried putting the arguments outside the quotes?
echo "<script>show('".$argument1."', '".$argument2."')</script>";
echo '<script type="text/javascript">show(' . $argument1 . ',' . $argument2 . ');</script>';
above might work for you.

Can't use Ajax to Send/Retrieve variables To/From Server

Quite confused with the answers in the StackOverFlow and the whole Internet! I have some problems which seem easy but can't solve them since some days!
In my scenario (Online Booking System), I want to take the entered values in the FORM (Starting Time and Duration of the reservation) and send it to the SERVER (PHP); In the PHP function I will check if they are valid (some SQL queries and PHP functions); Then I'll retrieve the result back to the JQuery (as json encoded array);
The current snippets are as follow:
My HTML form:
<FORM ACTION="add.php" METHOD="post" ID="submitform">
<INPUT type="text" cols="50" id="starting_time" NAME="starting_time" PLACEHOLDER="Starting Time" /><br />
<INPUT type="text" id="duration" NAME="duration" PLACEHOLDER="Duration"/><br />
<P>Suggestions: <span id="txtHint"></SPAN></P>
<INPUT type="button" value='Add Reservation' id="button" />
<DIV ID="ajaxfield"></DIV>
</FORM>
My JQuery and AJAX codes:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<script>
$(function(){
$('#button').click(function(){
$('#container').append('<img src= "ajax-loader.gif" alt="Currently loading" id="loading" />');
var str = $('#submitform').serializeArray();
$.ajax({
cache: false,
url: 'availability.php',
type: 'POST',
dataType:'JSON',
data: $str,
success: function(response){
resultObj = eval (response);
alert( resultObj );
}
});
});
});
</script>
My PHP:
<?php
header('Content-Type: application/json');
$starting_time = $_POST['starting_time'];
$duration = $_POST['duration'];
availability($starting_time, $duration);
function availability($starting_time, $duration) {
THE FUNCTION STUFF
}
echo json_encode( $arr );
}
?>
Now, the problem is first of all this is not working and the script is being stuck on the loader.gif!
And second how can I manipulate the json array from PHP to do some stuff, like enabling the submit button and/or suggesting a duration which works for the user.
PS: And of course, IN the final scenario I want to check these things instantly and before user presses the submission button.
Thanks!
EDIT
Some part of my problem is solved by the notes from answers, this is the modified code (till now):
var str = $('#submitform').serialize();
$.ajax({
cache: false,
url: 'availability.php',
type: 'POST',
dataType:'JSON',
data: str,
success: function(data){
alert(JSON.stringify(data, null, "\t"))
}
});
Now, obviously I could alert the JSON returned from the PHP function; I'll just need to modify it to manipulate for my purposes.
First of all... I'll try to teach you a bit of fishing instead of just giving you a fish...
You say that your code is just stuck on the loader.gif... you've been several days stuck so I supose you had time enough to detect where your code stops, to detect if there is any error on your javascript code or if your client code execution reachs your server code.
The only info you give us saying that it's stuck on the loader is that this line of code:
$('#container').append('<img src= "ajax-loader.gif" alt="Currently loading" id="loading" />');
Has been executed.
Well... and now?
Ok, you can check things like the following:
Check if str contains what you expect it to contains.
Check if execution reachs availability.php
Check what $str contains (is the data you're trying to pass to your server)
Surely during those checkings you'll see some light through your doubts and you'll be able to post here a more detailed question.

Categories

Resources