I have the following code:
function add_post() {
if (document.getElementById("blogTitle").value.trim() == "") {
alert("Please Insert Blog Title");
return;
}
if(CKEDITOR.instances.editor1.getData() == "") {
alert("Please Insert Blog Details");
return;
}
var data = new FormData(document.getElementById("file_add"));
var xhr = new XMLHttpRequest();
var de=CKEDITOR.instances.editor1.getData();
xhr.open("POST", "upload.php", false)
xhr.send(data + "&de=" + de);
if (xhr.status == 200) {
alert(xhr.responseText);
if(xhr.responseText == 2) {
document.getElementById("res").innerHTML="Please Upload The File";
}
if(xhr.responseText == 1) {
document.getElementById("res").innerHTML="Blog Created";
document.getElementById("blogTitle").value="";
document.getElementById("editor1").value="";
}
}
else {
output.innerHTML += "Error " + xhr.status + " occurred uploading your file.<br />";
}
}
I am using CKEDITOR in textarea to get formated text. I use CKEDITOR.instances.editor1.getData() to get the textarea value. On other hand I have used FormData because I want to upload form and file using ajax. I tried to send data but the data couldn't be sent. I have stored textarea value in de variable.
Your form data object is not a string. You can't just concatenate more data into it with +.
Replace:
xhr.send(data+"&de="+de);
with
data.append("de", de);
xhr.send(data);
Related
I'm trying to make basic HTML Server connection, therfore I want to call and JS function which should call an PHP file just schoing "hello world". Everything is working so far but the response I get seems to be null.
I've read through various tutorials but I did not find an answer, hope someone can help me.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == XMLHttpRequest.DONE && xhttp.status==200 && xhttp.responseText!=null) {
alert("Responestext: " + xhttp.responseText + " ENDE");
}else if(xhttp.status==403){
alert("forbidden");
}else if(xhttp.status==404){
alert("not found");
}else if(xhttp.responseText==null) {
alert("response text = null");
}else{
alert("Error");
}
};
xhttp.open("GET", "http://URL/fahrgemeinschaft/login.php", true);
xhttp.send(null);
I expect the output to be "Responsetext: hello world ENDE" but all I get is "Error".
I get two alert boxes saying "Error" as well.
The problem is your onreadystatechange handler is called for every ready state change event, not just when it is done.
You should skip the events that are not done:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState != XMLHttpRequest.DONE) {
return;
}
if (xhttp.status==200 && xhttp.responseText!=null) {
alert("Responestext: " + xhttp.responseText + " ENDE");
}else if(xhttp.status==403){
alert("forbidden");
}else if(xhttp.status==404){
alert("not found");
}else if(xhttp.responseText==null) {
alert("response text = null");
}else{
alert("Error");
}
};
xhttp.open("GET", "http://messenger.hopto.org:8080/fahrgemeinschaft/login.php", true);
xhttp.send(null);
Or to make it easier on yourself, so long as you don't need to support obsolete browsers, just use the onload event.
var xhttp = new XMLHttpRequest();
xhttp.onload = function() {
if (xhttp.status==200 && xhttp.responseText!=null) {
alert("Responestext: " + xhttp.responseText + " ENDE");
}else if(xhttp.status==403){
alert("forbidden");
}else if(xhttp.status==404){
alert("not found");
}else if(xhttp.responseText==null) {
alert("response text = null");
}else{
alert("Error");
}
};
xhttp.open("GET", "http://messenger.hopto.org:8080/fahrgemeinschaft/login.php", true);
xhttp.send(null);
below is my code fo ajax which sends a string data via post method, the request is successful but I get an empty response. I had checked the readystate and status both are proper and the php file is in the same directory.
function getData(str)
{
if (str == "")
{
} else
{
if (window.XMLHttpRequest)
{
var dat = new XMLHttpRequest();
} else
{
dat = new ActiveXObject("Microsoft.XMLHTTP");
}
dat.open("POST","userdat.php",true);
dat.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
dat.onreadystatechange = function ()
{
if (dat.readyState == 4 && dat.status == 200)
{
alert(dat.responseText);
$('#dataReT').text(dat.responseText);
}
}
dat.send("userid=" + str);
}
}
content of my php file:
<?php
$id=$_REQUEST['userid'];
echo $id;
?>
there is no userid in $_REQUEST. Try to add this to your php file:
if(array_key_exists('userid',$_REQUEST)) {
echo $_REQUEST['userid'];
} else {
echo 'no userid.';
}
You may send userid value from your javascript file
I made a simple chat. It's working properly, but not behaving as expected. When a user submits a message, the user's name, time and message are supposed to display.
It so happens that the username and response appear first and the time seems to be inserting itself after a slight delay (that's the lag). I can't figure out why, especially since the response is (or at least seems to be) sent as a whole and nothing is being inserting once the response is sent from the server...
Here's the link to the chat. You can input dummy username and dummy messages.
And here are the important pieces of code:
PHP
while ($row = $result->fetch_assoc()) {
$time = date('g:ia', $row['time']);
echo "<p class=\"message\"><i>{$row['username']}</i> ($time): {$row['content']}</p>";
}
JavaScript
ajax.onreadystatechange = function () {
if (ajax.status === 200 && ajax.readyState === 4) {
document.getElementById('messagesArea').innerHTML = ajax.responseText;
}
};
Your culprit is this section of the script:
var content = document.getElementById('messageBox').value;
if ( content === '') {
return;
} else {
var ajax = new XMLHttpRequest();
var username = document.getElementById('signedin').innerHTML;
document.getElementById('messageBox').value = '';
ajax.open('POST', 'postmessage.php', true);
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajax.onreadystatechange = function () {
if (ajax.status === 200 && ajax.readyState === 4) {
// if there are errors echoed from the PHP file
if (ajax.responseText != "") {
document.getElementById('mysqliError').innerHTML = ajax.responseText;
return;
}
document.getElementById('messagesArea').insertAdjacentHTML('beforeend', '<p class="message"><i>' + username + '</i>: ' + content + '</p>');
}
};
ajax.send('username=' + username + '&content=' + content);
}
Notice this line: document.getElementById('messagesArea').insertAdjacentHTML('beforeend', '<p class="message"><i>' + username + '</i>: ' + content + '</p>');
You are inserting the message, without the time, into #messagesArea. Then, in getRecentMessages later, it is set to fetch the entire chat log from displaymessages.php and overwrite #messagesArea with the content of the output, which does have the time.
I have got a validation script which validates my form first, if everything is okay it will return true (obviously PHP checks will be done as well after).
I have also got a JavaScript function which uploads the image and displays a progress bar, this is where things seem to be going wrong, the form is still submitting whilst the image is being uploaded, if it's uploading it should return false.
Form onsubmit call:
<form action="php/submitMessage.php" onsubmit="return !!(validation(this) && submitFile('image','reviewUpload'));" method="post" id="submitMessage">
Validation Script:
function validation(form) {
var inputs = form.elements;
var errors = Array();
for(var i=0;i<inputs.length;i++) {
if (inputs[i].getAttribute("rules") != null && inputs[i].getAttribute("rules") != "") {
var re = new RegExp(inputs[i].getAttribute("rules"));
var OK = re.test(inputs[i].value);
if (!OK) {
inputs[i].style.backgroundColor = "#e39d9d";
errors.push(false);
} else {
inputs[i].style.backgroundColor = "#6dcd6b";
errors.push(true);
}
}
}
//Check array for any errors
if (errors.indexOf(false) == -1) {
return true;
} else {
return false;
}
}
This is my image upload script, people are not required to add an image, so I have made it return true IF NO image has been selected.
function submitFile(fileId,buttonId) {
//Has a file been selected
if (doc(file).value != "") {
//Generate a new form
var f = document.createElement("form");
f.setAttribute("method", "POST");
f.setAttribute("enctype", "multipart/form-data");
//Create FormData Object
var formData = new FormData(f);
//Append file
formData.append("image", doc(file).files[0], "image.jpg");
var xhr = new XMLHttpRequest();
xhr.open("POST", "php/uploadImage.php", true);
xhr.onload = function(e) {
if (xhr.status == 200) {
if (xhr.responseText == "true") {
return true;
} else if (xhr.responseText == "false") {
return false;
}
} else {
console.log("error!");
console.log("Error " + xhr.status + " occurred when trying to upload your file");
}
};
//Progress
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
var currentPercentage = Math.round(e.loaded / e.total * 100)-1;
document.getElementById(buttonId).innerHTML = "UPLOAD IMAGE " + currentPercentage + "%";
document.getElementById(buttonId).style.backgroundSize = (currentPercentage+1) + "% 100%";
if (currentPercentage==99) {
document.getElementById(buttonId).innerHTML = "Processing image";
}
}
};
//Send data
xhr.send(formData);
} else {
return true;
}
}
Edit:
function handleSubmit() {
//Validate the form
var valid = validation(this);
var formElement = this;
//Check if validation passes
if (valid == true) {
//code here...
} else {
return false;
}
}
Even when validation() returns false the form is still submitting.
Form opening:
<form action="php/submitMessage.php" method="post" id="messageForm">
Writing this as answer as said by #Martin Ball
You can write single submit handler to do both validation check and image upload to get a better control of situation. Coming to your question, since image upload is asynchronous call submit functionality will not wait for completion of upload. You should handle success callback and submit after upload success and a separate submit handler will help in it.
e.g.
function handleSubmit () {
// validate your form
validation(this);
var xhr = new XMLHttpRequest();
// code to build XMLHttpRequest
var formElement = this;
xhr.onload = function (e) {
// code to handle success
// on success
// submit form
formElement.submit();
};
}
function validation () {
// logic to validate form
}
// attach submit to handler
var formElement = document.querySelector('submitMessage');
formElement.addEventListener('submit', handleSubmit);
Edit
In case you want to stop form from submitting you need to tell the event to stop doing the default action i.e. preventDefault.
see this jsbin for demo and code sample.
TLDR;
function handleSubmit (ev) {
var isValid = validation(this);
if(!valid) {
ev.preventDefault();
return false;
}
// further handling of submit action.
}
I have my JavaScript function which does XMLHttpRequest. Here is my code.
function addbilldetails() {
// Cancel the form submit
event.preventDefault();
// The URL to POST our data to
var postUrl = 'http://example.com/post.php';
// Set up an asynchronous AJAX POST request
var xhr = new XMLHttpRequest();
xhr.open('POST', postUrl, true);
// Prepare the data to be POSTed
var clientId = "clientid",
submittype = "a",
name = encodeURIComponent(document.getElementById('name').value),
billno = encodeURIComponent(document.getElementById('billno').value),
mobileno = encodeURIComponent(document.getElementById('mobileno').value),
phoneno = encodeURIComponent(document.getElementById('phoneno').value),
netAmount = encodeURIComponent(document.getElementById('netAmount').value);
var params = 'clientId=' + clientId +
'&billno=' + billno +
'&mobileno=' + mobileno +
'&phoneno=' + phoneno +
'&netAmount=' + netAmount +
'&type=' + submittype +
'&name=' + name;
// Replace any instances of the URLEncoded space char with +
params = params.replace(/%20/g, '+');
// Set correct header for form data
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
// Handle request state change events
xhr.onreadystatechange = function() {
// If the request completed
if (xhr.readyState == 4) {
statusDisplay.innerHTML = '';
if (xhr.status == 200) {
// If it was a success, close the popup after a short delay
statusDisplay.innerHTML = 'Saved!';
document.getElementById('save').disabled = false;
// window.setTimeout(window.close, 1000);
} else {
// Show what went wrong
statusDisplay.innerHTML = 'Error saving: ' + xhr.statusText;
}
}
};
// Send the request and set status
xhr.send(params);
statusDisplay.innerHTML = 'Saving...';
document.getElementById('save').disabled = true;
}
Now, the above code works perfectly and returns 200 on POST. But I want it to return custom message on the UI based on the value posted.
If the value POSTed is less than the value in the database, I want it to give "Enter Valid number" or something like this.
I am quiet new to XMLHttpRequest . I do not know how to achieve that. Any help would be highly appreciated.
Instead of statusDisplay.innerHTML = 'Saved!'; have you considered:
statusDisplay.innerHTML = xhr.responseText;
If you do this, then your statusDisplay will be equal to whatever your post.php echos out.
For example, in post.php
<?php
//handling $_POST['clientId'] ... etc
if (error)
echo "Enter Valid Number";
else
echo "Saved!";