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.
Related
First question on StackOverflow so I hope i get this right. I have a AJAX call to a JS function :
function addOptionText(str)
{
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("0").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","AddText.php?q="+str,true);
xmlhttp.send();
}
And Here is my HTML code :
<body>
<FORM NAME ="form6" onclick= "addOptionText(this.value)" >
Text Input:
<INPUT TYPE = "TEXT" VALUE placeholder ="Nume Field" NAME ="Text_Field">
<INPUT TYPE = "Submit" Name = "Edit" VALUE = "Add" >
</FORM>
<p id="0"> </p>
</body>
The php file only contains :
<html>
<body>
<?php
$name = ($_GET['q']);
echo "nume";
?>
</body>
</html>
But the function doesn't appear to be used as the paragraph doesn't change. New to php here and trying to understand how it works so I'm thinking something might've slipped me.
EDIT
I had more than one "submit" id's so that's why it didn't work. I changed the "submit" id from to and now all's working as intended.
Unfortunately, your code is all over the place.
<FORM NAME ="form6" onclick= "addOptionText(this.value)" > is wrong for a multitude of reasons.
First, we don't use onclick on the form itself but on the submit button. Secondly the value you put in the parameter doesn't in any way represent the value of the text box.
Since you want just to display the value of your textbox and not to navigate to a different page, modify your <form> tag, so that it doesn't have an action = "some page" attribute, because that way it will automatically redirect you to the page you specify and thus the AJAX request is rendered useless. Instead, modify your tag so that it looks like this:
<form name = "form6" onsubmit = "return false;">Provided that you specify your input/button type to submit: type= "submit", using the onsubmit event and setting it to return false will prevent the form from sending you over to a new page.
When using Vanilla JavaScript and not jQuery, I believe its more efficient to use IDs, so as to identify your HTML elements easier in JavaScript.
Your PHP code doesn't mean anything at all. Before doing anything else, you need to evaluate if, indeed, the q was sent over to the PHP file with the GET method. To do that, use in your php file:if (isset($_GET["q"])): // Your codeendif;
The line: echo "nume" you wrote will output "nume" regardless of what you have actually sent to your php file with the AJAX request.
In my opinion is pretty useless to still provide support for Internet Explorer 5 and 6. Not many people use it, unless for whatever reason they are mentally bound to it.
Analytically, how your files should be:
HTML:
<body>
<form name = "form6" onsubmit = "return false;">
Text Input:
<input type = "TEXT" placeholder ="Nume Field" id = "textfield" name = "Text_Field"/>
<input id = "submit" type= "submit" Name = "Edit" value= "Add"/>
</form>
<p id = "0"> </p>
<script src = "YOUR JAVASCRIPT FILE" type = "text/javascript"></script>
</body>
JavaScript:
var textfield = document.getElementById("textfield");
var submit = document.getElementById("submit");
submit.onclick = function() {
'use strict';
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("0").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET", "AddText.php?q=" + textfield.value, true);
xmlhttp.send();
};
PHP:
<?php
if (isset($_GET["q"])):
echo ($_GET["q"]);
endif;
?>
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>
First off, here's my code:
HTML ("formdata-index-test.html"):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Test page</title>
</head>
<body>
<form id="the-form" method="post" action="formdata-validation-test.php">
<input type="text" id="the-text">
<input type="submit" value="Upload">
</form>
<script src="formdata-fields-control-test.js" type="text/javascript"></script>
</body>
</html>
JS ("formdata-fields-control-test.js"):
var form = document.getElementById("the-form");
form.onsubmit = function() {
var q = document.getElementById("the-text").value;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if ((xhr.readyState == 4) && (xhr.status == 200)) {
alert(xhr.responseText);
}
}
xhr.open("POST", "formdata-validation-test.php", false);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send("q="+q);
}
PHP ("formdata-validation-test.php"):
<?php
$example = $_POST['q'];
echo $example;
if (empty($example)) {
echo "Empty";
}
?>
Now, at the beginning, I wasn't getting anything as response, but after a few tries and changes in my code, I'm being able to receive that alert in the JS file. The weird thing is that, even receiving the alert, I'm still getting the "Empty" echo when the PHP page is loaded after the form submission. Does anyone know why is it happening? My final goal is just to send the text from the HTML file to the PHP file, and then to database (that is, the "responseText" is not really necessary, and it's here just with test purposes), but apparently, PHP is not really receiving what JS sends, while JS receives what PHP sends. Does it make any sense?
The submit button is clicked and a submit event fires on the form.
The JavaScript is running. It is making an HTTP request to the PHP script with the data in it. Since you have forced it to be a synchronous request (don't do that, it locks up the event loop), the browser waits for the response before continuing. The JS is then processing the response, and alerting the value.
Then the form is submitted. It doesn't have a control with name="q", so for the second request to the PHP script, empty($example) will always be true.
If you want to stop the form being submitted then call preventDefault on the event object.
form.onsubmit = function(event) {
event.preventDefault();
try this :
1) in formdata-fields-control-test.js , make your script as a function :
function testFunction() {
var q = document.getElementById("the-text").value;
var params = "q="+q;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if ((xhr.readyState == 4) && (xhr.status == 200)) {
alert(xhr.responseText);
}
}
xhr.open("POST", "formdata-validation-test.php", false);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send(params);
};
2) in formdata-index-test.html , set action to empty and call the javascript function onsubmit :
<form id="the-form" onsubmit="return testFunction()" method="post" action="">
<input type="text" id="the-text">
<input type="submit" value="Upload">
</form>
the issue i think was with the form having an action and a onsubmit function together.
Hello I have encountered a problem while coding in Javascript and PHP (Ajax non jquery). I am trying to upload a file over Ajax, and handle it in PHP.
This is my code:
index.html
<html>
<head>
<title>PHP AJAX Upload</title>
<script type="text/javascript">
function upload() {
// 1. Create XHR instance - Start
var dat= "bla";
document.getElementById("div2").innerHTML = "working";
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
else {
throw new Error("Ajax is not supported by this browser");
}
var rad = document.getElementById('fajl');
var filee = rad.files[0];
var formData = new FormData();
formData.append('rad',filee)
formData.append('var',dat)
xhr.open('POST', 'upload.php');
xhr.send(formData);
xhr.onload = function () {
if (xhr.readyState === 4 && xhr.status == 200) {
document.getElementById("div2").innerHTML = xhr.responseText;
//alert(xhr.readyState);
//alert(xhr.status);
}
}
}
</script>
</head>
<body>
<form id="uploadForm" enctype="multipart/form-data">
<label>Upload File:</label><br/>
<input name="rad" id="fajl" type="file" class="inputFile" />
<input type="submit" value="Submit" class="btnSubmit" onclick="upload()" />
<div id="div2">
</div>
</form>
</body>
</html>
upload.php
<?php
if(is_array($_FILES)) {
if(is_uploaded_file($_FILES['rad']['tmp_name'])) {
$sourcePath = $_FILES['rad']['tmp_name'];
$targetPath = "images/".$_FILES['rad']['name'];
if(move_uploaded_file($sourcePath,$targetPath)) {
echo ("uspjeh<br>");
}}
}
$podatak=$_POST['var'];
echo "$podatak"
?>
Problem is that I dont see PHP script response in my div2 element. Ajax behaves wierd and it puzzles me. I have put JavaScript alert command under xhr.readyState condition (now commented). When I do that then I see the output, but when I close alert dialog, the browser automaticly reloads page and makes the URL like i'm using GET method (i'm using POST) and then server output dissapears. (rad in ?rad=... is the name of my input element)
When I'm not using alert command then I don't see output at all, because page redirects really fast. What am I misiing?
It's because you are using a submit button and that's submitting the form. By default form methods are GET requests. Change to just a button instead:
<input type="button" value="Submit" class="btnSubmit" onclick="upload()" />
The default form action (submitting) is being carried out.
To stop this add return false to your click handler:
onclick="upload(); return false;"
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