I'm trying to save a few lines of text in a textarea with ajax targeting a classic asp file.
I'm not sure how to use ajax when when it comes to sending data with POST method and NOT using jQuery, didn't find any questions concerning this here either, no duplicate intended.
Ajax function:
function saveDoc() {//disabled
var xhttp = new XMLHttpRequest();
var note = document.getElementById("note");
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("0").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", "saveNote.asp", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(note);
ASP Classic:
set fs=Server.CreateObject("Scripting.FileSystemObject")
set f=fs.OpenTextFile("c:\inetasp\1.txt",8,true)
dim note
note = RequestForm("note")
f.Write(note)
f.Close
Response.Write("Works.");
set f=nothing
set fs=nothing
I'm aware there might be a lot wrong with the .asp since i couldn't find any specific info about how to handle ajax requests with Classic ASP correctly.
Any suggestions on how to make this work without jQuery are welcome.
I cannot test your code as I don't have a backend running on my machine right now. But I can already tell you a few things:
you are calling xhttp.send(note); but your note is a DOM element. It should be a string with a querystring format.
in your server side code you call RequestForm is it a custom function you have previously defined ? The usual syntax is Request.Form
Hope it can help
Related
This question already has answers here:
How to prepare encoded POST data on javascript?
(5 answers)
Closed 1 year ago.
The context
I'm building a save/load system for an email template builder based on grapesjs-mjml. I'm saving my MJML code in a BDD (MySQL).
My current code
I'm sending my template name and my template MJML code through an ajax call which look like that
let params = "name="+template_name + "&html="+template_mjml;
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "save.php", true);
xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// doing stuffs when it's saved
}
};
xhttp.send(params);
and on the server side, I'm catching the html value with a standard $_POST['html']
My issue
Sometimes, there is urls inside my html param (it could be links for example). And inside those urls, there is some & which means my $_POST['html'] is not reading the whole param: it's stopping right before the first & of my html code
My dirty solution
On my client side, I added a html = html.replaceAll('&','//amp;') and I'm doing the reverse function on the server side. Which that, I'm getting rid of all & in my 'html' param, but it's not very nice...
I would like to know if one of you know a better/nicer solution to do that ?
You should use encodeURIComponent(). This will properly encode special characters.
let params = "name=" + encodeURIComponent(template_name) + "&html=" + encodeURIComponent(template_mjml);
I am in need of a little help with a small bit of my code that is essential to my application. I am making a small clicker game, and I want users to be able to save and load data via PHP to my server. I do not want to use Local Storage to make it harder for anyone to edit their economy and "cheat". When the user clicks on a save button I have, it fires my vue method which initializes the saving. I have had no problem getting the data into a JSON format, however I cannot get PHP to read this data via POST. I have checked for network headers, and it shows that stuff is being sent, it seems that PHP just isn't catching it. I'll include the code for the JS part and PHP part below. The PHP is only set to echo if the array_key_exists right now, as after getting this sorted out I will easily be able to handle the rest. Any help would be greatly appreciated!
I have tried to follow this, which has not worked so far Send JSON data from Javascript to PHP?
JS
saloOut: function() {
var saveData = {
saveMoney: this.money,
saveCrystals: this.crystals,
};
saveData = "saveData=" + (JSON.stringify(saveData));
var sendData = new XMLHttpRequest();
sendData.open("POST", "salo.php", true);
sendData.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
sendData.send(saveData);
console.log(saveData);
}
PHP
<?php
if (array_key_exists("saveData", $_POST)) {
echo "<p>SALO Ready!</p>";
}
?>
Decode the JSON string at the PHP end before accessing values, like this:
<?php
if(isset($_POST['saveData'])){
$result = json_decode($_POST['saveData'], true);
// use $result['saveMoney'] and $result['saveCrystals'] accordingly
}
?>
Update# 1:
As OP commented below, I expect that it will print "SALO Ready" but it is instead doing nothing
That's because you are not using responseText property of XMLHttpRequest object to see the text received from the server. Use below snippet to see the response text.
saloOut: function() {
var saveData = {
saveMoney: this.money,
saveCrystals: this.crystals,
};
saveData = "saveData=" + (JSON.stringify(saveData));
var sendData = new XMLHttpRequest();
sendData.open("POST", "salo.php", true);
sendData.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
sendData.send(saveData);
sendData.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
}
};
}
Reference: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseText
I'm making a Design Studio custom component in Eclipse. I created a property 'backgroundColor' in my contribution.xml file. I can call this xml file inside my javascript and adjust it locally, but is there a way I can upload these changes to the server xml file again? Cause at the moment my alerts return all the new data but on the server side nothing happens.
Code that i have:
Contribution.xml:
<property
id="backgroundColor"
title="BackgroundColor"
type="Color"
group="Display"
visible="true"
bindable="true"/>
component.js:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "serverpath/contribution.xml", true);
xhttp.send();
function myFunction(xml) {
xml.responseXML.getElementsByTagName('property')[0].setAttribute("visible",false);
//this returns BackgroundColor so the call does work
alert(xml.responseXML.getElementsByTagName('property')[0].getAttribute("title"));
}
You will need to make some server side coding to do that. You could achieve that by making simple rest api. But otherwise without any server side coding you cant do that. You are now getting data with GET request to server which means you cant do any modifications, you simply get any server response data.
I have been following a tutorial on javascript and php and modifying it to my own personal tastes.
I've run into something i dont know how to fix, and i cant find anything online to help me fix it either.
The tutorial in question has shown me how to create and ajax module i can call from any php script to do its bidding. however the tutorial simply had the ordinary file paths of "index.php" or "signup.php", but i went ahead and out of my own personal preference, i used $_GET includes to display my pages via "index.php?page=signup"
the tutorial ajax module is:
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
now when i use a form to call this function to send data to php, it just sends me back to index.php without the dynamic url in place. im not sure what i need to place into the function call. the tutorial had:
var ajax = ajaxObj("POST", "signup.php");
I just dont know what to use besides "signup.php in the case of having the url being index.php?page=signup but nothing i've tried seems to work, and im starting to question if the error actually has anything to do with the ajax function.
Please assist a nooby noob in this dilemma.
I'm using XHR 2 to upload/save files.
According to the response of the server I want to perform an action. For example if the responce is "Saved" I want to hide a div or if the response is "Not Saved" I want to show another div etc...
I implemented what appears to be a simple code that should be working , but is not
Here is the snippet of the XHR
//initialize
var xhr = new XMLHttpRequest();
xhr.open('POST', 'upload.php');
xhr.responseType="text";
xhr.onload = function() {
//if all ok....
if (xhr.status === 200)
{
//update html5 progress bar
progress.value = progress.innerHTML = 100;
//get the respnse
var data=xhr.response;
//convert it to sting - kind of overkill, I know, but I'm stack
var data2=data.toString();
//alert it -- works
alert('data2 '+data2);
//now, do something, according to the response -- NOT working, never alert anything
if (data2=="Not Saved"){alert('Ooops, not saved');}
if(data2=="Saved"){alert('It's all good');}
if(data2=="File too big"){alert('hey, you are watching Jake and Amir');}
document.getElementById('imagesaved').innerHTML=data;
}
//refers to if (xhr.status === 200)
else {document.getElementById("imagesaved").innerHTML="Connect to server failed";}
What is wrong here? This should be working right? Any suggestions?
Thanks
EDIT
I put the alerts for testing. What I actually want to do is call some functions.
If I put
if (data2=="Not Saved"){functionOne();}
if(data2=="Saved"){functionTwo();}
if(data2=="File too big"){functionThree();}
the functions never get called
if I put
if (data2!="Not Saved"){functionOne();}
if(data2!="Saved"){functionTwo();}
if(data2!="File too big"){functionThree();}
ALL the functions are called!!!
I still dont get it...Maybe its something with the response? Or the onload function?
Thanks again
What I finally did is make the server response with numbers, not text. So encoding does not matter any more...
This is the code
var xhr = new XMLHttpRequest();
xhr.onload = function() {
if (xhr.status == 200)
{
var data=xhr.response;
if(data==1)
//say to the user is saved
{document.getElementById('imagesaved').innerHTML="Saved";}
//say to the user, there was an error
else{document.getElementById('imagesaved').innerHTML="Error";}
}
//say to the user that connection to the server failed
else {document.getElementById("imagesaved").innerHTML="Cannot connect";}
};
xhr.open('POST', 'upload.php');
xhr.send(formData);
This is a workaround. I dont know if its the right way to solve this problem , technically. I decided to post it anyway, to help others to quickly solve similar problems. If anyboy else has a better way to suggest , please do.
In this line : if(data2=="Saved"){alert('It's all good');}, you have to escape " ' ".
So convert it to : if(data2=="Saved"){alert('It\'s all good');}
Are you sure that the response of your ajax is text/plain ?
Look on the console (ctrl+shift+i on chrome, F12 on firefox), on net or network tab.
Look on console tab if you got some javascript errors too.