So, TideSDK say that php is preprocessed upon each request (if it's a .php file).
I'm using the following JS ajax:
function ajax(url, method, data, async)
{
method = typeof method !== 'undefined' ? method : 'GET';
async = typeof async !== 'undefined' ? async : false;
if (window.XMLHttpRequest)
{
var xhReq = new XMLHttpRequest();
}
else
{
var xhReq = new ActiveXObject("Microsoft.XMLHTTP");
}
if (method == 'POST')
{
xhReq.open(method, url, async);
xhReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhReq.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhReq.send(data);
}
else
{
if(typeof data !== 'undefined' && data !== null)
{
url = url+'?'+data;
}
xhReq.open(method, url, async);
xhReq.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhReq.send(null);
}
return xhReq.responseText;
console.log("[ajax] Request Completed.");
}
and my index.php file is:
<?php echo "Test"; ?>
ajax is called as such
console.log(ajax('index.php', 'GET'));
Instead of returning 'Test' it just returns the source code.
Am I doing something wrong, or is this expected. Other-wise, what could I do too get the expected output: the pre processed PHP.
If you want to do a ajax get request on your php script, use the jQuery ajax method.
RTM: http://api.jquery.com/jquery.ajax/
Example GET Request:
$(document).ready(function()
{
$.get("index.php", function(data) {
console.log(data);
});
});
Example POST Request:
$(document).ready(function()
{
$.ajax({
type: "POST",
url: "index.php",
data: { "test": "hello world", "anotherkey": "andvalue" },
success: function(data) {
console.log(data);
}
});
});
// usage in php: $post_test = $_POST['test']; // returns 'hello world'
Related
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
I tried to solve WebGoat prompt bypass using javascriptcode depending on XMLHttpRequet to send multiple requests of different types, since the first request is of GET type and the second one is of POST type.
The code is:
<script>
var req1 = new XMLHttpRequest();
req1.onreadystatechange = function() {
if (req1.readyState == 4 && req1.status == 200) {
req2 = new XMLHttpRequest();
req2.open("POST", "http://localhost:8080/WebGoat/attack?Screen=32&menu=900", false);
req2.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); //shoud be specified in the POST requests
req2.send("transferFunds=CONFIRM");
}
};
req1.open("GET", "http://localhost:8080/WebGoat/attack?Screen=32&menu=900&transferFunds=4000", false);
req1.send();
</script>
When saving this code as htmlfile and opening it then monitoring the requests no any requests appeared except the GET one and it's status is 302. What should I do for this code to be executed successfully?
Browser is : Firefox 40.0.3
WebGoat Version: 6.0.1
You might try chaining requests.
Executes first request, if the «callback function» returns 200 ok, then executes the next request.
I've made an example.
(function() {
// Implements XMLHttpRequest object to use in requests.
function sendServer(options) {
var newXHR = new XMLHttpRequest() || new ActiveXObject("Microsoft.XMLHTTP");
options.async = true;
options.contentType = options.contentType || "application/x-www-form-urlencoded";
newXHR.open(options.type, options.url, options.async || true);
newXHR.setRequestHeader("Content-Type", options.contentType);
newXHR.send((options.type == "POST") ? options.data : null);
newXHR.onreadystatechange = options.callback;
return newXHR;
}
// Usage:
// First request: GET
sendServer({
type: "GET",
url: "http://localhost:8080/WebGoat/attack?Screen=32&menu=900&transferFunds=4000",
data: null,
async: false,
callback: function(xhr) {
if (xhr.target.readyState === 4 && xhr.target.status === 200) {
// Second request: POST
sendServer({
type: "POST",
url: "http://localhost:8080/WebGoat/attack?Screen=32&menu=900",
data: "transferFunds=CONFIRM",
async: false,
callback: function(xhr) {
if (xhr.target.readyState === 4 && xhr.target.status === 200) {
console.log(xhr.target.responseText); // Checks the response.
}
}
});
}
}
});
})();
Reference: http://jsfiddle.net/dannyjhonston/jppz5nk3/1/
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.
I need to get data from webservice url in javascript. i"m getting the response code as 200 but dont get any data from the url.
Following is the code
var xmlDoc = null;
url = 'http://localhost:8458/service1.svc/geturl';
if (window.XMLHttpRequest) {
xmlDoc = new XMLHttpRequest(); //Newer browsers
}
else if (window.ActiveXObject) //IE 5, 6
{
xmlDoc = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlDoc) {
xmlDoc.onreadystatechange = function () {
if (xmlDoc.readyState == 4 && xmlDoc.status === 200) {
alert(xmlDoc.responseText);
}
}
xmlDoc.open("GET", url, true);
xmlDoc.send();
and the service which i have written returns the string
I would suggest using jQuery for this:
var request_url = 'http://localhost:8458/service1.svc/geturl';
$.ajax({
url: request_url,
type: "POST",
dataType: "html",
success: function(response){
// Do something with your response here
alert(response);
}
});
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