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;"
Related
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.
I'm fairly new to both JavaScript and PHP, so I hope this problem isn't as complex as it seems to me. I'm trying to send data from a form to a PHP file using XMLHttpRequest, and then display the output of the PHP as an alert. Here's the HTML and JavaScript:
<form onSubmit="password_Check()">
<input type="password" size="40" name="password" id="pass">
<input type="submit" value="Go">
</form>
<script type="text/javascript">
function password_Check() {
var url = "test.php";
var pass = $("#pass").val();
var xhr = new XMLHttpRequest();
xhr.open("GET", url+"?pass="+pass, true);
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
}
</script>
And here's the PHP:
<?php
$pass = $_GET["pass"];
echo "The password is $pass! We've done it!";
?>
I've tried all sorts of ways to do this, like $.post, $.get, $.ajax, and an xhr using POST. But I can't seem to get this to work. Now it just appends "?password=(whatever I put)" onto the end of the current url, which does nothing, but it shows it's doing something.
In your code you are missing the send part where you actually trigger the request. If you are not triggering the request then there is no point of the event listeners which listen for the state changes.
do it like
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
xhr.send();
Also in your question you are mentioning about jquery ajax, with $.get your code could be as simple as
$("#form1").on("submit",function(e){
e.preventDefault();
var url = "test.php?pass=" + $("#pass").val();
$.get(url,function(data){
//handle data here
});
});
You forgot to execute the request. xhr.send():
Also note that since you're having an XMLHTTPRequest, you need to prevent the default behavior (which is the form is going to be submitted) by using .preventDefault();
<form id="form1">
<input type="password" size="40" name="password" id="pass">
<input type="submit" value="Go">
</form>
<script type="text/javascript">
// handle the submission event
document.getElementById('form1').addEventListener('submit', function(e){
e.preventDefault(); // prevent from submitting
var url = "test.php";
var pass = document.getElementById('pass').value; // be faithful!, just use plain javascript
var xhr = new XMLHttpRequest();
var params = '?pass='+pass;
xhr.open("GET", url+params, true);
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
xhr.send(); // send it
});
</script>
If you are using jQuery then better use jQuery's ajax functions instead of xhr by yourself!
Also if you are submitting the password, better not submit it using GET request as it will be visible in the URL. Instead always use POST when handling Passwords!
Client side:
<form action="/index.php" id="myform" method="post">
<input type="password" size="40" name="password" id="pass">
<input type="submit" value="Go">
</form>
<script type="text/javascript">
$('#myform').on('submit', function() {
$.ajax({
type: $(this).attr('method'), //Taking for the form attribute
url: $(this).attr('action'),
data: $(this).serialize(), //Takes care of all input fields in the form! No need to pass one by one!
success: function(response) {
if(response == 'success') {
window.location.href = '/url-to-goto'; //Set your redirect url here
}
else {
//Handle invalid password here
alert(response);
}
}
});
return false;
});
</script>
Server side:
<?php
//If you are handling password, better to put it in the post body instead of url for security reasons
if($_SERVER['REQUEST_METHOD'] == 'POST') {
//Check password here
if(isset($_POST['password']) && $_POST['password'] == '123') {
die('success'); //successful! redirect user!
}
die('Invalid password!');
}
?>
Hope that helps you better understand!
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
I have been trying to learn ajax and from what I can see my code is correct however it always refreshes the page when it echo's the returned json string. Any help would be greatly appreciated!
<script>
// Get XML HTTP Type
function get_XmlHttp() {
var xmlHttp = null;
if(window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}else if(window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttp;
}
function ajaxSuccess () {
alert(this.responseText);
}
function ajaxrequest(oFormElement) {
//Get The Correct XMLHTTP Object
var request = new XMLHttpRequest();
request.open(oFormElement.method, oFormElement.action, true);
request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
request.send(new FormData(oFormElement));
return false;
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
alert("done");
document.getElementById('comment_form').innerHTML = request.responseText;
}
}
}
</script>
<form action="<?php echo $add_comment; ?>" method="post" enctype="multipart/form-data" id="comment_form" onsubmit="ajaxrequest(this);">
<input name="user_id" type="hidden" value="<?php echo $user_id; ?>">
<input name="user_message_id" type="hidden" value="<?php echo $user_message_id; ?>">
<textarea id="new_comment" name="new_comment" cols="100" rows="5"></textarea>
<input type="submit" value="post request"/>
</form>
You have to stop the event from happening. there is a common used function this in javascript:
e.preventDefault; // e is the event that you need to pass to your function.
or Change <input type="submit" value="post request"/>
to
<input type="button" onclick="ajaxrequest(this);" value="post request"/>
what is going to happen is your form is only going to be processed by javascript and page will mot reload due to the form submission.
Just modify this approach for yourself and it should fix your issue.
Use Jquery library http://api.jquery.com/jQuery.ajax/, but if u wanna build your own script. consult w3c documentation http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
As Pointy pointed out, you might want to prevent the default click event of the submit button from firing
submitForm( event ) {
event.preventDefault();
}
http://api.jquery.com/event.preventDefault/ <- My bad...
Just for clarification, is that your complete code?
so i tried to "parse" the form object with js and pass stuff that was supposed to be used to URL and submit a form with ajax.the code did not work.both A and B parameters were not successfully passed to server and response as i thought at the first place.
<html>
<head>
<script type="text/javascript">
function ajaxForm(form){
form = document.getElementById(form);
var elements = form.elements;
var content="";
var element;
for(i=0;i<elements.length;i++){
element = elements[i];
if(element.type=="text"){
content += encodeURIComponent(element.name)+"="+encodeURIComponent(element.value)+"&";
}
}
ajaxSubmit(content);
}
function ajaxSubmit(content){
if(content.length==0){
document.getElementById("txtinput").innerHTML="";
}
if(windows.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("txtinput").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","process.php?"+content,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form id="ajax_form">
A:<input type="text" name="A" />
<br/>
B:<input type="text" name="B" />
<input type="submit" onsubmit="ajaxForm('ajax_form')" />
</form>
<p>Elevator:<span id="txtinput" ></span><br/></p>
</body>
</html>
process.php:
<?php
$response = "This is simply an example for debugging purposes";
echo $response;
?>
AjaxForm and AjaxSubmit are never getting called, instead the form is getting submitted in the normal way. You need something like
<form id="ajax_form" onsubmit="ajaxForm('ajax_form');return false;">
try changing encodeURLComponent to ecodeURIComponent