Content sent through jQuery ajax is getting cut off - php

I am trying to send html via jQuery's $.ajax() method, and then dump the html into a new .html file, but the content is getting cut off for some reason.
I have set up a test case:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script >
$(document).ready(function(){
var contents = $('html').html();
var filename = "test/000.html";
$.ajax({
type: "POST",
url: "/file.php",
data: "content="+contents+"&fn="+filename,
dataType: "html",
success: function(msg, ts, xh){
console.log(msg);
console.log(ts);
console.log(xh);
alert("success");
},
processData: false,
error: function(X, textStatus, error){
alert("Error saving... please try again now.")
}
});
});
</script>
</head>
<body>
<div id="rteContainer" class="dev">
<div id="textEditor">
<form>
<textarea name="balh" id="balh" rows="25" cols="103"></textarea>
<input type="button" id="updateContent" value="Update Changes">
<input type="button" id="closeEditor" value="Close Without Saving">
</form>
</div>
</div>
</body>
</html>
the file.php file is:
<?php
header("Content-type:text/html;charset:UTF-8");
$content = "<html>".stripslashes(urldecode($_POST["content"]))."</html>";
$dump_file = $_POST["fn"];
$fp = fopen($dump_file, 'w');
fclose($fp);
echo $content;
?>
Why is is getting cut off? I'm guessing it's come encoding problem, but I can't figure this out.

The html string, contents, has to be url-encoded before you POST it. Javascript provides the escape() function, just for this purpose.
Pass $('html').html() to escape() and assign it to contents, like so:
var contents = escape($('html').html());

Your script is dying of embarrassment at the massive security hole in it.
Never, ever, write into a file where the filename is a form parameter without validating the filename first. Even a novice hacker could use this script to overwrite any file on your system that the webserver has access to.
In your Ajax call, pass a { } style array of key value pairs in the data parameter, don't concatenate the variables with ampersands yourself:
data: { content: contents,
fn: filename }
Oh, and you're never actually writing the content into the dumpfile, so whatever file 'fn' points at will just get truncated.
Hope that helps...

I suspect that the ampersand in the javascript is causing a problem. Try replacing it with '&' and see if that fixes it.

Related

How to load php instantly from ajax?

I am trying to directly load a page using ajax. Here are the details:
HTML:
<div id="feedback"> </div>
<script type="text/javascript" src="script.js"></script>
script.js:
$(document).ready(function() {
$.ajax({
url: 'do.php',
success: function(data){
$('#feedback').html(data);
});
});
do.php:
<?php
//Do whatever...
echo "Done!";
?>
What I am seeing is: the page first loads, and there is a delay before the "feedback" div gets written. How can I solve this?
As far as I know of course it will have that delay. Suppose your page containing <div id="feedback">[…]</div> is loaded at 0th second now:
$(document).ready(function() {
$.ajax({
url: 'do.php',
success: function(data){
$('#feedback').html(data);
});
});
Is called as apparently it’s visible when document loads. So suppose its called at 3rd second when the document is ready—you can refer to this page for details—now you will be seeing that feedback div blank for 3 seconds.
I can suggest 2 things:
You can place a loader image by default inside the div so your code will change to <div id="feedback"><img src='loader.gif'></div> (Assume you have the loader.gif in the same directory of the page). By doing this you will make the user visually understand that some processing is going on and will load data.
Instead if you can place file_get_contents() or include() so it will look something like this <div id="feedback"><?php file_get_contents('do.php');?></div> or <div id="feedback"><?php include('do.php');?></div> As far as I know file_get_contents will execute the page and then load while include will load and then execute hence in include() you have the variables in the page available whereas in file_get_contents are not available but CSS would work in both cases.
You could start loading immediately and then add the data when everything has completed.
var _data = null;
var _ready = false;
$.ajax({
url: 'do.php',
success: function(data){
_data = data;
tryAddData();
}
});
$(document).ready(function() {
_ready = true;
tryAddData();
});
function tryAddData(){
if(_ready && _data !== null){
$('#feedback').html(_data);
}
}

Passing results from PHP class to AJAX and back to the calling script

I have a class which returns a set of data from the database. The class is called by ajax and the results need to be returned back to the index.php so that I can format and display the results in a table format.
Problem: I'm unable to return the results throug ajax and back to a php variable.
Any help you can provide would be greatly appreciated.
<php
class Questions
{ public function displayQuestions()
{
return $this->questionArray;
} // contains set of data from db
}
?>
Return the dataset from the class and pass it to the $var so that I can format the data for display
index.php:
<html>
<body>
<div id="questiondev" ><?php $var[] = returned by ajax ?> </div>
<div id="questionButton">
<form method="POST" name="form_questions" action="">
<TEXTAREA NAME="saveqa" id="saveqa"></TEXTAREA>
<BUTTON class="btn_save" id ="btn_save" NAME="btn_save">Ask</BUTTON>
</form>
</div>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function() {
$('#btn_save').on('click', function() {
$.ajax({
type: "POST",
cache: false,
url: "testData.php",
dataType: "json",
success:function(info){
$('#questiondev').html(info[0]);
console.log(" reponse :"+ info);
}
});
});
$('#btn_save').trigger("click");
});
</script>
</body>
</html>
add
data:$("form").serialize(), U need to serialize the form
<div id="questionButton">
<form method="POST" name="form_questions" action="">
<TEXTAREA NAME="saveqa" id="saveqa"></TEXTAREA>
<BUTTON class="btn_save" id ="btn_save" NAME="btn_save">Ask</BUTTON>
</form>
</div>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function() {
$('#btn_save').on('click', function() {
$.ajax({
type: "POST",
cache: false,
url: "testData.php",
data:$("form").serialize(),
dataType: "json",
success:function(info){
$('#questiondev').html(info[0]);
console.log(" reponse :"+ info);
}
});
});
$('#btn_save').trigger("click");
});
</script>
</body>
</html>
It doesn't look like you're echoing your results in json format. It appears that if your query is successful, $questionArray gets set, but is not echoed. Plus you can't just echo $questionArray - it must be output in json format for the Ajax code to accept it.
Try this - after $questionArray is set:
$encodedJSON = json_encode($questionArray);
echo $encodedJSON;
you can't insert result of AJAX request into PHP variable like this. When you run php page web server willl render it, and then javascript is run by browser, which means, that you can't edit PHP variables from javascript, because PHP runs on server and JS runs on client.
Why do you want to do this? Maybe it is flaw in app design, give more information and maybe we can help you more so you won't need to do this. If you want to format data, then format them before you send them back to AJAX :)

Get value from remote php server in javascript

I have two sites, site A is just html and javascript, and site B has php. What I need is to get variables from site B in site A.
EX:
site A is like
<html>
<head>
<script>
//this script has to get the values from siteB
</script>
</head>
<body>
<div><!-- here i will do something with the data of site B --></div>
</body>
</html>
Site b is like:
<?php
var1= "something";
var2= "somethingElse";
?>
I was thinking to use JSON or Ajax but i do not understand exactly how.
$(document).ready(function() {
$.ajax({
type: "GET",
url: "filename.html",
dataType: "json",
success: function(data) {
// data will contain var1 and var2
},
error: function(data) {
alert("Problem - perhaps malformed JSON?");
}
});
});
and change your PHP file to be something like:
{
"var1" : "something",
"var2" : "somethingElse"
}
Confirmed to work.
Make sure that your file is a well-formed JSON, otherwise "success" won't be fire.
Note - I am implying usage of JQuery here. Your HTML file should include:
<script type="txt/javascript" src="jquery-1.8b1.js"></script>
File B
<?php
$array[var1] = 'Something';
$array[var2] = 'else';
echo json_encode( $array );
File A (jQuery)
$.getJSON( $( 'file.php', function( data ) {
$( 'div' ).html( data.var1 + ' ' + data.var2 );
}
Edited -- As mentioned, can't do this cross domain without doing some other measures.
Javascript cannot use ajax cross site, for security reasons. The only way to make this happen is to have but one php file on site A that can redirect.
<?php echo file_get_contents($_GET["url"]); ?>
And the javascript can call the url:
/redir.php?url=http://siteb.com/valuetoget.php
There is no way that I know of to do this with no php on the calling website.

AJAX Post to self in PHP

I feel like this is something that I should have learned by now, and I'm sure it's something small I'm missing, but I could use clarification to make sure my approach is correct.
I'm using AJAX to post data to self which is a file that contains php and html. I can write the php fine, but after a successful ajax post, how do I only return the data that is processed via php and not the remaining html? Is it better to just post to a separate script?
If you have the PHP handling the POST request in the beginning of the file, you can just do something like this:
<?php
if (isset($_POST['somevar'])) {
/* do something */
exit(0);
}
?>
exit() will stop the loading of the page at that line.
I, for one, think it's better to be utilizing a separate script to deal with dynamic AJAX requests.
You can scrape changed parts of the resulting document and insert them into the original page. This way you can also make your page work for a user with JavaScript disabled not doing anything specially.
Example:
<html><title>Unobtrusive AJAX Example</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js">
</script><script type="text/javascript">
$("form.ajax[id]").live('submit', function() {
$(this).find("input[type='submit']").attr("disabled", true);
$.ajax({
type: $(this).attr('method') || 'POST',
url: $(this).attr('action') || window.location.pathname,
data: $(this).serialize(),
context: $(this),
success: function(data) {
$(this).html(
$(data).find("#" + $(this).attr("id")).html()
);
}
});
return false;
});
</script>
</head><body>
<div><form method="post" class="ajax" id="main">
<p><?php echo date('H:i:s'); ?></p>
<p><input type="submit"></p>
</form></div>
<!-- keep the div: you got to have at least one div to make it work -->
</body></html>
It always depends on what are your needs, but if using the same script is enough for you then do it.
If you want the script not to send anything more than your answer to an XML HTTP Request, after sending the data, use an exit(); in PHP, which will make the script finish at that point.
Put to the of the script:
if($_POST['id']) {
$data = array('return'=>'returnValue');
$data = json_encode($data);
exit($data); }
Javascript:
$.ajax({
url: 'frmSelf.php',
data: $("#frmSelf").serialize(),
dataType: 'json',
type : 'post',
success : function(returnData) {
console.log(returnData);
}
});

How to receive XMLHttpRequest with PHP?

I would like to be able to read XMLHttpRequest that is sent to a PHP page. I am using prototype's Ajax.Request function, and I am sending a simple XML structure.
When trying to print the POST array on the PHP page, I don't get any output.
Any help appreciated.
EDIT: Below is my code
<html>
<head>
<SCRIPT type="text/javascript" src="prototype.js"></script>
</head>
<body>
<script type="text/javascript">
var xml='<?xml version=1.0 encoding=UTF-8?>';
xml=xml+'<notification>';
xml=xml+'heya there';
xml=xml+'</notification>';
xml=xml+'</xml>';
var myAjax = new Ajax.Request('http://localhost:8080/post2.php',{
contentType: 'text/xml',
parameters: xml,
method: 'post',
onSuccess: function(transport){ alert(transport.status); alert(transport.responseText); }
});
</script>
</body>
</html>
post2.php
Welcome <?php print_r($_POST); ?>!<br />
You will read it exactly the sme way you read normal request vars.
$_GET['varname'] and $_POST['varname']
php://input allows you to read raw POST data like
Welcome <?php print(file_get_contents('php://input')); ?>!<br />
Note: php://input is not available with enctype="multipart/form-data".
When you use "method: post" and you want to send a post body, you need the parameter postBody. So something like this might work:
var myAjax = new Ajax.Request('http://localhost:8080/post2.php',{
contentType: 'text/xml',
postBody: xml,
method: 'post',
onSuccess: function(transport){
alert(transport.status); alert(transport.responseText);
}
});
But why did you build a XML doc around your content? You can simply sent the message "heya there" with the postBody without the XML arround.
Edit: Here you'll find all the Ajax.Request options: http://www.prototypejs.org/api/ajax/options
You could use fopen() with the input:// wrapper or $HTTP_RAW_POST_DATA.

Categories