Send and process FormData - javascript

I've been struggling for hours with following code without success. In my html I have several inputs (type=text, type=date and selects), and a button calling a js function: onclick=SendNewData().
The JS function is something like the following:
function SendNewData() {
var MyData1=document.getElementById("id1").value;
var MyData2=document.getElementById("id2").value;
var MyData3=document.getElementById("id3").value;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open('POST', 'Handler.php', true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status==200) {
document.getElementById("FormNuevaCom").innerHTML = xmlhttp.responseText;
}
}
var data = new FormData;
data.append('DATA1', MyData1);
data.append('DATA2', MyData2);
data.append('DATA3', MyData3);
xhr.send(data);
}
and the Handler.php is something like the following:
if(isset($_POST['DATA1'])) {
$MyVar=$_POST['DATA1'];
echo "Hi there! ".$MyVar." received...";
}
I canĀ“t get any response. Anyone can spot the problem?

Related

Why are my javascript functions are stacking?

I am making a messaging system and I have recently implemented a file uploader, and my javascript functions aren't working, if I press the input file button then press cancel, the next time I upload a file it does it 3 times. It's as if since I don't upload anything, they just sit there and then the function stack. Here is my input :
<input type="file" id="file" onclick="bro()"name="file" value="FILE UPLOAD" style="opacity: 0;z-index: 100000; bottom: 17.5px; position: fixed; right: 10px;">
And here is my javascript function
function bro() {
document.querySelector('#file').addEventListener('change', function(e) {
var file = this.files[0];
var fd = new FormData();
fd.append("file", file);
var xhr = new XMLHttpRequest();
var group_id = document.getElementById('group_id').value;
var fullurl = '../backend/sendvideosandimages.php?id=' + group_id;
xhr.open('POST', fullurl, true);
xhr.onload = function() {
if (this.status == 200) {
};
};
xhr.send(fd);
}, true);
};
The problem is, I can't just put the function because I use an ajax request thing to display the input. To explain more since I am making a messaging system I have a sidebar with group id and group name. I use this function :
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxLoad(page, id, id2){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('mainpage');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var queryString = "?id=" + id + "&id2=" + id2;
//alert(page + queryString);
ajaxRequest.open("GET", page + queryString, true);
ajaxRequest.send(null);
}
//-->
</script>
The problem is that if I put the event change listener by itself, then it bugs because when the home page loads, the mainpage does not have a input yet. And if I put a script in the mainpage it doesn't execute
It is stacking because of multiple eventListeners . there only should be 1 eventListeners .
Firstly, take document.querySelector('#file').addEventListener out of bro() function.
Whenever you calling function. It is adding new change listeners without removing before one.
thus seems like bro function has no use;
This will work :
document.querySelector('#file').addEventListener('change', function(e) {
var file = this.files[0];
var fd = new FormData();
fd.append("file", file);
var xhr = new XMLHttpRequest();
var group_id = document.getElementById('group_id').value;
var fullurl = '../backend/sendvideosandimages.php?id=' + group_id;
xhr.open('POST', fullurl, true);
xhr.onload = function() {
if (this.status == 200) {
};
};
xhr.send(fd);
}, true);
//OR
function bro() {
document.querySelector('#file').removeEventListener('change',(e)=>{console.log('removed listener')})
document.querySelector('#file').addEventListener('change', function(e) {
var file = this.files[0];
var fd = new FormData();
fd.append("file", file);
var xhr = new XMLHttpRequest();
var group_id = document.getElementById('group_id').value;
var fullurl = '../backend/sendvideosandimages.php?id=' + group_id;
xhr.open('POST', fullurl, true);
xhr.onload = function() {
if (this.status == 200) {
};
};
xhr.send(fd);
}, true);
}
Remove the change event handler and then try.
You need to remove this:
document.querySelector('#file').addEventListener('change'
Right now you have two events on file upload.
Change event.
Click event.
When you click it adds a change event hence multiple uploads.
Here either you can remove change event code or remove the event listener every time you click.
Try these fixes and see if it works.

changing the text of a button in ajax

I Have list confirmation buttons generated dynamically using PHP.When I click a button i want it change to "approved".But it is not doing so?Nothing changes though the query is submitted successfully.Any help please.Here is my js code snippet:
function appr ($ref) {
var job_id= $ref;
var resp;
var buttons=$('.confirm');
buttons.click(function(){
var $this=$(this);
$this.text=('approved');
});
if (window.XMLHttpRequest) {
resp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
resp = new ActiveXObject("Microsoft.XMLHTTP");
}
var data = "job_id="+job_id
resp.open("POST",
"approve.php",
true);
resp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
resp.send(data);
resp.onreadystatechange = display_data;
function display_data() {
if (resp.readyState == 4) {
if (resp.status == 200) {
document.getElementById("myDiv").innerHTML=resp.responseText;
} else {
alert('Request not successful.');
}
}
}
}
you can do it like that
$this.html("approved");

JavaScript - Inserting into Content section of HTML

I want my program to work like this: When i press a hyperlink in html, i want it to load new content into the "content" section. I have an example code that does this. But I am trying to insert a dygraph inside and I find that the example only passes string. The graph that i was trying to insert did not appear in the content, only basic html appeared (button, background color, etc)
function loadPage(page)
{
if(window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", page, true);
xmlhttp.setRequestHeader("Content-type",
"application/x-www-form-urlencoded");
xmlhttp.send();
xmlhttp.onreadystatechange = function ()
{
if((xmlhttp.readyState == 4) && (xmlhttp.status == 200))
{
document.getElementById("content").innerHTML = xmlhttp.responseText;
}
}
}
If i'm not wrong, the loadPage function needs to be edited. But i'm not sure how. Hope you guys can answer me in a layman's term.
You need to pass your newly retrieved content to dygraph after you fetch.
function loadPage(page) {
if (window.XMLHttpRequest) {
var xmlhttp = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.open("GET", page, true);
xmlhttp.setRequestHeader("Content-type",
"application/x-www-form-urlencoded");
xmlhttp.send();
xmlhttp.onreadystatechange = function () {
if ((xmlhttp.readyState == 4) && (xmlhttp.status == 200)) {
var g = new Dygraph('content', xmlhttp.responseText, [rest of your parameters]);
}
}
}
}

How do I have the text and xml files open in a new window/tab?

Here is the code. I am fairly new to JavaScript and I'm learning more every day. This code is from an example from a textbook. Thank you for your responses. Another question I'd like to ask is how can I display the returned text in an unordered list? Would that be something to include in the html side of things or can it be done within the JavaScript file?
window.addEventListener("load",initAll,false);
var xhr = false;
function initAll() {
document.getElementById("makeTextRequest").addEventListener("click",getNewFile,false);
document.getElementById("makeXMLRequest").addEventListener("click",getNewFile,false);
}
function getNewFile(evt) {
makeRequest(this.href);
evt.preventDefault();
}
function makeRequest(url) {
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
}
}
}
if (xhr) {
xhr.addEventListener("readystatechange",showContents,false);
xhr.open("GET", url, true);
xhr.send(null);
}
else {
document.getElementById("updateArea").innerHTML = "Sorry, but I couldn't create an XMLHttpRequest";
}
}
function showContents() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
if (xhr.responseXML && xhr.responseXML.childNodes.length > 0) {
var outMsg = getText(xhr.responseXML.getElementsByTagName("choices")[0]);
}
else {
var outMsg = xhr.responseText;
}
}
else {
var outMsg = "There was a problem with the request " + xhr.status;
}
document.getElementById("updateArea").innerHTML = outMsg;
}
function getText(inVal) {
if (inVal.textContent) {
return inVal.textContent;
}
return inVal.text;
}
}
By the looks of it, you are making an AJAX request and are receiving XML.
In this case, I would:
Open up a new page with window.open()(returns a new Window object)
And then change the document.body.innerHTML of that new page to the XML you have
If you had a webpage that held the XML(maybe the server you are requesting to has one), you can just do:
window.open("page.xml");

ajax request one by one

I need a function that click one link, send ajax request to 2 pages one by one.
first send data to page1.php, when finish page1's work, back the data to the main page, then send data to page2.php do another ajax process and return data to the main page.
I write page2.php Request in page1.php document.getElementById("div1").innerHTML = HttPRequest.responseText;, but this will only return the page2's data and miss back the data from page1.php
in firebug , consule:
page1.php (always show loading.gif)
page2.php 200 OK 2199ms
how to do the ajax one by one well? Thanks.
function myajax(text) {
var HttPRequest = false;
if (window.XMLHttpRequest) {
HttPRequest = new XMLHttpRequest();
if (HttPRequest.overrideMimeType) {
HttPRequest.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) {
try {
HttPRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
HttPRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!HttPRequest) {
alert('Cannot create XMLHTTP instance');
return false;
}
var url = 'page1.php';
var pmeters = "text=" + text;
HttPRequest.open('POST',url,true);
HttPRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
HttPRequest.send(pmeters);
HttPRequest.onreadystatechange = function()
{
if(HttPRequest.readyState == 4)
{
document.getElementById("div1").innerHTML = HttPRequest.responseText;
var url = 'page2.php';
var pmeters = "text=" + text;
HttPRequest.open('POST',url,true);
HttPRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
HttPRequest.send(pmeters);
HttPRequest.onreadystatechange = function()
{
if(HttPRequest.readyState == 4)
{
document.getElementById("div2").innerHTML = HttPRequest.responseText;
}
}
}
}
}
There are two options to do it.
Use Ajax in Synchronous mode, so the code will wait until you get results from page1
Call the Ajax method for Page2 only at the response of Page1
Option 2 is better since it work in Asynchronous mode.
Here is a pseudo code:
var xhr = new XMLHttpRequest();
xhr.open( ..)
xhr.onreadstatechange = function() {
// handle page1 response
// do page2 reauest
var xhr2 = new XMLHttpRequest();
xhr2.open( ... )
xhr2.onreadystatechange = function() {
// handle page2 response
}
xhr2.send(null);
}
xhr.send(null);

Categories