POST Request (Javascript) - javascript

How do you make a simple POST request in Javascript without using a forms and without posting back?

Though I am taking the code sample from #sundeep answer, but posting the code here for completeness
var url = "sample-url.php";
var params = "lorem=ipsum&name=alpha";
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
//Send the proper header information along with the request
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(params);

You can do this using AJAX calls (XMLHttpRequest object)
http://www.openjs.com/articles/ajax_xmlhttp_using_post.php

I have made a function that send a request without refresh the page, without open a page and without AJAX. The proccess is invisible to the user. I use a false iframe to send a request:
/**
* Make a request without ajax and without refresh the page
* Invisible for the user
* #param url string
* #param params object
* #param method string get or post
**/
function requestWithoutAjax( url, params, method ){
params = params || {};
method = method || "post";
// function to remove the iframe
var removeIframe = function( iframe ){
iframe.parentElement.removeChild(iframe);
};
// make a iframe...
var iframe = document.createElement('iframe');
iframe.style.display = 'none';
iframe.onload = function(){
var iframeDoc = this.contentWindow.document;
// Make a invisible form
var form = iframeDoc.createElement('form');
form.method = method;
form.action = url;
iframeDoc.body.appendChild(form);
// pass the parameters
for( var name in params ){
var input = iframeDoc.createElement('input');
input.type = 'hidden';
input.name = name;
input.value = params[name];
form.appendChild(input);
}
form.submit();
// remove the iframe
setTimeout( function(){
removeIframe(iframe);
}, 500);
};
document.body.appendChild(iframe);
}
Now you can do it:
requestWithoutAjax('url/to', { id: 2, price: 2.5, lastname: 'Gamez'});
See how works!: http://jsfiddle.net/b87pzbye/10/.

Related

JavaScript is retrieving data from mysql database that is suppose to be deleted with AJAX delete method already

In the script , a button have an onclick function that call deleteByName function
<button onclick='deleteByName("name","view","view_value")' type='button'>
In this function , it use AJAX to execute delete method and calls search function to update page
function deleteByName (target,view,view_value){
var url = "http://localhost/assignment_web/index.php/facility/name/"+target;
request.open("DELETE", url, true);
request.send(null);
search("all");
}
In search function , it use AJAX get method to retrieve data and use updatePage attribute to update the innerHTML
function search(type) {
var target = "" ;
if(type=="district"|type=="name"){
var target = document.getElementById('option_txt').value;
}
var url = "http://localhost/assignment_web/index.php/facility/"+type+"/"+target;
request.open("GET", url, true);
request.onreadystatechange = updatePage;
request.send(null);
}
function updatePage() {
if (request.readyState==4) {
if (request.status==200) {
var serverData = request.responseText;
console.log("serverData: "+serverData);
var dataArr = JSON.parse(serverData);
var objLen = Object.keys(dataArr).length;
var view = document.querySelector('input[name="option"]:checked').value;
var view_value;
var html ="<ul>";
for(let i=0;i<objLen;i++){
var name =dataArr[i].Name_en ;
if(view=="district"){view_value = dataArr[i].District_en;}else if(view=="name"){view_value = dataArr[i].Name_en;
}else{view_value = "all" ; }
html = html+"<li>District : "+dataArr[i].District_cn+"&nbsp"+dataArr[i].District_en
+"</li>...<li><button onclick='deleteByName(\""+name+"\",\""+view+"\",\""+view_value+"\")' type='button'>delete</button>
<div name=\""+name+"_textBox\" id=\""+name+"_textBox\"></div></li><hr>" ;
}
html = html+"</ul>";
document.getElementById("displayArea").innerHTML = html;
}
}
}
The question is , in get method , it retrieved the data (shown in console.log(DataArr) ) i was deleted from the delete method before . How do i make sure the update function won't retrieve any data that is deleted before instead retrieving the data after the delete method is complete ...

Form onsubmit in dynamic iframe do not get triggered

Update
the problem is not the iframe, the problem is the form not submitting by the onsubmit function that posts json. The goal is to dynamically create an iframe that redirects using a form post to another URL with the json content of the script tag above.
Original
I have the following on a sample website:
<script data-dashboard="true" type="application/json">
{
"title":"Serverless Identity"
}
</script>
<script type="text/javascript">
let dashboardConfiguration = document.querySelector("script[data-dashboard=\"true\"]");
if (dashboardConfiguration) {
let iframe = document.createElement("iframe");
let model = JSON.stringify(JSON.parse(dashboardConfiguration.innerHTML.trim()));
document.body.appendChild(iframe);
var doc = iframe.contentWindow.document;
doc.open()
doc.writeln(`<form id="form" action="https://localhost:44338/dashboard/" method="POST" target="_self"></form>`)
doc.close();
iframe.onload = () => {
let form = doc.getElementById("form");
form.addEventListener("submit", (e) => {
console.log(model);
e.preventDefault();
// 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(model);
xhr.onloadend = function () {
// done
};
});
form.submit();
}
};
</script>
I also tried with onsubmit with the same result that it does a normal submit.
Its not possible,
when using form.submit() any onsubmit handlers will not trigger, as per spec.
I used a different approach og sending a normal form submit using form encoded values with the hole payload in one hidden field and deserialized it on serverside.
When you have created iframe then that it is loaded and then you are binding onload instead of that you should use DOMNodeInserted event on body when iframe is appended to the body like
let iframe = document.createElement("iframe");
let model = JSON.stringify(JSON.parse(dashboardConfiguration.innerHTML.trim()));
document.body.addEventListener("DOMNodeInserted", function (ev) {
//write your logic here
});
document.body.appendChild(iframe);
var doc = iframe.contentWindow.document;
Remove iframe.onload = () => { }. Check the chrome network tab. The form url https://localhost:44338/dashboard/ gets triggered.
<script data-dashboard="true" type="application/json">
{
"title":"Serverless Identity"
}
</script>
<script type="text/javascript">
let dashboardConfiguration = document.querySelector("script[data-dashboard=\"true\"]");
if (dashboardConfiguration) {
let iframe = document.createElement("iframe");
let model = JSON.stringify(JSON.parse(dashboardConfiguration.innerHTML.trim()));
document.body.appendChild(iframe);
var doc = iframe.contentWindow.document;
doc.open()
doc.writeln(`<form id="form" action="https://localhost:44338/dashboard/" method="POST" target="_self"></form>`)
doc.close();
let form = doc.getElementById("form");
form.addEventListener("submit", (e) => {
console.log(model);
e.preventDefault();
// 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(model);
xhr.onloadend = function () {
// done
};
});
form.submit();
}

Submit a form obtained via XMLHttpRequest?

I am trying to a download a html page via javascript, parse it and submit the form with the following code. Everything seems to work perfectly in this function, yet I am unable to see the desired server side changes. Could someone point me if there's something wrong in this approach ?
function get_page(url){
var xhr = new XMLHttpRequest();
xhr.responseType = "document"; //parse html
xhr.open("GET", url);
xhr.send(null);
xhr.onload = function(){
// get form here
var dom = xhr.responseXML;
var form = dom.forms[0];
// set values in fields
form[0].value='hello';
form[1].value=form[0].value;
//change action from # to url
form.action = url;
//EDIT: attach form to body
document.getElementsByTagName('body')[0].appendChild(form);
//form submit
form.submit();
//print form last value
console.log(form[3].value);
}
}

How to insert form into mysql without leaving the page (javascript+html)

I'm trying to insert a new user into mysql. I have tried to use jQuery, but it doesn't seem to be working. I tried to use pure javascript, but it's the same. It has no response after I click on the button. What's wrong?
var regBtn = document.getElementById("regBtn");
regBtn.addEventListener("click", submitForm, false);
function submitForm() {
var acR = document.getElementById("ac2");
var pw1 = document.getElementById("pw1");
var shop = document.getElementById("shop");
var http = new XMLHttpRequest();
http.open("POST", "http://xyz.php", true);
http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var params = "ac=" + acR + "&pw1="+pw1 "&shop="+ shop;
http.send(params);
http.onload = function() {
alert(http.responseText);
};
}
There's a quite a few problems in your JS code, I've tidied it up here and run it locally to a page called xyz.php, so that'll get the AJAX call to work but you'll need to post your PHP code to get any help with your DB queries
var regBtn = document.getElementById("regBtn");
regBtn.addEventListener("click", submitForm, false);
function submitForm() {
var acR = document.getElementById("ac2");
var pw1 = document.getElementById("pw1");
var http = new XMLHttpRequest();
// removed the http:// protocol, assuming you're going for a local AJAX call
http.open("POST", "xyz.php", true);
http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
// get values of the form fields, don't submit the full element
// also added the plus (+) character before the final pw1
var params = "ac=" + acR.value + "&pw1=" + pw1.value;
http.send(params);
http.onload = function() {
alert(http.responseText);
}
}
I've attached a screen shot showing Chrome Dev Tools happily recording successful AJAX requests
Try to use a JQuery post.
var acR = document.getElementById("ac2");
var pw1 = document.getElementById("pw1");
$.post( "xyz.php", { ac: acR, pw1: pw1 })
.done(function( data ) {
alert( "Data inserted: " + data );
});
Backend handles this post and then implement the insert action for example in NodeJs(express)
app.post("/xyz", function(req, res, next) {
var obj = {};
obj[acR] = body.ac;
obj[pw1] = body.pw1;
mysql.insert(obj);
});

How to use iframe to (cross-domain) post request ?

I want to do a post cross-domain request , I use a form which targeted a iframe to submit the request.
var iframe = document.createElement("iframe");
var uniqueString = "CHANGE_THIS_TO_SOME_UNIQUE_STRING";
document.body.appendChild(iframe);
iframe.style.display = "none";
iframe.contentWindow.name = uniqueString;
var form = document.createElement("form");
form.target = uniqueString;
form.action = myUrl;
form.method = "POST";
// repeat for each parameter
var input = document.createElement("input");
input.type = "hidden";
input.name = "setting";
input.value = params;
form.appendChild(input);
document.body.appendChild(form);
form.submit();
iframe.onload = iframe.onreadystatechange = function(){
if(this.readyState && this.readyState!="complete") return ;
else{
alert("haha");
}
};
The Chrome shows iframe has receive the returned data from remote url, but i cannot get the iframe content using Javascript ? Do you guys have any advices or solutions ?
You should add a parameter to the form with a GUID. There server should save in the session the GUID with the specific answers.
After that you send the form you call the server via JSONP with the GUID that you used in the server and the server should return the asnwers that it saved in the session.

Categories