Php not writing newlines from javascript textarea - javascript

I'm trying to create a .txt file on my server when a user submits a form. However any newlines from the comment textarea is not reflected in the resulting .txt file.
Here's my code:
Javascript
function sendInfo(){
var name = document.getElementById("scenarioName").value;
var author = document.getElementById("author").value;
var email = document.getElementById("email").value;
var comments = document.getElementById("comments").value;
var urlString = "get_info.php?name="+name+"&author="+author+"&email="+email+"&comments="+comments;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (this.readyState==4 && this.status==200)
{
document.getElementById("successParagraph").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET",urlString,true);
xmlhttp.send();}
PHP
$content = $_GET['name']."\r\n".$_GET['author']."\r\n".$_GET['email']."\r\n".$_GET['comments'];
if(isset($_GET['name'])){
$fp = fopen("files/".$_GET['name'].".txt","wb");
fwrite($fp,$content);
fclose($fp);
}
So if the comment was:
"foo
bar"
Then in the textfile this would be a single line, reading "foobar"

Right, I don't know why or how, but I've worked a solution to this.
The issue seemed to be the way the php file was writing the content, it appears to ignore newlines.
So I split the comments by the newline character, and used a foreach loop to write each line into the file. As so:
$content = $_POST['name']."\r\n".$_POST['author']."\r\n".$_POST['email']."\r\n";
$comments = split("\n",$_POST['comments']);
if(isset($_POST['name'])){
$fp = fopen("fine-uploader/files/".$_POST['name'].".txt","wb");
fwrite($fp,$content);
foreach($comments as $c){
fwrite($fp,$c);
fwrite($fp,"\r\n");
}
fclose($fp);
}

Related

works in all browser except Firefox

Tried everything. It works on Chrome, Vuze and Opera. But not on FirefoxThe code for the PHP file is this:
$sql= "SELECT * FROM `tarotAntwoord` WHERE `kaart` = '".$kaart."'";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result);
$kaarter = utf8_encode ($row['kaart']);
echo $kaarter;
$test ="this is a test";
echo $test;
I use this echo, for an ajax response in a modal.
The modal outputs
this is a test
But it doesn't output the value $kaarter I got from the database.
It works in every browser except Firefox. (And it didn't work in chrome at my girlfriend).
Do I have to use an operator on the string from mysql or something? The Ajax script works, because it displays the test variable. I've tried with and without the utf8 encode.
This is the client side. No error in chrome debugging (f12)
function hedenFunction(){
var verleden = document.getElementById("tarot2").src;
// document.getElementById("verledenAntwoord").innerHTML = "hoi dit is een modal test";
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
document.getElementById("hedenAntwoord").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","tarotantwoord.php?q="+verleden,true);
xmlhttp.send();
}

I made a request to the Twitter API. How can I get the JSON response from my PHP script to my JavaScript?

I'm doing a Twitter API request that returns JSON of all tweets containing #awkward . Here's the successful response on a server: http://babbage.cs.missouri.edu/~atgvyc/php/election_tweets/index.php
But I want to be able to use that JSON in my JavaScript and parse through it with a for-loop to pull out certain information (particularly the geotags and location). I thought I could do this with AJAX and then JSON.parse, but it's not working the way I thought it would.
Any suggestions?
Here's my PHP script:
<?php
require_once('TwitterAPIExchange.php');
$settings = array(
'oauth_access_token' => "XXX",
'oauth_access_token_secret' => "XXX",
'consumer_key' => "XXX",
'consumer_secret' => "XXX"
);
$url = 'https://api.twitter.com/1.1/search/tweets.json';
$getfield = '?q=#awkward&geocode=38.949926,-92.330037,35mi&result_type=recent';
$requestMethod = 'GET';
$twitter = new TwitterAPIExchange($settings);
echo $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();
?>
Here's my HTML:
<!DOCTYPE html>
<html>
<head>
<title>Sample elections tweets</title>
<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var json = JSON.parse(xmlhttp.responseText);
//here's where i'd like to put a for-loop
}
}
xmlhttp.open("GET","index.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">Request data</button>
<body>
Ok, I think I know what you are trying to do now. There really isn't an out of the box "for each" like there is in php, which is why a lot of frameworks implement there own (jQuery's $.each()), or make prototypes. But, you may be able to do what you need with the below. You can replace all the console.log() with alert() if you want, but it gets hectic not being in Chrome's dev tools (f12 on most machines). Also, if Dale Musser is still there tell him hello! MIZ
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var json = JSON.parse(xmlhttp.responseText);
//log entire json struct to developer console for easy viewing
console.log(json);
//you can reference individual pieces of json by doing something like
//json.statuses or json.statuses[2]
var statuses = json.statuses;
for(var i=0;i<statuses.length;i++){
var curStatus = statuses[i];
//access bits directly
var tweetAuthor = curStatus.user.name;
var tweetTime = curStatus.created_at;
//iterate hashtags
var hashtags = curStatus.entities.hashtags;
for(var k=0;k<hashtags.length;k++){
console.log("Hashtag: " + hashtags[k].text);
}
//iterate all elements of tweet
for(var key in curStatus){
var attrName = key;
var attrValue = curStatus[key];
console.log("attribute name: " + attrName);
console.log("attribute key: " + attrValue);
if(attrName = "text") {
//Do something with tweet texts... like:
//document.getElementById("statuses").appendChild(attrValue);
}
}
}
}
}
xmlhttp.open("GET","index.php",true);
xmlhttp.send();
}

DOMParser.parseFromString fails with XML5619: Incorrect document syntax

I have this javascript function that gets an xml file from a web site:
function getCCDfromHV() {
var xmlhttp;
if (window.XMLHttpRequest) xmlhttp=new XMLHttpRequest(); // code for IE7+, Firefox, Chrome, Opera, Safari
else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");// code for IE6, IE5
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
var xml = xmlhttp.responseText;
document.getElementById("uploadResponse").innerHTML=xml;
xmlDom = createXmlDOM(xml);
}
}
xmlhttp.open("GET","../HVRawConnectorPHP/demo_app/GetCCDfromHV.php",true);
xmlhttp.send();
}
The xml is retrieved ok as I can see from the dump to .innerHTML. But createXmlDOM's parseFromString fails with "XML5619: Incorrect document syntax" as shown below:
function createXmlDOM(xml) {
console.log('createXmlDOM: the first 255 chars=' +xml.substring(0,255));
if (window.DOMParser){
var parser=new DOMParser();
xmlDom=parser.parseFromString(xml,"text/xml"); //fails with XML5619: Incorrect document syntax.
}
else { // Internet Explorer
xmlDom=new ActiveXObject("Microsoft.XMLDOM");
xmlDom.async=false;
xmlDom.loadXML(xml);
}
return xmlDom;
}
But if I copy the .innerHTML text and paste it into an editor and save it as a text file, load that file using FileReader, then send that text to createXmlDOM, it works fine!
So somehow the act of cut and pasting or file writing and reading does some kind of translation that makes it acceptable to parseFromString. Is there a way do do it without saving and reloading a file? It seems to be failing on the first character which is a '&' because the first char is really '<' but html changes that to &lt whereas loading it from text file doesn't.
I finally figured it out. The xml needs to be html decoded. I added the following function:
function htmlDecode(input){
var e = document.createElement('div');
e.innerHTML = input;
return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
}
Which I found from here:
http://css-tricks.com/snippets/javascript/unescape-html-in-js/

Insert Javascript Code into HTML from PHP response [duplicate]

This question already has answers here:
Can scripts be inserted with innerHTML?
(26 answers)
Closed 8 years ago.
Hi I am trying to insert a JavaScript code in my HTML document using the following AJAX-PHP code inside the function called exJS(), following is the content of the function exJS()
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax.php", false);
xmlhttp.send();
This what ajax.php is
<?php
echo '<script language="javascript">
alert("Hello World");
var testVAR = "Hello World";
</script>';
?>
Now whenever I execute this function exJS() the alert doesn't work but when I view the source code using F12 and see the contents of the div#myDiv" I see that the entire script is embedded inside the div but still the JavaScript for some reason is not getting registered.
I even tried accessing the JavaScript variable testVAR, I see the variable in the source code when I hit F12 but when I try to access that variable I get an error, that no such variable is defined.
Please note that it is simple example so there is no error and that the PHP code is echoing just fine, all the contents are returned from the PHP code, when I view the code and see what are the content of the div element the entire PHP echo content is present there but still not executing.
Also if I open the ajax.php file directly it works fine, I mean I get the alert message, but the same thing doesn't happen when I execute the function jsEx() the JavaScript code gets inserted into myDiv but nothing happens, no alert.
BTW jQuery has a specific AJAX function to get a script: http://api.jquery.com/jquery.getscript/
If you want to avoid jQuery a workaround would be to make it so you echo an iframe and from that Iframe you link to the PHP generating the actual Javascript.
E.G. a sample ajax.php
if( isset($_GET['getscript']) ){
header('Content-type: application/javascript'); #or header('Content-type: text/javascript');
echo 'alert("The script is working.")';
exit;
}
echo '<iframe src="ajax.php?getscript=1" frameborder="0"/>';
?>
try this:
tested in my WAMP (win 7, php 5.4) & works fine in IE11,Chrome,Safari,FireFox and Opera (I don't have any other ;-) )
index.html:
<head>
<title>Testing DYNAMIC JS</title>
<script type="text/javascript">
function exJS(){
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var script = document.createElement('script');
script.onload = function() {
// alert("Script loaded and ready");
};
script.setAttribute("type","text/javascript");
script.text = xmlhttp.responseText;
document.getElementsByTagName('head')[0].appendChild(script);
}
}
xmlhttp.open("GET","ajax.php", false);
xmlhttp.send();
}
</script>
</head>
<body onload="exJS();">
</body>
</html>
in ajax.php try:
<?php
echo 'alert("Hello World"); var testVAR = "Hello World";';
?>
if you want to run script from within a div:
use:
javaScript:
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var MyDiv=document.getElementById("myDiv");
var arr = MyDiv.getElementsByTagName('script');
for (var n = 0; n < arr.length; n++)
eval(arr[n].innerHTML);
}
and php:
<?php
echo '<script language="javascript">
alert("Hello World");
var testVAR = "Hello World";
</script>';
?>
hope it'll help you.

How to pass a string containing back slash and front slash from PHP query page back to JavaScript using AJAX

Here I am retrieving values of database using AJAX and PHP. I stored the path of images like photos/image1.jpg in database. While retrieving that data from database and sending them back that data is not getting printing back as it has backslashes or fronth slashes in them. So what is the process to send that data back to main pages which contain special characters while using AJAX?
My JavaScript code:
function getdata(eve)
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("grayscreen").innerHTML=xmlhttp.responseText;
} }
xmlhttp.open("GET","picdetails.php?q="+eve,true);
xmlhttp.send();
My PHP code
<?php
include 'config.php';
$query2="select * from Sampletable where sublabel= '".$_GET['q']."'";
$query=mysql_query($query2);
if(mysql_num_rows($query)>0)
{
$count=0;
while($res= mysql_fetch_array($query))
{
if($count==0)
{
$ans= "<img src=". $res['image']."\>";
echo $ans;
}
else {
echo "<img src=".$res['image']." style='display:none'/>";
}
$count=$count+1;
}
}
?>
Here $res['image'] is the path of image which is like images/image1.jpg which will be retrived from database.
Output in the screen is
"<img src="\\">"<img src="style='display:none'/">
But output is supposed to be
<img src="images/images1.jpg"/> <img src="images/images2.jpg" style='display:none'/>
The problem is the data which is retrieved from are images/images1.jpg and images/images2.jpg which is not getting echoed back as it has front slash in it.
How to print that data?
Change:
$ans= "<img src=". $res['image']."\>";
To:
$ans= '<img src="'. $res['image'] .'"/>';
This should work.
Hope it helps!

Categories

Resources