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
Related
I have variable _randNum in JavaScirpt which generate random number between 1 and 50.
I need to select some data from database depending on value of this variable.
I've used following JavaScript code to select data from database via PHP (but without sending JavaScript variable to PHP).
// handles the click event for link 1, sends the query
function getSuccessOutput() {
getRequest(
'questions.php', // demo-only URL
drawOutput,
drawError
);
return false;
}
// handles drawing an error message
function drawError () {
var container = document.getElementById('output');
container.innerHTML = 'Bummer: there was an error!';
}
// handles the response, adds the html
function drawOutput(responseText) {
$.getJSON("questions.php", function(theObject){
var d1 = theObject.data1; // Get the data from PHP
var d2 = theObject.data2;
}
// helper function for cross-browser request object
function getRequest(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req .readyState == 4){
return req.status === 200 ?
success(req.responseText) : error(req.status)
;
}
}
req.open("GET", url, true);
req.send(null);
return req;
}
How can I send _randNum variable's value to PHP?
In PHP I could do something like that:
$rnd = mysqli_real_escape_string($con, $_POST['randNum']);
But no clue, how to send It from Javascript in same function.
I could create function like this:, but how to use It correctly with getSuccessOutput() function?
function sendFtId() {
$.post( "questions.php", { randNum : _randNum })
.done(function( data ) {
});
}
Have you any ideas?
You can use isset function to check any post request is coming or not.
E.g:
function getSuccessOutput($randNum) {
echo $randNum;
}
if(isset($_POST['randNum'])){
getSuccessOutput($_POST['randNum']);
}
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/
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'
I'm building a building a website using the Reddit API to display images from Reddit.
I'm getting the data via JSON then use it to build the page, using URLs provided as sources for the images.
Some of the URLs that I get don't go to images directly, but instead to image hosting sites (like imgur.com). Usually, adding '.jpg' at the end of the URL takes me to the right image.
So, doing that, I would like to check if the URL + '.jpg' exists before using it.
I tried to build a function to check the url.
function checkUrl(url){
var request = new XMLHttpRequest;
request.open('GET', url, true);
request.send();
request.onreadystatechange = function(){
if(request.readyState==4){
console.log(request.readyState);
return true;
}else{
return false;
}
}
};
//Then I use the function to check and append the data to the page
var url = url+'.jpg';
if(checkUrl(url)){
//work with the data
}else{
//do nothing
}
Nothing happens to the page, still I get the readyState logged into the console, so the checkUrl() function seems to be returning true.
What I am doing wrong ? I am pretty new to the whole Ajax thing, so some help would very appreciated.
Thank you
Your problem is that when request.readyState == 4 this means the request has completed, regardless of what the result of that request was. So even if the URL you request returns a "404 not found", you'll still see the XHR resolving itself to readyState 4.
To address what you're trying to do, I'd recommend checking the status code of the response. For example, using your code:
if(request.status==200){
return true;
}
Why your code won't work:
Your AJAX request is asynchronous, and if(checkUrl(url)){ will return null (false) as the function checkUrl() sends the AJAX request and immediately returns, before the AJAX call has completed.
Change
request.open('GET', url, true);
to
request.open('GET', url, false);
Also, move your request.send() to after the request.onreadystatechange() as now it is a non-async request.
request.onreadystatechange = function(){
if(request.readyState==4){
console.log(request.readyState);
return true;
}else{
return false;
}
}
request.send();
Or, you could simply place your check logic into the onreadystatechange function:
request.onreadystatechange = function(){
var url = url+'.jpg';
if(request.readyState==4){
//work with the data
}else{
//do nothing
}
}
I believe your problem is misunderstanding of AJAX; AJAX is basically asynchronous, and that's why the behavior you are describing.
I've used the following to get a simple true/false indication whether a URL is valid, in a synchronous manner:
function isValidURL(url) {
var encodedURL = encodeURIComponent(url);
var isValid = false;
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22" + encodedURL + "%22&format=json",
type: "get",
async: false,
dataType: "json",
success: function(data) {
isValid = data.query.results != null;
},
error: function(){
isValid = false;
}
});
return isValid;
}
The usage is then trivial:
var isValid = isValidURL("http://www.wix.com");
alert(isValid ? "Valid URL!!!" : "Damn...");
Hope this helps
The return value of request.reonreadystatechange is not the return value of checkUrl. Try this:
function checkUrl(url){
var request = new XMLHttpRequest;
request.open('GET', url, true);
request.send();
request.onreadystatechange = function(){
if(request.readyState==4){
console.log(request.readyState);
// perform your data manipulation here
// don't separate it with the request
}
}
};
On Safari, ActiveXObject will work fine, compared to XMLHttpRequest:
function isThere(url)
{
var req= new AJ(); // XMLHttpRequest object
try {
req.open("HEAD", url, false);
req.send(null);
//alert(req.status); //un-comment if need alert for status code
return req.status== 200 ? true : false;
}
catch (er) {
//alert ('ERROR:'); // un-comment if need alert for error
return false;
}
}
function AJAX()
{
var obj;
if (window.XMLHttpRequest) obj= new XMLHttpRequest();
else if (window.ActiveXObject)
{
try
{
obj= new ActiveXObject('MSXML2.XMLHTTP.3.0');
}
catch(er)
{
try
{
obj= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(er)
{
obj= false;
}
}
}
return obj;
}