Hi i would like to create a login page in html 5, but in order to login i need to send the username and password to a web service, the web service is already created and it will return a value 0 if flase and any other number if true. I can only use javascript and json. Can anyone help me out to understand json as i know almost nothing about it. How would i send the username and password using json and javascript?
var form;
form.onsubmit = function (e) {
// stop the regular form submission
e.preventDefault();
// collect the form data while iterating over the inputs
var data = {};
for (var i = 0, ii = form.length; i < ii; ++i) {
var input = form[i];
if (input.name) {
data[input.name] = input.value;
}
}
// construct an HTTP request
var xhr = new XMLHttpRequest();
xhr.open(form.method, form.action, true);
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
// send the collected data as JSON
xhr.send(JSON.stringify(data));
xhr.onloadend = function () {
// done
};
};
Related
The Ajax request is being sent continuously and I am not sure why
placing return false in multiple areas of the code.
//when user clicks on create channel
document.querySelector('#add-channel').onclick = () => {
// pop up modal
modal1.style.display = "block";
// Initialize new request
document.querySelector('#form1').onsubmit = () => {
const request = new XMLHttpRequest();
const chatroom = document.querySelector('#chatroom').value;
const username = localStorage.getItem('name');
request.open('POST', '/add_chatroom');
// Callback function for when request completes
request.onload = () => {
// Extract JSON data from request
const data = JSON.parse(request.responseText);
// Update the result div
if (data.success) {
// get the data that was returned.
// add it back to the list
document.querySelector('#contacts').append(li);
}
else {
alert('chatroom already exists');
}
}
// add data to send to the server
const data = new FormData();
data.append('chatroom', chatroom);
data.append('username', username);
// Send request
request.send(data);
return false;
};
};
The post request won't stop everytime I click ok even though the event should only trigger when the form with id #form1 is submitted. It triggers even when i click ok for the alert.
I ended up changing the browser from Firefox to Microsoft edge to solve the onsubmit re-running issue, why this works is beyond my knowledge.
Js method
I have create a js post method using xmlhttprequest posting data to my
php page. The problem is how i will get the data after post request is
successful and display on my html page Below is my code.
I am currently working on a project that i have to use js method to post,get delete other more. All I want is an idea of how to get the data deplayed when the submit form function is called after successful submission of the data.
The code is working the part but the feedback part
//define form variables
var formSubmition = document.getElementById('formSubmition');
//addEventListener
formSubmition.addEventListener('submit',dataSubmit,true);;
function pageView(){
//localstorage_cookie = localStorage setItem('userpage_id','27727');
}
// connect to server via XMLHttpRequest
function serverConnection(){
this.object = {
method:'',
url:'',
data:'',
connect:function(a,b,d){
if(window.XMLHttpRequest){
server_http = new XMLHttpRequest();
}else{
server_http = new ActiveXObject('Microsoft.XMLHTTP');
}
server_http.onprogress = function(event){
console.log(event);
}
server_http.onreadystatechange = function(e){
if(server_http.readyState == 4 && server_http.status == 200){
var res = server_http.responseText;
return res;
}
}
server_http.open(a,b,true);
//server_http.setRequestHeader("Content-type","application/x-www-
form-urlencoded");
server_http.send(d);
}
}
}
var conn = new serverConnection(),response_xmlhttp = new serverConnection();
function serverConn(c,method,URI,formdata){
//defining data configurations
c.object['method'] = method; //defined key data for method
c.object['url'] = URI; //defined key data for url
c.object['data'] = formdata; //defined key data for data
//store in global variables
var method,url,data;
method = c.object['method'];
url = c.object['url'];
data = c.object['data'];
c.object.connect(method,url,data);
}
//submit_data using the class conn
function dataSubmit(e){
e.preventDefault();
var formdata,method,URI,username,password;
//define username and password
username = document.getElementById('username').value;
password = document.getElementById('password').value;
if(username == '' && password == ''){
alert('fill in all the fields');
}else{
formdata = new FormData(this);
formdata.append('submit_data','SIGNIN');
method = 'POST';
URI = 'admin/php_data/loginCredentials.php';
serverConn(conn,method,URI,formdata);
}
}
You need to pass a call back function to serverConnection which it can call when it receives the data from backend, something alone the lines of
function serverConnection(cb){
this.object = {
method:'',
url:'',
data:'',
connect:function(a,b,d){
if(window.XMLHttpRequest){
server_http = new XMLHttpRequest();
}else{
server_http = new ActiveXObject('Microsoft.XMLHTTP');
}
server_http.onprogress = function(event){
console.log(event);
}
server_http.onreadystatechange = function(e){
if(server_http.readyState == 4 && server_http.status == 200){
var res = server_http.responseText;
cb(res);
return res;
}
}
server_http.open(a,b,true);
//server_http.setRequestHeader("Content-type","application/x-www-
form-urlencoded");
server_http.send(d);
}
}
}
and then create a function to handle response
function handleResponse(res) {
// set the res in some element
}
Now just pass it to server connection
var conn = new serverConnection(handleResponse)
i have a javascript array with values like "correct", "wrong".
I want to send this array to my php file using ajax. But im not familiar with how.
This is what i have tried so far..and i would like to do this without jquery.
var hold=[];
for(t = 0;t <= 10; t++){
answers_Arr = document.getElementsByName("question"+t);
for (k = 0; k < answers_Arr.length; k++){
if(answers_Arr[k].checked){
hold[t] = answers_Arr[k].value;
//document.getElementById("test"+t).innerHTML = "Value: "+ hold[t];
break;
}else{
hold[t] = "no";
continue;
}
}
}
var jsonString = JSON.stringify(hold);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("test1").innerHTML= xmlhttp.responseText;
}
}
xmlhttp.open("GET","result.php?res="+hold[],true);
xmlhttp.send();
}
Here is an example of sending the json string with POST through AJAX:
var jsonString = JSON.stringify(hold);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
//
}
xmlhttp.open("POST","result.php",true);
xmlhttp.setRequestHeader("Content-type", "application/json");
xmlhttp.send(jsonString);
Avoid sending json strings with GET method because if the request string gets too long, the browser will throw you an error.
Now in your php script you will have all the data in $_POST
Edit: Looks like on some versions of php, the requests that have other Content-type, like application/json, the $_POST has an empty value. To fix this you can do:
$_POST = json_decode(file_get_contents('php://input'));
replace this line
xmlhttp.open("GET","result.php?res="+hold[],true);
with
xmlhttp.open("GET","result.php?res="+jsonString,true);
I have a simple web app that uses an API to return search results from a database and uses ajax to insert them into an empty ul element on the page. (Using JSONP with a cross domain request)
I cant figure out how to do it using javascript, everywhere I've found uses jQuery. I want to be able to have them enter another search term and have it clear the existing content from the page.
Currently if you conduct a second search it just appends the new results to the bottom of the existing list.
Once you have the content (returned from your API call using AJAX) you just can assign it to your ul or div e.g. document.getElementById('YourULID').innerHTML = "The content you got from your AJAX call"
From vanilla.js (so you can compare with jQuery):
var r = new XMLHttpRequest();
r.open("POST", "path/to/api", true);
r.onreadystatechange = function () {
if (r.readyState != 4 || r.status != 200) return;
alert("Success: " + r.responseText);
};
r.send("banana=yellow");
if i understand what you want. You want to get result from server and insert them into a ul form field of your webpage.
This is just an example and might help
function createRequest(){
try{
request = new XMLHttpRequest();
}catch (tryMS){
try{
request = new ActivXObject("Msxml2.XMLHTTP");
}catch (otherMS){
try{
request = new ActivXObject("Microsoft.XMLHTTP");
}catch (failed){
request = null;
}
}
}
return request;
}
function loggin(user_id,password){
request = createRequest();
data = new FormData();
data.append('user_id',user_id.value);
data.append('password',password.value);
request.onreadystatechange=function(){
if(request == null){
alert('Unable to connect');
}else{
if(request.readyState==4){
if(request.status==200){
if(request.responseText){
document.location.href = request.responseText;
}
}
}
}
}
This will create and HTTP request. Post data to your server then fetch the result and throw it back to your javascript, then staight to your webpage. Use request.responseText to append/insert to the appropriate field
I figured it out by using a few simple lines of html when onsubmit occurs with the search field:
var div = document.getElementById('cart_item');
while(div.firstChild){
div.removeChild(div.firstChild);
}
I am trying to send a JSON object to a web api, but am having a bit of trouble. Its supposed to take value from an input, check the response first, and if the response is correct, send the data. Here is my JS code:
var form = document.getElementById("inputForm"), master = {}, xhr = new XMLHttpRequest(); //global variables used for checking different parts of the process
form.onsubmit = function (e) {
// stop the regular form submission
e.preventDefault();
// collect the form data while iterating over the inputs
var data = {};
for (var i = 0, ii = form.length; i < ii; ++i) {
var input = form[i];
if (input.name) {
data[input.name] = input.value;
}
master.data = data;
}
// construct an HTTP request
function get(url, callback) {
xhr.open("GET", url);
xhr.onreadystatechange = function() {
if(xhr.readyState === 4 && xhr.status === 200) {
var type = xhr.getResponseHeader("Content-Type");
if (type.indexOf("xml") !== -1 && xhr.responseXML)
callback(xhr.responseXML);
else if (type === "application/json")
callback(JSON.parse(xhr.responseText));
else
callback(xhr.responseText);
}
};
// send the collected data as JSON
console.log(JSON.stringify(master));
xhr.send(JSON.stringify(master));
}
get("http://example.com:12321/data");
};
However, when sending it, I get a HTTP 500 error in the console, and the output in the server itself says:
Processing request on /data
Caught error: <unspecified file>(1): expected object or array
And here is the result of the console.log:
{"data":{"val":"2"}}
I thought I was sending the data correctly, but it isnt recognizing it. The example they gave was of a .json file and that works fine, but my stringified JSON isnt working.
Any help would be greatly appreciated