How to update XML file using Ajax + Jquery? - javascript

I want to update the XML file using Ajax & jquery. I am new to ajax so tried with using both POST/PUT.
For PUT: I am getting the error 405. i.e "Method Not Found"
For POST: Bad Request
vvmsUrl: is the path to xml file
Our get is working fine, but not the PUT/POST.
PUT Code:
vvmsUrl: is the path to xml file
var XMLData= "<origin>ABCbfk</origin>";
jQuery.ajax({
type: "PUT",
url: vvmsUrl,
contentType: "application/xml",
headers: { 'Prefer' : 'persistent-auth',
'Access-Control-Allow-Methods': 'PUT'},
dataType: "xml",
processData: false,
crossDomain: true,
data: XMLData,
success:function(msg)
{
alert("hello"+msg);
},
error: function(msg){
alert("Error"+msg);
LOG(xhr.status);
}
});
I am stuck from 2 days. I am not getting what goes wrong in this.

You can try : upload any file
HTML code
<input type="file" id="uploadfile" name="uploadfile" />
<input type="button" value="upload" onclick="upload()" />
Javascript code
<script>
var client = new XMLHttpRequest();
function upload()
{
var file = document.getElementById("uploadfile");
/* Create a FormData instance */
var formData = new FormData();
/* Add the file */
formData.append("upload", file.files[0]);
client.open("post", "/upload", true);
client.setRequestHeader("Content-Type", "multipart/form-data");
client.send(formData); /* Send to server */
}
/* Check the response status */
client.onreadystatechange = function()
{
if (client.readyState == 4 && client.status == 200)
{
alert(client.statusText);
}
}
</script>

You need a server side script to handle modifications to anything at the server you cannot just use client side jQuery. The script will also check who is authorized to write to the file or otherwise anyone can modify/update your XML file which is a security problem and probably is what you don't want.
Please could you include all of your code? I mean what is vvmUrl ? Are you using some web service? Is your code making call to another domain, why crossDomain: true?
EDIT:
This should work in jQuery 1.7.2+
var username = 'myUser';
var password = 'myPassword';
$.ajax
({
type: "PUT",
url: vvmsUrl,
contentType: 'application/xml',
async: false,
crossDomain: true,
username: username,
password: password,
data: xmlData,
success: function (){
alert('Works!');
}
});

Related

NodeJS: how to perform Ajax Post with FormData

I am testing a local HTML Form sending data to an aspx application as backend. Since I have some problem with CORS (even on localhost) I am trying to emulate the Ajax request performed by jQuery with NodeJS. I don't know if this is the right way to do. In the HTML form, after the jQuery validation, this is what I do:
submitHandler: function(form) {
$.ajax({
url: form.action,
type: form.method,
data: $(form).serialize(),
success: function(response) {
console.log(response);
}
});
//console.log($(form).serialize())
}
and it works, until CORS ends the request. I mean that I can retrieve the data from the backend application.
Instead, if I do:
function loadDoc() {
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhttp = new XMLHttpRequest();
/*var FormData = require('form-data');
var myform = new FormData();
myform.append('firstname', 'foo');*/
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}
};
xhttp.open("POST", "http://127.0.0.1:1308/ImperoOrdini/ImperoOrdini.aspx?CMD=NUOVOORDINE", true);
//which is the same string I get from .serialize() in jQuery
xhttp.send("firstname=foo&email=some#domain.it");
}
loadDoc();
I cannot get anything from the server application. If I want to get the parameter firstname from the POST data, I get null. So, where am I wrong?
UPDATE
This is the only workaround I have found useful in NodeJS:
var http = require('http');
var querystring = require('querystring');
var post_data = querystring.stringify({'firstname':'Lory'});
var post_options = {
host: 'localhost',
port: '1308',
path: '/ImperoOrdini/ImperoOrdini.aspx?CMD=NUOVOORDINE',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(post_data)
}
};
// Set up the request
var post_req = http.request(post_options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('Response: ' + chunk);
});
});
// post the data
post_req.write(post_data);
post_req.end();
I had also tried with:
var request = require('ajax-request');
request.post({
url: 'http://127.0.0.1:1308/ImperoOrdini/ImperoOrdini.aspx?CMD=NUOVOORDINE',
data: {'firstname':'Lory'},
headers: {}
}, function(err, res, body) {
console.log(res);
}
);
but it did not work too. I feel such an ignorant and I would like to know the differences between those 3 libraries.
I have some doubts concerning the fact I must use querystring.stringify() in the working solution, because POST data are not in the URL and should not be uder the limits of query string, if I remember well.
I would like to suggest request module. while doing ajax call post, we can post the data by form or JSON format. It's based on receiver end point how they are receiving.
I hope you are trying to post form data.
var request = require('request');
request.post({
url:'http://service.com/upload',
form: {'firstname':'Lory'}
}, function(err,httpResponse,body){
/* ... */
})
If you are trying to do normal JSON post.
var request = require('request')
request({
method: 'POST',
uri: 'http://www.google.com',
body:{'firstname':'Lory'}
}, function(err,httpResponse,body){
/* ... */
})
request module provide lots of options. Play with that then you will get the better idea.
<html>
<head>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
</head>
<body>
<form id="myForm" name="myForm">
<div>
<label for="comment">Comment:</label>
<textarea id="comment" name="comment"></textarea>
</div>
<div>
<label for="rating">Comment:</label>
<textarea id="rating" name="comment"></textarea>
</div>
<input type="submit" value="Submit!">
</form>
<script>
$(document).ready(function () {
$('form').submit(function (event) {
event.preventDefault();
//collect the form data using Id Selector what ever data you need to send to server
let comment=$('#comment').val();
let rating= $('#rating').val()
$.ajax({
url: 'replace your url',
data: JSON.stringify({"comment": comment, "rating": rating }),
processData: false,
type: 'POST',
contentType: 'application/json',
success: function (data) {
alert(data);
}
});
});
})
</script>
</html>

How can I put ajax in global js?

My view like this :
<input type="file" style="display: none" id="test">
When the file called, it will call ajax
I put my ajax in main.js (myshop\resources\assets\js\main.js)
It is global js. I put all my js there. I also put my ajax there
I put my ajax in main.js like this :
var _token = $('input[name="_token"]').val();
console.log(_token);
$('#test').on("change", function(){
data = new FormData();
$.ajax({
url: window.Laravel.baseUrl+'/product/addImage',
type: "POST",
data: { data: data, _token: _token },
enctype: 'multipart/form-data',
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
}).done(function(data) {
console.log(data);
});
});
My routes like this :
Route::post('product/addImage', 'ProductController#addImage');
My controller like this :
public function addImage(Request $request)
{
dd('test');
// dd($request->all());
}
When executed, the console tab exist error like this :
POST http://myshop.dev/product/addImage 500 (Internal Server Error)
and on the network tab exist error like this :
TokenMismatchException in VerifyCsrfToken.php line 68:
How can I solve the error?
Whether ajax can be placed in global js?
You can resolve this issue in two ways:
You could use
<meta name="csrf-token" content="{{ csrf_token() }}" /> // add this under head tag
And before Ajax call add this:-
$.ajaxSetup({
headers:
{
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Or the other (simpler) way, inside your app\Http\Middleware/VerifyCsrfToken.php add
protected $except = [
'product/addImage',
];
Hope it helps!
Remember to add file to data
data = new FormData();
data.append("test", $("#fileInput")[0].files[0])

Stripe with Google App Engine - Upload image directly through browser using Javascript for Mananaged Account Identity Verification

Hi I've been searching for ages about how to upload directly from the browser, as is suggested in the case of using Stripe with Google App Engine at this forum. Also the Stripe documentation suggests it is possible to upload directly from a browser as is suggested here.
I have been trying with AJAX but from my effort and research it seems it is not possible to get the path to the local file because of security reasons. The code below shows the closest I've gotten, however I don't know how to upload an image through the browser without it touching the server. The console returns an error of "Invalid file: must be uploaded in a multipart/form-data request".
Next I will try using Jquery Form Plugin, however I don't know if I will have any success with that.
var formData = new FormData($('#theHTMLForm')[0]);
var sendarray={purpose:"identity_document", file:formData};
sendarray=JSON.stringify(sendarray);
$.ajax({
type:'POST',
url: 'https://uploads.stripe.com/v1/files',
data: sendarray,
mimeType: "multipart/form-data",
headers: {
"Authorization": "Bearer STRIPEPUBLISHABLEKEY"
},
contentType: 'application/json',
processData: false,
success:function(data){
alert('success');
console.log(data);
},
error: function(data){
alert('error');
console.log(data);
}
});
Thanks to a very kind person on this forumn, I was able to make it work!! I'll copy the answer here just in case anybody comes by looking for the same answer.
HTML
<div>
<form method="post" id="fileinfo" name="fileinfo" ajax="true">
<input type="file" id="file-box" name="file" required />
<input type="submit" value="Upload" />
</form>
</div>
<div>
<div id='label-results'>...</div>
<pre id="upload-results"></pre>
</div>
And Javascript
$('#fileinfo').submit(function(event) {
event.preventDefault();
var data = new FormData();
var publishableKey = 'pk_test_***';
data.append('file', $('#file-box')[0].files[0]);
data.append('purpose', 'identity_document');
$.ajax({
url: 'https://uploads.stripe.com/v1/files',
data: data,
headers: {
'Authorization': 'Bearer ' + publishableKey
},
cache: false,
contentType: false,
processData: false,
type: 'POST',
}).done(function(data) {
$('#label-results').text('Success!');
$('#upload-results').text(JSON.stringify(data, null, 3));
}).fail(function(response, type, message) {
$('#label-results').text('Failure: ' + type + ', ' + message);
$('#upload-results').text(JSON.stringify(response.responseJSON, null, 3));
});
return false;
});

Django + Ajax | File Upload | Server doesn't recognise Ajax Request

I am trying to implement file upload using ajax with Django but facing some problem.
When the user tries to upload the files after selecting the file and submitting the form, then as per my understanding , an ajax request should be send to the server using POST method ,but in my case a POST request is being made to the server, but the server is not able to identify it as an ajax request and browser is redirected to http://<server>:<port>/upload/ and the contents on this page are as follows.
{"status": "error", "result": "Something went wrong.Try Again !!"}
Django Version: 1.6.2
Python Version: 2.7.5
Also, testing on Django Development Server.
views.py
def upload(request):
logging.info('Inside upload view')
response_data = {}
if request.is_ajax():
logging.info('Is_AJAX() returned True')
form = UploaderForm(request.POST, request.FILES)
if form.is_valid():
logging.info('Uploaded Data Validated')
upload = Upload( upload=request.FILES['upload'] )
upload.name = request.FILES['upload'].name
upload.save()
logging.info('Uploaded Data Saved in Database and link is %s' % upload.upload)
response_data['status'] = "success"
response_data['result'] = "Your file has been uploaded !!"
response_data['fileLink'] = "/%s" % upload.upload
return HttpResponse(json.dumps(response_data), content_type="application/json")
response_data['status'] = "error"
response_data['result'] = "Something went wrong.Try Again !!"
return HttpResponse(json.dumps(response_data), content_type='application/json')
Template
<form id="uploadForm" action="/upload/" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input id="fileInput" class="input-file" name="upload" type="file">
<input type="submit" value="Post Images/Files" />
</form>
Javascript 1:
$('#uploadForm').submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: '/upload/',
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
Javascript 2
var options = {
url: '/upload/',
type: "POST",
error: function(response) {
alert('Something went Wrong. Try Again');
},
success: function(response) {
if ( response.status == 'success' ) {
alert('success');
}
}
};
$('#uploadForm').ajaxSubmit(options);
Question:
1) Why is Django not able to recognize the ajax request and value of request.is_ajax() is always False.
2) Even if the server doesn't recognize ajax request why is my browser getting redirected to another page ?
There is another similar question here but with no result.
This works for me. You need a jquery.form.js
$("#uploadForm").submit(function(event) {
$(this).ajaxSubmit({
url:'{% url upload_file %}',
type: 'post',
success: function(data) {
console.log(data)
},
error: function(jqXHR, exception) {
console.log("An error occurred while uploading your file!");
}
});
return false;
});
Here's the similar question here with answers.
Make sure that javascript code block
$('#uploadForm').submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: '/upload/',
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
loaded after your uploadForm html form in DOM on page. In your case seems you trying to bind submit handler with form element which not yet loaded so when you click, it send simple POST request.
1) why is_ajax() not working?
Have you included the JQuery form plugin (jquery.form.js) ? ajaxSubmit() needs that plugin.
Take a look at http://jquery.malsup.com/form/
If it's already done, you might take a look at the HTTPRequest object
Django Documentation says HttpRequest.is_ajax()
Returns True if the request was made via an XMLHttpRequest. And if you are using some javascript libraries to make the ajax request, you dont have to bother about this matter. Still you can verify "HTTP_X_REQUESTED_WITH" header to see if Django received an XMLHttpRequest or not.
2) Why page redirects?
As I said above, JQuery form plugin is needed for handling the ajax request and its call back. Also, for ajaxSubmit() you need to override the $(#uploadForm).submit()
$('#uploadForm').submit( function (){
$(this).ajaxSubmit(options);
return false;
});
Hope this was helpful :)

File Upload without Form

Without using any forms whatsoever, can I just send a file/files from <input type="file"> to 'upload.php' using POST method using jQuery. The input tag is not inside any form tag. It stands individually. So I don't want to use jQuery plugins like 'ajaxForm' or 'ajaxSubmit'.
You can use FormData to submit your data by a POST request. Here is a simple example:
var myFormData = new FormData();
myFormData.append('pictureFile', pictureInput.files[0]);
$.ajax({
url: 'upload.php',
type: 'POST',
processData: false, // important
contentType: false, // important
dataType : 'json',
data: myFormData
});
You don't have to use a form to make an ajax request, as long as you know your request setting (like url, method and parameters data).
All answers here are still using the FormData API. It is like a "multipart/form-data" upload without a form. You can also upload the file directly as content inside the body of the POST request using xmlHttpRequest like this:
var xmlHttpRequest = new XMLHttpRequest();
var file = ...file handle...
var fileName = ...file name...
var target = ...target...
var mimeType = ...mime type...
xmlHttpRequest.open('POST', target, true);
xmlHttpRequest.setRequestHeader('Content-Type', mimeType);
xmlHttpRequest.setRequestHeader('Content-Disposition', 'attachment; filename="' + fileName + '"');
xmlHttpRequest.send(file);
Content-Type and Content-Disposition headers are used for explaining what we are sending (mime-type and file name).
I posted similar answer also here.
UPDATE (January 2023):
You can also use the Fetch API to upload a file directly as binary content (as also was suggested in the comments).
const file = ...file handle...
const fileName = ...file name...
const target = ...target...
const mimeType = ...mime type...
const promise = fetch(target, {
method: 'POST',
body: file,
headers: {
'Content-Type': mimeType,
'Content-Disposition', `attachment; filename="${fileName}"`,
},
},
});
promise.then(
(response) => { /*...do something with response*/ },
(error) => { /*...handle error*/ },
);
See also a related question here: https://stackoverflow.com/a/48568899/1697459
Step 1: Create HTML Page where to place the HTML Code.
Step 2: In the HTML Code Page Bottom(footer)Create Javascript: and put Jquery Code in Script tag.
Step 3: Create PHP File and php code copy past. after Jquery Code in $.ajax Code url apply which one on your php file name.
JS
//$(document).on("change", "#avatar", function() { // If you want to upload without a submit button
$(document).on("click", "#upload", function() {
var file_data = $("#avatar").prop("files")[0]; // Getting the properties of file from file field
var form_data = new FormData(); // Creating object of FormData class
form_data.append("file", file_data) // Appending parameter named file with properties of file_field to form_data
form_data.append("user_id", 123) // Adding extra parameters to form_data
$.ajax({
url: "/upload_avatar", // Upload Script
dataType: 'script',
cache: false,
contentType: false,
processData: false,
data: form_data, // Setting the data attribute of ajax with file_data
type: 'post',
success: function(data) {
// Do something after Ajax completes
}
});
});
HTML
<input id="avatar" type="file" name="avatar" />
<button id="upload" value="Upload" />
Php
print_r($_FILES);
print_r($_POST);
Basing on this tutorial, here a very basic way to do that:
$('your_trigger_element_selector').on('click', function(){
var data = new FormData();
data.append('input_file_name', $('your_file_input_selector').prop('files')[0]);
// append other variables to data if you want: data.append('field_name_x', field_value_x);
$.ajax({
type: 'POST',
processData: false, // important
contentType: false, // important
data: data,
url: your_ajax_path,
dataType : 'json',
// in PHP you can call and process file in the same way as if it was submitted from a form:
// $_FILES['input_file_name']
success: function(jsonData){
...
}
...
});
});
Don't forget to add proper error handling
Try this puglin simpleUpload, no need form
Html:
<input type="file" name="arquivo" id="simpleUpload" multiple >
<button type="button" id="enviar">Enviar</button>
Javascript:
$('#simpleUpload').simpleUpload({
url: 'upload.php',
trigger: '#enviar',
success: function(data){
alert('Envio com sucesso');
}
});
A non-jquery (React) version:
JS:
function fileInputUpload(e){
let formData = new FormData();
formData.append(e.target.name, e.target.files[0]);
let response = await fetch('/api/upload', {
method: 'POST',
body: formData
});
let result = await response.json();
console.log(result.message);
}
HTML/JSX:
<input type='file' name='fileInput' onChange={(e) => this.fileInput(e)} />
You might not want to use onChange, but you can attach the uploading part to any another function.
Sorry for being that guy but AngularJS offers a simple and elegant solution.
Here is the code I use:
ngApp.controller('ngController', ['$upload',
function($upload) {
$scope.Upload = function($files, index) {
for (var i = 0; i < $files.length; i++) {
var file = $files[i];
$scope.upload = $upload.upload({
file: file,
url: '/File/Upload',
data: {
id: 1 //some data you want to send along with the file,
name: 'ABC' //some data you want to send along with the file,
},
}).progress(function(evt) {
}).success(function(data, status, headers, config) {
alert('Upload done');
}
})
.error(function(message) {
alert('Upload failed');
});
}
};
}]);
.Hidden {
display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div data-ng-controller="ngController">
<input type="button" value="Browse" onclick="$(this).next().click();" />
<input type="file" ng-file-select="Upload($files, 1)" class="Hidden" />
</div>
On the server side I have an MVC controller with an action the saves the files uploaded found in the Request.Files collection and returning a JsonResult.
If you use AngularJS try this out, if you don't... sorry mate :-)

Categories

Resources