Ajax POST request without an html form and in pure JS - javascript

Is it possible to make an ajax post without having an HTML form? And if it is how should i do it and what PHP variable is used to fetch the variable? The PHP is inside the fetched file. I'm not using any framework.
function ajax(instruction, push, url, callback){
var xmlhttp; // the object for the httprequest
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() { // every time the readystate changes
ajaxLoad(xmlhttp.readyState); // Calls function with the ready state each time it uppdates
if (xmlhttp.readyState == 4) { // status 200 = sucessfull page! NOT 404! // 1 2 3 4 are states of the request (4 is when it's done)
// When load bar is complete
if(xmlhttp.status == 200){
callback(xmlhttp.responseText); // goes to the callback function (from the argument "callback") and then passes the xmlhttp
}
else if(xmlhttp.status == 404){ // Could not find file
ajaxError() // Function that will call the ajax but with the error file
}else{}
ajaxDone(); // activates all the nessesary js to check what to do with some parts of the site
}
else{}
};
xmlhttp.open(instruction,url, true); // sends a the var q to the next php file
if(instruction === "GET"){
xmlhttp.send(''); // Sends the request
}
else if(instruction === "POST"){
xmlhttp.send(url); // Sends the request
}
else{
console.log("This ajax does not support " + instruction + " requests.");
}
if(push == true){ // Change the link to the url of the ajax with
var urlPath = window.location.protocol + "//" + window.location.host + window.location.pathname; // where the host is on
if(url == "home.php"){ // If it's the starting page REMOVE THE ?p= !!
var urlPath = window.location.protocol + "//" + window.location.host + window.location.pathname;
window.history.pushState({path:urlPath},'','./'); // an empty url push (!REMOVE THE DOT WHEN THE SITE IS HOSTED PROPERLY)
return; // exit's the function
}else{}
var newLink = "?p=" + url; // Gives us the link we want except that we don't want the .php
newLink = newLink.substring(0, newLink.indexOf('.')); // makes a new string with character 0 to the dot! Will not include the ending of the file
window.history.pushState({path:urlPath},'',newLink); // the push
}
else{}
}
To page 1

You can find some answers here, about how to make Vanilla JS Ajax call:
http://www.sitepoint.com/guide-vanilla-ajax-without-jquery
About to send without forms, you already have the response here:
Send POST data using XMLHttpRequest
You can get your params server-side(php) with the global variables $_GET["your_param_name"] and $_POST["your_param_name"], they are arrays so I think you know how to use them.

Of course, you can make AJAX request in pure js, even jquery handle ajax request in pure js in behind.
JavaScript:
var ajax = {};
ajax.x = function () {
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
return xhr;
};
ajax.send = function (url, callback, method, data, async) {
if (async === undefined) {
async = true;
}
var x = ajax.x();
x.open(method, url, async);
x.onreadystatechange = function () {
if (x.readyState == 4) {
callback(x.responseText)
}
};
if (method == 'POST') {
x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
}
x.send(data)
};
ajax.get = function (url, data, callback, async) {
var query = [];
for (var key in data) {
query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
}
ajax.send(url + (query.length ? '?' + query.join('&') : ''), callback, 'GET', null, async)
};
ajax.post = function (url, data, callback, async) {
var query = [];
for (var key in data) {
query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
}
ajax.send(url, callback, 'POST', query.join('&'), async)
};
Call Ajax Method: I will recommend you to not use it in onclick.
ajax.get('ajax.php',{DATA_TO_PASS},function(response) {
//Do something with response
console.log(response);
},true);
$_GET to receive the ajax data;
OR:
ajax.post('ajax.php',{DATA_TO_PASS},function(response) {
//Do something with response
console.log(response);
},true);
$_PSOT to receive the ajax data;

You don't need a form to use ajax post.
$.post( "test.php", { 'choices[]': [ "Jon", "Susan" ] } );
as the same way you are using form you can fetch the values from php using $_POST

Related

Detect request url of an ajax request

So I have used the below function to detect an ajax call.
var oldXHR = window.XMLHttpRequest;
function newXHR() {
var realXHR = new oldXHR();
realXHR.addEventListener("readystatechange", function() {
if(realXHR.readyState==1){
alert('server connection established');
}
if(realXHR.readyState==2){
alert('request received');
}
if(realXHR.readyState==3){
alert('processing request');
}
if(realXHR.readyState==4){
alert('request finished and response is ready');
}
}, false);
return realXHR;
}
window.XMLHttpRequest = newXHR;
It is working but now I need the url of that particular ajax request. I have functions like below:-
function loadFundSimulation(num_days = ''){
var url = "<?php echo site_url('investment_plan/simulation/FUND'); ?>";
$.post(url, data).done(function (response,status,xhr) {
#....code....#
}).fail(function (data) {
#....code....#
});
}
When the ajax is being called at that time I want url of this functions. I have many functions like this. When I get the url I want to append ?debug = 1 at the end of the url. I have tried alert(this.url); but it was returning undefined. Any help will appreciated. Thanks in advance.
Edit
var open = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function(method, uri, async, user, pass) {
this.addEventListener("readystatechange", function(event) {
if(this.readyState == 4){
var self = this;
var response = {
method: method,
uri: uri,
responseText: self.responseText
};
response.uri = uri + '?debug=1';
console.log(response);
} else {
console.log(this.readyState);
}
}, false);
open.call(this, method, uri, async, user, pass);
};
I have got the url of that ajax request and I appended ?debug=1 as well. When I console.log(response); I see the url is being changed but I still don't see any error. Please let me know I have to do anything else for that.
After searching a lot this is the best way to do this. Though only tested on chrome.
(function() {
var proxied = window.XMLHttpRequest.prototype.open;
window.XMLHttpRequest.prototype.open = function() {
arguments[1] = arguments[1] + '&debug=1';
console.log( arguments[1] );
return proxied.apply(this, [].slice.call(arguments));
};
})();

Jena Fuseki not working when making an insert query from javascript. No Update parameter error

I have this JavaScript function which aims to insert a keyword in a named graph which belongs to the project Dataset.
function insert(keyword) {
var query = "INSERT DATA {GRAPH <http://test1> {<subj> <pred>'" + keyword + "'. }}";
var endpoint = "http://localhost:3030/project/update";
sparqlQueryJson(query, endpoint, showResults, true);
}
I have executed Jena Fuseki with the --update option. The sparqlQueryJson function is as follows:
function sparqlQueryJson(queryStr, endpoint, callback, isDebug) {
var querypart = "query=" + escape(queryStr);
// Get our HTTP request object.
var xmlhttp = null;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
// Code for older versions of IE, like IE6 and before.
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert('Perhaps your browser does not support XMLHttpRequests?');
}
// Set up a POST with JSON result format.
xmlhttp.open('POST', endpoint, true); // GET can have caching probs, so POST
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlhttp.setRequestHeader("Accept", "application/sparql-results+json");
// Set up callback to get the response asynchronously.
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
// Process the results
callback(xmlhttp.responseText);
} else {
// Some kind of error occurred.
alert("Sparql query error: " + xmlhttp.status + " " + xmlhttp.responseText);
}
}
};
xmlhttp.send(querypart);
};
The showResults function is, in my opinion, not very important here, since it takes the results of the query and show them in HTML.
I followed what is discussed here and here, executing the query using the http://localhost:3030/project/update. The thing is that if I execute the same query on top of the local Fuseki server with the same endpoint url by using the web, it works, but from the JavaScript code, it raises the error:
"SPARQL query error: 400 Error 400: SPARQL Update: No 'update=' parameter".
I'm using Ubuntu 16.04 and Jena Fuseki - version 2.4.1.
To solve this problem the =query parameter has to be changed to =update. In addition, a parameter with the type of the query has to be handled, i.e., update or query.
if(type==="update"){
var querypart = "update=" + escape(queryStr);
}else if(type === "query"){
var querypart = "query=" + escape(queryStr);
}
...
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
if(type==="query"){
xmlhttp.setRequestHeader("Accept", "application/sparql-results+json");
}

how to load json from url using javascript?

I'm new to javascript which should be really simple to solve, but I am lost as of now.
I have a url: http:getall.json
Using JavaScript (not JQuery or php. Just JavaScript), I want to read this JSON string and parse it. That's it.
access to your url doesn't work, you should show the JSON result. In javascript to get JSON object with AJAX request you can do something like this:
request = new XMLHttpRequest;
request.open('GET', 'http://v-apps-campaign.com/dunkindonuts/main/get_allStore', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400){
// Success!
data = JSON.parse(request.responseText);
} else {
// We reached our target server, but it returned an error
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send();
your result will be in the data variable.
JSONP calls:
function getJSONP(url, callback) {
var script = document.createElement('script');
var callbackName = "jsonpcallback_" + new Date().getTime();
window[callbackName] = function (json) {
callback(json);
};
script.src = url + (url.indexOf("?") > -1 ? "&" : "?") + 'callback=' + callbackName;
document.getElementsByTagName('head')[0].appendChild(script);
}
getJSONP("http://v-apps-campaign.com/dunkindonuts/main/get_allStore", function(jsonObject){
//jsonObject is what you want
});
Regular ajax ajax call:
function getXHR() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
}
try {
return new ActiveXObject('MSXML2.XMLHTTP.6.0');
} catch (e) {
try {
// The fallback.
return new ActiveXObject('MSXML2.XMLHTTP.3.0');
} catch (e) {
throw new Error("This browser does not support XMLHttpRequest.");
}
}
}
function getJSON(url, callback) {
req = getXHR();
req.open("GET", url);
req.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var jsonObject = null,
status;
try {
jsonObject = JSON.parse(req.responseText);
status = "success";
} catch (e) {
status = "Invalid JSON string[" + e + "]";
}
callback(jsonObject, status, this);
}
};
req.onerror = function () {
callback(null, "error", null);
};
req.send(null);
}
getJSON("http://v-apps-campaign.com/dunkindonuts/main/get_allStore", function (jsonObject, status, xhr) {
//jsonObject is what you want
});
I tested these with your url and it seems like you should get the data with a jsonp call, because with regular ajax call it returns:
No 'Access-Control-Allow-Origin' header is present on the requested resource
with jsonp it gets the data but the data is not a valid json, it seems your server side has some php errors:
A PHP Error was encountered
...
In your HTML include your json file and a js code as modules
<script src="/locales/tshared.js" type="module" ></script>
<script src="/scripts/shared.js" type="module" ></script>
file content of tshared
export const loc = '{"en": { "key1": "Welcome" },"pt": {"key1": "Benvindo"} }'
file content of shared
import {loc} from "./../../locales/tshared.js";
var locale = null;
locale = JSON.parse(loc) ;
Adapt path and names as needed, use locale at will.

XMLHttpRequest not adding header - "X-Requested-With: XMLHttpRequest"

I have an ajax call where I used jQuery.ajax() to make a request to an mvc action. This all worked fine. However due to some forms having a file control I changed it from using jQuery.ajax() to using the XMLHttpRequest to send it using the HTML5 File API.
Since making this change the MVC action method no longer see's it as an ajax request. Using Fiddler2 I have noticed that it no longer adds the "X-Requested-With: XMLHttpRequest" to the request and I assume this is the problem.
The form I am trying to send does not have a file input in it, only normal textboxes etc, but I was trying to keep the method generic to deal with both. The following is the code I am using to send the ajax request:
// get the edit tender form
var $Form = $Button.closest('form');
var Url = $Form.attr('action');
var AjaxRequestObject = new XMLHttpRequest();
var FormDataToSend = new FormData();
$Form.find(':input').each(function () {
if ($(this).is('input[type="file"]')) {
var files = $(this)[0].files;
if (files.length > 0) {
FormDataToSend.append(this.name, files[0]);
}
} else {
FormDataToSend.append(this.name, $(this).val());
}
});
AjaxRequestObject.open('POST', Url, true);
AjaxRequestObject.onreadystatechange = function () {
if (AjaxRequestObject.readyState == 4) {
// handle response.
if (AjaxRequestObject.status == 200) {
if (!AjaxErrorExists(AjaxRequestObject.responseText, )) {
alert("success");
console.log(AjaxRequestObject.responseText);
}
else {
alert('failure');
}
}
else {
alert('failure');
}
}
};
AjaxRequestObject.send(FormDataToSend);
This code was provided following a problem I had which Darin Dimitrov provided the solution to, so I could send the file inputs by ajax.
Any ideas why this request would not send the header for an ajax call?
X-Requested-With is automatically added by jQuery. You can just as easily add it yourself with AjaxRequestObject.setRequestHeader(). Docs
I was having troubles with detecting if my request was ajax. So, maybe this sample will save someone a minute or two:
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', URL, true); // `true` for async call, `false` for sync.
// The header must be after `.open()`, but before `.send()`
xmlhttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xmlhttp.onreadystatechange = function() {
// 4th state is the last:
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { ... }
};
xmlhttp.send();
Tested with Flask.
You can override natively all XMLHttpRequest.open method calls and add in it X-Requested-With header like:
(function () {
// #author https://github.com/stopsopa jfdsa78y453cq5hjfd7s877834h4h3
if (window.XMLHttpRequest.prototype.onOpen) {
return console.log('XMLHttpRequest.onOpen is already defined');
}
function over(method, on, off) {
var old = window.XMLHttpRequest.prototype[method];
if (!old.old) {
var stack = [];
window.XMLHttpRequest.prototype[on] = function (fn) {
if (typeof fn === 'function') {
stack.push(fn);
}
}
window.XMLHttpRequest.prototype[off] = function (fn) {
for (var i = 0, l = stack.length ; i < l ; i += 1 ) {
if (stack[i] === fn) {
stack.splice(i, 1);
break;
}
}
}
window.XMLHttpRequest.prototype[method] = function () {
var args = Array.prototype.slice.call(arguments);
var ret = old.apply(this, args);
for (var i = 0, l = stack.length ; i < l ; i += 1 ) {
stack[i].apply(this, args);
}
return ret;
}
window.XMLHttpRequest.prototype[method].old = old;
}
}
over('open', 'onOpen', 'offOpen')
XMLHttpRequest.prototype.onOpen(function () {
this.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
});
}());

Checking result of an html form using javascript

I am using an html form to upload a file to my server. I want to execute a javascript function only after the form has been submitted and the file has been successfully uploaded. The form opens a new page with the text "upload succeeded" if the file upload worked. I tried using a while loop that would loop until the file was found in the database but it crashed my browser. How can I do this? I'm using myform.submit() to submit my form right now.
If the post went well, and you save the file before flushing the page contents, this is easy. The page won't return until the post cycle is ready, so you could insert javascript code to the page after the saving of the file.
You can use AJAX to upload you file and you the async return function (this is a event that will trigger when your request is done) to ether a success or failed message from you php.
EDIT:
Here is a ajax function iv made that u can use, just load this in an extenal file:
var ajax = function(data){
// Return false is no url... You need an url to get url data..
if(typeof data.url !== 'undefined'){
var url = data.url;
// Adept the function depending on your method
if(data.method === 'GET' && data.params !== 'undefined'){
url+='?'+data.params;
}
}else{
return(false);}
var // Set some vars 'n' stuff
method = ( data.method === 'GET') ? 'GET' : 'POST',
params = (typeof data.params !== 'undefined') ? data.params : null,
async = ( data.async === true) ? true : false,
done = (typeof data.done === 'function') ? data.done : false,
return_value = null,
length = (data.method === 'POST') ? data.method.length : '';
var // Find out what ajax methods the browser support
request_method = function(){
var xmlhttp = false;
try {
xmlhttp = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
xmlhttp = false;
}
}
}
return xmlhttp;
}// This thing connet to the server
connect = function(){
if(request = request_method()){}else{
return(false);
}
request.open(method, url, async);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.setRequestHeader("Content-length", length);
request.setRequestHeader("Connection", "close");
request.send(params);
request_handle(request);
},// This is where the result get processed
request_handle = function(request){
if(async){
request.onreadystatechange = function() {
if(request.readyState === 4 && request.status === 200) {
done(data);
}
}
}else{
done(data);
}
};
connect();
return(return_value);
}
usage:
ajax({
url: 'test.php',
//// Your ajax request url // no default // Must be set!
method: 'POST',
//// Method of sending ajax data // default is POST
async: true,
//// What to do when done with the request // no default
done: function(http){
table(http,'test');
}
});
one simple thing you can do
use executescalar to insert uploading file as soon as it inserts the file return boolean value to check whether it is inserted,if so then set hiddenfield value. in javascript check the value of the hiddenfield and according to that you can call your javascript function

Categories