I am building an online calculator and tried to send the values through AJAX to process them by a php script. The response from the server is set to the div but that div immediately disappears after showing. My ajax code is:
function get_XmlHttp() {
// create the variable that will contain the instance of the XMLHttpRequest object (initially with null value)
var xmlHttp = null;
if(window.XMLHttpRequest) { // for Forefox, IE7+, Opera, Safari, ...
xmlHttp = new XMLHttpRequest();
}
else if(window.ActiveXObject) { // for Internet Explorer 5 or 6
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttp;
}
function ajaxrequest(php_file, tagID) {
var request = get_XmlHttp(); // calls the function for the XMLHttpRequest instance
// gets data from form fields, using their ID
var c1 = document.getElementById('c1').value;
var c2 = document.getElementById('c2').value;
var c3 = document.getElementById('c3').value;
var c4 = document.getElementById('c4').value;
var c5 = document.getElementById('c5').value;
var c6 = document.getElementById('c6').value;
// create pairs index=value with data that must be sent to server
var the_data = 'c1='+c1+'&c2='+c2+'&c3='+c3+'&c4='+c4+'&c5='+c5+'&c6='+c6;
request.open("POST", php_file, true); // sets the request
// adds a header to tell the PHP script to recognize the data as is sent via POST
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(the_data); // sends the request
// Check request status
// If the response is received completely, will be transferred to the HTML tag with tagID
request.onreadystatechange = function() {
if (request.readyState == 4) {
document.getElementById("ajaxform").submit();
document.getElementById(tagID).innerHTML = request.responseText;
}
}
}
Please note that I am using bootstrap CSS framework for the actual site and not applying any classes on the response div.
Thanks
In your onreadystatechange handler, you're submitting a form, which is causing the page to submit (and therefore the page to change).
request.onreadystatechange = function () {
if (request.readyState == 4) {
document.getElementById("ajaxform").submit(); // <-- ?
document.getElementById(tagID).innerHTML = request.responseText;
}
}
The fact you're seeing the same page again means the form ajaxform has no action set.
Related
I’m trying to submit a form with data to a php file without reloading the page. I also have some js code that changes the form name and values when the next btn is clicked. I had 10 questions all on 1 page and I got it to work with PHP but now I’m trying to get 1 question per page. I looked in the network tab and it looks like the xhr requests are being sent but in my database.php file I wrote $user_anwser = $_POST[‘quiz_1’]; and var dumped it and I get a NULL value. Here is the ajax code.
form.addEventListener("submit", function(e){
if (ind < 10){
e.preventDefault();
} else {
form.setAttribute("action", "results.php");
}
let data = new FormData(form);
let xhr = new XMLHttpRequest();
xhr.open('POST', '../private/database.php');
xhr.onload = function() {
if (xhr.status === 200) {
// if the response is json encoded
let response = JSON.parse(xhr.responseText); // i get a parse error there
if (response.message == 'valid') {
// redirect here
}
}
// }
xhr.send(data);
}
});
I am using AJAX to display upcoming events on a website. To that end, I call a JavaScript function via onload="showEvents(3);", see the function below:
function showEvents (amount) {
// are there Events?
if (document.getElementById("eventsDiv")) {
document.getElementsByClassName("info")[0].innerHTML = 'Loading events...';
// initialize XML Http Request
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("eventsDiv").innerHTML = xmlhttp.responseText;
}
}
// send request
xmlhttp.open("GET", "./events.php?number=" + encodeURIComponent(amount), true);
xmlhttp.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
xmlhttp.send();
}
}
The file events.php is a PHP file in the same directory, and it connects to the database to fetch the upcoming events. The HTML header of the main website includes
<base href="http://www.my-domain.com/">
The problem: I get a "Cross Orign" error message (in Firefox), preventing my parent index.html file accessing the events.php. As I understand, this error message should not appear since I am using a resource from the same directory.
Ok that's ok, you also can do like this...
if($_SERVER['HTTP_ORIGIN'] == "http://your-domain.com") {
header('Access-Control-Allow-Origin: http://your-domain.com');
I'm learning and trying to write a simple stock quote tool using Python-Flask and Javascript.
I specifically want to learn plain Javascript. My code is working, but what I don't understand is when I'm watching the developer console, I get 3 error messages printed before I get the successful console.log(response).
Is it simply that the code loops 3 times before the response comes back, so it logged 'ERROR' each of those times before finally returning the 200 status? Would someone explain it to me or point me to a good article/post?
My event listener:
document.getElementById("btn_quote").addEventListener("click", getQuote);
The ajax call:
function getQuote(e){
e.preventDefault();
var ticker = document.getElementById("ticker").value
var shares = document.getElementById("shares").value
var url = "/quote/"+ticker+"/"+shares
// Fetch the latest data.
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState === XMLHttpRequest.DONE) {
if (request.status === 200) {
var response = JSON.parse(request.response);
console.log(response);
}
} else {
// TODO, handle error when no data is available.
console.log('ERROR');
return false;
}
};
request.open('GET', url);
request.send();
}
It's not returning separate HTTP status codes, its returning different ready states.
Change your console.log("ERROR");. To console.log(request.readyState);.
Then you will see what it is reporting and why.
i think you should be checking your readyState values with the actual values of the response. For you reference, following are the possible values of readyState:
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
So you could basically check it to be 4 in your case:
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState === 4) {
//response statements
} else {
//error statements
}
};
Basically, ajax calls will get notified for the following events which is called as readyStateChange event.
For most cases, you used to get 4 ready state changes based on the speed of the connection (rare cases only only one if it's very quick) and you should check whether it is 4 which means the response is completed now.
To check whether the request is suceess or not, you should check the request.status === 200 which means success and can check for other http status code for errors like 404, 500 etc.
document.getElementById("btn_quote").addEventListener("click", getQuote);
document.getElementById("btn_quote_error").addEventListener("click", getQuoteError);
function getQuote(e){
e.preventDefault();
var ticker = document.getElementById("ticker").value;
var shares = document.getElementById("shares").value;
//var url = "/quote/" + ticker + "/" + shares;
var url = 'http://stackoverflow.com/';
// Fetch the latest data.
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
console.log(request.readyState);
if (request.readyState === XMLHttpRequest.DONE) {
console.log(request.status);
if (request.status === 200) {
//var response = JSON.parse(request.response);
//console.log(response);
}
}
//else {
// TODO, handle error when no data is available.
//console.log('ERROR');
//return false;
//}
};
request.open('GET', url, true);
request.send();
}
function getQuoteError(e){
e.preventDefault();
var ticker = document.getElementById("ticker").value;
var shares = document.getElementById("shares").value;
//var url = "/quote/" + ticker + "/" + shares;
var url = 'http://stackoverflow404.com/';
// Fetch the latest data.
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
console.log(request.readyState);
if (request.readyState === XMLHttpRequest.DONE) {
console.log(request.status);
if (request.status === 200) {
//var response = JSON.parse(request.response);
//console.log(response);
}
}
//else {
// TODO, handle error when no data is available.
//console.log('ERROR');
//return false;
//}
};
request.open('GET', url, true);
request.send();
}
<input type="text" id="ticker"/>
<input type="text" id="shares"/>
<input type="button" id="btn_quote" value="Get Quote" />
<input type="button" id="btn_quote_error" value="Get Quote Error" />
How do I send a custom HTTP body with my POST AJAX request in plain Javascript (not JQuery)? I am actually trying to send a JSON file in the body. I can set the custom header fields but can't find how to set HTTP body.
below is the code
function calculateorder() {
document.getElementById("finalize").style.display = "inline";
url1 = "https://ethor-prod.apigee.net/v1/stores/";
url2 = "/orders/calculate?apikey=wSgbv9PE8aJhDOI17vvTUX1NlAceUXG7";
url = url1 + store_id + url2;
var xmlhttp;
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-Type", "application/json");
xmlhttp.send(JSON.stringify(calculate));
}
When I used the same headers and JSON file with Rested (a OSX HTTP client) It works perfectly
Add parameter in XmlHttpRequest Obeject's .send() method
Like this:
xhr.send('username=me');
Send JSON Format Data myData Like this:
xhr.send(JSON.stringify(myData));
How to send an http request with either post/get method using javascript as an eventhandler? Thanks! Paul
Okay, you don't want to use Ajax.
You can use an event handler to submit a form!
<a href='#' onclick='cow_submit("zoodle")'>send</a>
<form method='post' id='formie' action='find_some_action.php'>
<input type='hidden' id='snoutvar' name='snoutvar' value='snout'>
</form>
<script>
function cow_submit(a_var_to_set){
var plip=document.getElementById('formie');
var snout=document.getElementById('snoutvar');
snout.value=a_var_to_set;
plip.submit();
}
See https://developer.mozilla.org/en/DOM/form
use XmlHttpRequest
sample code:
var client = new XMLHttpRequest();
client.onreadystatechange = handler;
client.open("GET", "test.xml");
client.send();
function handler()
{
// your handler
}
You can use XMLHttpRequest for sending request from javascript
Sending GET request
var url = "get_data.php";
var params = "lorem=ipsum&name=binny";
http.open("GET", url+"?"+params, true);
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(null);
Sending POST request
var url = "get_data.php";
var params = "lorem=ipsum&name=binny";
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
And don't forget to encode parameters using encodeURIComponent for param value encoding in case of user input
e.g.
params="paramName="+encodeURIComponent(paramValue);
The standard class for doing this is XmlHttpRequest, but it's not universally supported. On some browsers you have to use ActiveXObject("Microsoft.XMLHTTP") instead.
Look into the jQuery system which provides HTTP download (AJAX style) methods regardless of the underlying browser APIs (hence avoiding a lot of the code shown in Tzury's answer).
The jQuery AJAX documentation is at http://docs.jquery.com/Ajax
You should try to add atring in a hidden field and then call the form.submit() to submit your form into the page define in action.
<script type="text/javascript">
function doTestFormSubmit(yourString) {
document.getElementById("myString").value=myString;
document.getElementById("testForm").submit();
}
</script>
<form name="testForm" id="testForm" action="yourDesiredPage.php" method="post">
<input type="hidden" name="myString" id="myString" value=""/>
</form>
Ajax Tutorial (http://code.google.com/edu/ajax/tutorials/ajax-tutorial.html)
var obj;
function ProcessXML(url) {
// native object
if (window.XMLHttpRequest) {
// obtain new object
obj = new XMLHttpRequest();
// set the callback function
obj.onreadystatechange = processChange;
// we will do a GET with the url; "true" for asynch
obj.open("GET", url, true);
// null for GET with native object
obj.send(null);
// IE/Windows ActiveX object
} else if (window.ActiveXObject) {
obj = new ActiveXObject("Microsoft.XMLHTTP");
if (obj) {
obj.onreadystatechange = processChange;
obj.open("GET", url, true);
// don't send null for ActiveX
obj.send();
}
} else {
alert("Your browser does not support AJAX");
}
}
function processChange() {
// 4 means the response has been returned and ready to be processed
if (obj.readyState == 4) {
// 200 means "OK"
if (obj.status == 200) {
// process whatever has been sent back here:
// anything else means a problem
} else {
alert("There was a problem in the returned data:\n");
}
}
}