Javascript fetching text from textarea & posting to php page - javascript

I've got a textarea on a page used to submit posts, like in a chat or forum. To show how the posts are formatted I'm trying to get a preview function to work, using javascript. Once the preview-link is clicked, the script should fetch the text from the textarea (id = inputinsertcommentary) and post it to a popup window (postvorschau.php), where it's previewed using the $_POST variable.
Here's my script:
function postvorschau() {
var url = 'www.page.com/folder/postvorschau.php';
var form = document.createElement('form');
form.action = url;
form.method = 'POST';
form.setAttribute("target", "_blank");
var text = document.getElementById('inputinsertcommentary').value;
var postname ='posting';
var input = document.createElement('input');
input.type = 'hidden';
input.name = postname;
input.value = text;
form.appendChild(input);
form.submit();
}
And here's the link where the function is called:
<a href='javascript: postvorschau();'>Postvorschau</a>
As far as I can see from my browser log (firefox), the function is called and doesn't produce any errors. However, there's no popup window opened - I suppose something in my syntax is wrong, but from looking at similar examples I can't really figure out what. Any help is greatly appreciated!

A basic example of using ajax to send the contents from the textarea to the backend script. The php script presumably formats the data and then prints it out.
<?php
/* postvorschau.php: format data and send back to callback */
if( !empty( $_POST ) ) {
/* you would send back formatted data probably - whatever that might be */
exit( json_encode( $_POST, true ) );
}
?>
<!doctype html>
<html>
<head>
<meta charset='utf-8'>
<title>html preview</title>
</head>
<body>
<form>
<textarea name='inputinsertcommentary' cols=80 rows=10 style='resize:none' placeholder='Enter comments / data here and use preview button / link'></textarea>
<a href='#'>Preview</a>
</form>
<script>
var olnk=document.querySelectorAll('form a')[0];
olnk.onclick=preview;
function preview(e){
/* get textarea ~ you could use ids instead of course */
var oTxt=e.target.parentNode.querySelectorAll('textarea')[0];
/* create request object */
var xhr = new XMLHttpRequest();
xhr.onreadystatechange=function(){
/* invoke callback with response data */
if( xhr.readyState==4 && xhr.status==200 ) cbpreview.call( this, xhr.response );
};
xhr.open( 'POST', '/folder/postvorschau.php' );
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send( 'data='+oTxt.value );
}
function cbpreview(r){
alert( r );/* use this callback to generate the "popup" using "r" as the data, either formatted or raw */
}
</script>
</body>
</html>

Related

I am Having Problems Updating My MySQL table value From my Modal form Sing PHP

I created a modal form (that pops up upon a link click, i.e trigger()). This is the HTML code:
<div class="modalbg">
<div class="modalPopup">
<form action="samepage.php" class="formContainer" method="post">
<h2>Change Desk Number</h2>
<label for="studentid">
<strong></strong>
</label>
<input type="password" placeholder="Your KEY" name="studentid" required/>
<label id="status" style="color:red;"></label>
<button type="submit" class="btn" onclick="return verify()">Upgrade</button>
<button type="button" class="btn cancel" onclick="closeForm()">Close</button>
</form>
</div>
</div>
The JavaScript that controls this modal is:
function trigger(){
document.getElementById("modalPopup").style.display = "block";
}
function closeForm() {
document.getElementById("modalPopup").style.display = "none";
}
function verify() {
var studentid = document.getElementById("studentid").value;
if (studentid != dbstudentid || !studentid){
document.getElementById("status").innerHTML="Invalid Student ID!";
function trigger(event) { event.preventDefault(); }
return false;
}
else{
document.getElementById("modalPopup").submit();
}
}
Everything works at this point (i.e it pops up whenever I click the link and whenever I knowingly try to enter a wrong studentid, it returns the "Invalid student ID" on the "status" label. (Note: I had already saved the session's student ID in the variable dbstudentid using:
var dbstudentid = <?php echo json_encode($dbstudenid);?>;
My problem however comes from when I try to execute the PHP on the same page.
Whenever I insert the PHP code into the modalbg div or modalPopup div inside it, the entire modal refuses to pop, let alone submit.
This is the PHP code I used (it should be noted that at the beginning of the page, I had already used include(configure-db.php) and session_start() ) :
<?php
if(isset($_POST['studentid'])){
$studentid = $_POST['studentid'];
$desk = 1;
$deskstatus ="";
$select = "UPDATE users SET deskNo = '$desk' WHERE name='$SESSION';
}
if (mysqli_query($MyConn, $select)) {
$deskstatus = "Desk changed successfully!";
} else {
$deskstatus = "Error";
} return $deskstatus;
?>
I have tried everything, the modal just refuses to come every time, let alone successfully make the Desk Update on my Database. to make things worse, whenever I refresh the page, the modal which I set to display:none; by default on CSS suddenly starts showing. But whenever I remove the PHP code, it returns to normal.
Do I need to make the action execute in a separate page? If yes, please how?
Else, how please?
I world highly suggest you think about using AJAX to handle this probolem.
let's clear up things.
you can write var dbstudentid = '<?= $dbstudenid ?>'; instead of var dbstudentid = <?php echo json_encode($dbstudenid);?>; this will give you freedom of JS native datatype.
you need to send this form request through ajax and recive output there.
Change the php code else part to like this
else { $deskstatus = "Error: " . mysqli_error($MyConn); }
Now when there is a actual problem on code you will know what was the problem. and it will not break you interface.
4. Create seperate file that handle this form request.
5. Here is code snippet of plaing JS AJAX implementation
let post = JSON.stringify(postObj)
const url = "https://jsonplaceholder.typicode.com/posts"
let xhr = new XMLHttpRequest()
xhr.open('POST', url, true)
xhr.setRequestHeader('Content-type', 'application/json; charset=UTF-8')
xhr.send(post);
xhr.onload = function () {
if(xhr.status === 201) {
console.log("Post successfully created!");
let AlertDiv = document.querySelector('#alert');
AlertDiv.innerHTML = xhr.response;
}
}

Safari not sending AJAX form data

A strange problem has started on a page where the code hasn't been changed. I have stripped things back and have now isolated the issue, but I can't make sense of it.
On this form if I only input the text field, Safari wont send the form (although no errors occur). It does send in Firefox when only the text field is entered.
Safari will send the form if the image field has a file or if I remove the image filed altogether. So for some reason the lack of data in the image field is causing the form to not send in Safari.
It seems to matter that the text field is created by Javascript, if I just make the page with a regular text input to start with the problem doesn't occur.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" language="javascript">
function sendForm(){
var formElement = document.querySelector("#upload");
var formData = new FormData(formElement);
var request = new XMLHttpRequest();
request.open("POST", "test.php");
request.send(formData);
}
</script>
</head>
<body>
<form name="upload" id="upload" >
<h2>Image</h2>
<input name="image" type="file" />
<p onclick="sendForm()" />SEND</p>
</form>
<script>
for (var f = 0; f < document.forms.length; f++) {
new_input = document.createElement('input');
new_input.type = 'hidden';
new_input.name = 'title';
new_input.value = 'test';
document.forms[f].appendChild(new_input);
}
</script>
</body>
</html>
I am tracking the data sent with:
<?php
$title = $_REQUEST['title'];
$file = 'output.txt';
$current = file_get_contents($file);
file_put_contents($file, $title."\n");
?>
Additionally if request.send(formData); is changed to request.send("test"); then "test" will be sent in all cases, so it appears Safari is having an issue with the FormData object.
I have aso tested this using the fetch() API and the same thing happens.

Combination JQuery and PHP

I'm making a project with the slides of text.
I have in the page a main div that contain the text of each slide.
I saved the content in a database.
I want do this operation:
When I click the arrow for view the next slide, PHP catch from database the content and save it in a variable.
Then with JQuery, I replace the maindiv's content with variable.
It is possible? If not, How can I do it?
Use a ajax request to simulate a post request, and parse the information with php. You will end up with someting like this:
<?php
if( isset( $_POST["slide"] ) {
// Database stuff
// Echo back
echo "Information that you need to get in jQuery";
}
?>
<script>
$("button.next_slide").click(function(){
var ajax;
if (window.XMLHttpRequest) {
ajax = new XMLHttpRequest();
} else {
ajax = new ActiveXObject("Microsoft.XMLHTTP");
}
ajax.onreadystatechange = function() {
if (ajax.readyState==4 && ajax.status==200) {
document.getElementById("some_element").innerHTML = ajax.responseText;
}
}
ajax.open("POST","this_page.php?slide=1&foo=bar&bar=foo",true);
ajax.send();
});
</script>
<button class="next_slide">Next slide</button>
<div id="some_element"></div>
Note: This could be done without jQuery, or with jQuery's $.ajax method. Read more here: http://api.jquery.com/jquery.ajax/
In my understanding, you want to load some data when user click on a particular button and then load it into a div we can achieve it via jQuery ajax and PHP.
HTML
<div class="main_div">
<ul id="list"><!-- Our content will load here --></ul>
Next
</div>
jQuery
jQuery(document).ready(function($){
$('.call_ajax').on('click', function(e){
e.preventDefault();
$.post('ajax.php', { get_slide: true }, function(response){
// We are telling jQuery to parse response as json because in ajax.php we have used json_encode function.
var data = jQuery.parseJSON(response);
$("#list").append('<li>' + data['slide'] + '</li>');
});
})
})
PHP ajax.php
if(isset($_POST['get_slide'])){
//Get slide from db and output it as json, but currently for example purpose we assume that we have a array.
$data['slide'] = 'Your slide text';
echo json_encode($data); die(); // We have used die because we don't won't our script to run any more.
}
I've not tested it, but it will work.

Ajax: bulk url list in textarea sending requests one after another and display answers repetitive

I want to input a bulk list of urls in a textarea (each line contains 1 url). After submitting the form, the ajax should get one url, doing php stuff with this url, sending the result back, take another url, do the same and repeat. While the hole thing is working there should be displayed a loading circle ("ajax-loader.gif") and the results should be displayed one after another, like:
[Submit] -> loading -> result 1st-url -> loading -> add result 2nd-url one line under result 1st-url -> loading -> add result 3rd-url one line under result 2nd-url -> ...
I'm doing this whole ajax/js stuff since yesterday - so i'm not very experienced in that way - the php is working with no errors. my main problem is the js/ajax request; how to recieve the result, doing stuff with it,.. This is what i've written so far:
js/ajax (w.o. jquery cause i dont like the notation):
function send (){
var url = document.getElementById('comment').value.split('\n'); //split input from textarea in array
document.getElementById("load").innerHTML='<img src="ajax-loader.gif" />';
for(var i=0;i<url.length;i++) {
http = new XMLHttpRequest();
http.open("POST", "check.php", true);
http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
http.send("name=" + url[i]);
http.onreadystatechange=function() {
if (http.readyState == 4) {
document.getElementById("result").innerHTML=http.responseText;
}
}
}
}
html:
<form method="post" action="" name="Formular">
<textarea cols="100" rows="10" id="comment"></textarea><br/>
<input type="button" value="Absenden" onClick="send()">
</form>
<div id="load"></div>
<div id="result"></div>
php:
<?php
$url = $_POST['name']; //get url
..do funky stuff..
echo $result; //result is a simple string if an element on that url exists
?>
What you need to do is make your ajax function recursive, eg on completion, it calls its self, rather than using a loop.
Here is a full example, contained in a single php file, called ajax-example.php:
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
sleep(1);
echo $_POST['name'];
die();
}
?>
<html>
<head></head>
<body>
<div id="load">doin nothin</div>
<textarea name="n" id="comment" cols="30" rows="10"></textarea>
<br/>
<button onclick="send()">send</button>
<div id="result"></div>
<script type="application/javascript">
function send (){
var url = document.getElementById('comment').value.split('\n'); //split input from textarea in array
var current = 0;
var total = url.length;
document.getElementById("load").innerHTML='loading';//'<img src="ajax-loader.gif" />';
//call ajax for 1st time
ajax();
function ajax(){
//if there are urls left to process
if(current < total){
var http = new XMLHttpRequest();
http.open("POST", "/ajax-example.php", true);
http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
http.send("name=" + url[current]);
//increment current marker
current++;
http.onreadystatechange=function() {
if (http.readyState == 4) {
var res = document.getElementById("result");
res.innerHTML=res.innerHTML + http.responseText +"</br>";
//recursive call
ajax();
}
}
}else{
//we are done, remove the loading img
document.getElementById("load").innerHTML='finished';
}
}
}
</script>
</body>
</html>
Just to add, dont discount jQuery just because you dont like the syntax, it can make your life a lot easier for non trivial dom manipulation

Error in extraction of tweets from twitter

<!doctype html>
<html>
<head>
<title>Twitter</title>
<meta charset="utf-8">
<script>
window.onload = function () {
// set up the click handler for the form button
var button = document.getElementById("submit");
button.onclick = getTweets;
}
// when you click "Get Tweets" we call this function
function getTweets() {
// set up a new XHR request
var xhr = new XMLHttpRequest();
// we're calling search.php and passing in a query string
var url = "search.php?query=";
var query = document.getElementById("query").value;
if (!query) {
query = "html5";
}
// we encode the query to handle any special characters properly
url += encodeURIComponent(query);
// this is the function that is called when the XHR request
// to our search.php script is handled, and a response sent back
xhr.onload = function () {
// if everything went okay, then send the response data
// to the displayTweets() function
if (xhr.status == 200) {
displayTweets(xhr.responseText);
} else {
var errorDiv = document.getElementById("error");
errorDiv.innerHTML = "Error getting tweets: " + xhr.status;
}
};
// make the request!
xhr.open("GET", url);
xhr.send(null);
}
function displayTweets(tweets) {
// tweets is a big long string, so we need to parse it
// into JSON first
tweets = JSON.parse(tweets);
var ul = document.querySelector("ul");
// clear existing tweets from list
while (ul.hasChildNodes()) {
ul.removeChild(ul.lastChild);
}
// add new tweets
for (var i = 0; i < tweets.length; i++) {
var li = document.createElement("li");
li.innerHTML = tweets[i].tweet;
ul.appendChild(li);
}
}
</script>
</head>
<body>
<form>
Query:
<input type="text" id="query">
<input type="button" id="submit" value="Get Tweets">
</form>
<div id="error"></div>
<ul></ul>
</body>
</html>
In the above code when I enter some text in the textbox and click on "Get Tweets" button it gives an error as Error getting tweets: 0. The search.php when executed independently without embedding in html and javascript gives accurate and required results.Can you please check the html and js code and suggest any changes in code??
Seems that the issue is CROSS-DOMAIN Ajax issue. When you execute the search.php independently, then there is no X-domain issue. But when you are embedding the code in some html, check if the html is part of the same domain or not. Also, if you are trying to run the html file from file:/// it will not work.

Categories