I'm new to jquery/ajax/javascript. I try to get data from an API, everything works, except, I can't print the data to my html-page. Somehow the appendChild-method doesn't work. What do I do wrong here? Thanks in advance!
function openkvk() {
var urls = "https://overheid.io/api/kvk?";
var keyset = {
"ovio-api-key": '041be6bc5818ad9bfe0ff9c9a9637a24b2fd1ec817cd8c3d102f61afc8006dd2'
};
var postcode = document.getElementById('plaats').value;
var naam = document.getElementById('bedrijfsnaam').value;
var kvk = document.getElementById('kvk').value;
console.log("tot aan hier1");
if(postcode != ""){
urls = urls + "&filters[postcode]=" + postcode;
}
if(naam != ""){
urls = urls + "&filters[handelsnaam]=" + naam;
}
if(kvk != ""){
urls = urls + "&filters[dossiernummer]=" + kvk;
}
console.log("tot aan hier2");
$.ajax({
type: 'GET',
url: urls,
headers:{"ovio-api-key":'041be6bc5818ad9bfe0ff9c9a9637a24b2fd1ec817cd8c3d102f61afc8006dd2',"Content-Type":"application/json"},
dataType: 'json',
complete: function(data) {
var response = data.responseJSON;
console.log(response);
var container = document.getElementById('result-kvk');
container.innerHTML = "";
console.log(data);
console.log("data geprint");
$.each(response._embedded.rechtspersoon, function(index,item){
console.log(item);
console.log("items geprint");
var kvknummer = document.createElement("P");
kvknummer.innerHTML = item.dossiernummer;
//console.log(kvknummer);
var handelsnaam = document.createElement('P');
handelsnaam.innerHTML = item.handelsnaam;
console.log("hwiueh");
//failed
container.appendChild(kvknummer);
container.appendChild(handelsnaam);
});
}
});
}
Related
all. I am newest in Django and I have a question. I want learn what I need return to ajax get/post request. I have example, but I know it is not good. Can u please explain me about responses? When, what and why? I did not find any information about it.
When I click on button, object will delete from data base.
This is my ajax request:
function removeProduct(){
$('.btn-remove').click(function(e){
e.preventDefault();
var data = {};
data["csrfmiddlewaretoken"] = $('#quantity_goods [name="csrfmiddlewaretoken"]').val();
var product = $(this);
data.product_id = product.data("product_id");
var url = product.attr("action");
$.ajax({
url: url,
type: 'POST',
data: data,
cache: true,
success: location.reload(),
});
});
}
This is my view:
def remove_product(request):
"""Remove product from basket."""
data = request.POST
product_id = data.get('product_id')
product = ProductInOrder.objects.filter(id=product_id)
product.delete()
return HttpResponse()
Here's how I do it
var username_ok = false;
var email_ok = false;
/*CSRF Code */
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
function sameOrigin(url) {
// test that a given url is a same-origin URL
// url could be relative or scheme relative or absolute
var host = document.location.host; // host + port
var protocol = document.location.protocol;
var sr_origin = '//' + host;
var origin = protocol + sr_origin;
// Allow absolute or scheme relative URLs to same origin
return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
(url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
// or any other URL that isn't scheme relative or absolute i.e relative.
!(/^(\/\/|http:|https:).*/.test(url));
}
/* End CSRF Code */
$(function() {
$('#username, #email').focus(function() {
var value = $(this).val();
if (value == 'required') {
$(this).val(null);
}
});
$('#username').change(function() {
var username = $(this).val();
var data = {'username': username};
var csrftoken = $.cookie('csrftoken');
$.ajax({
url: "/ajax_username",
type: "POST",
dataType: 'json',
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) {
// Send the token to same-origin, relative URLs only.
// Send the token only if the method warrants CSRF protection
// Using the CSRFToken value acquired earlier
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
},
data: JSON.stringify(data),
success: function(response){
if (response['status'] == 'ok') {
if (response['exists'] == true) {
$('.username-exists').removeClass('hidden');
username_ok = false;
} else {
$('.username-exists').addClass('hidden');
username_ok = true;
}
}
}
});
/* End Ajax Call */
});
backend
import json
def username_ajax(request):
response = {'status': None}
if request.method == 'POST':
data = json.loads(request.body)
username = data['username']
response['exists'] = bool( User.objects.filter(username=username))
response['status'] = 'ok'
else:
response['error'] = 'no post data found'
return HttpResponse(
json.dumps(response),
content_type="application/json"
)
hope it helps
I am developing my mobile application using ionic framework and I want it to connect to my API through ajax. Currenty, in the mobile side, which is I am using Ionic Framework, I want to upload an image and pass it to my api through ajax. I am using Cordova for the upload but it seems it doesn't found the URL I indicated.
Here's the HTML
<ion-footer-bar class="bar bar-positive">
<div class="button-bar">
<button class="button icon-left ion-upload" ng-click="uploadImage()" ng-disabled="image === null">Upload</button>
</div>
</ion-footer-bar>
Here's the uploadImage() function in the controller (Just copied the code in a site. Forgot where) EDIT: added targetPath
$scope.uploadImage = function() {
// Destination URL
var url = "http://192.168.0.19/identificare_api/public/api/plants/image";
var targetPath = $scope.pathForImage($scope.image);
// File name only
var filename = $scope.image;
var options = {
fileKey: "file",
fileName: filename,
chunkedMode: false,
mimeType: "multipart/form-data",
params : {'fileName': filename}
};
$cordovaFileTransfer.upload(url, targetPath, options).then(function(result) {
var jsonparse = JSON.parse(result);
$scope.showAlert(jsonparse);
}
But in the upload part, I want to do it in ajax to indicate the method for the URL but the problem I don't know what put in data.
$.ajax({
url: "http://192.168.0.19/identificare_api/public/api/plants/image",
type: 'POST',
data:
success:function(json){
var jsonparse = JSON.parse(json);
alert(jsonparse);
},
error:function(){
alert("Error");
}
});
Can someone help me with this issue?
UPDATE: Applied here #Blauharley's comment below
I had another issue here. I returned the $_FILES['image']['tmp_name'] in the API side but it returns nothing but when I returned the $_FILES['image']['name'], it returned my_image.jpg. Why it doesn't have tmp_name?
$scope.uploadImage = function() {
// File for Upload
var targetPath = $scope.pathForImage($scope.image);
$scope.getBase64ImageByURL(targetPath).then(function(base64Image){
var blob = $scope.base64ToBlob(base64Image,'image/jpeg');
var fd = new FormData();
fd.append('image', blob, "my_image.jpg");
fd.append('user_token', "rLUrh37rfTozuBxmemHtlKMgH");
$.ajax({
url: 'http://192.168.0.19/identificare_api/public/api/plants/image',
type: 'POST',
data: fd,
contentType: false,
processData: false,
success:function(res){
alert(res);
},
error:function(err){
alert("Something's wrong with your api. Come on fix it!");
}
});
});
};
$scope.getBase64ImageByURL = function(url) {
var dfd = new $.Deferred();
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function() {
var reader = new FileReader();
reader.onloadend = function() {
dfd.resolve(reader.result);
}
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.send();
return dfd.promise();
};
$scope.base64ToBlob = function(base64Image,toMimeType) {
var byteCharacters = atob(base64Image.replace('data:'+toMimeType+';base64,',''));
var byteNumbers = new Array(byteCharacters.length);
for (var i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
var blob = new Blob([byteArray], {
type: toMimeType
});
return blob;
};
ADDED: API side
public function image(){
echo json_encode($_FILES['image']['tmp_name']);
}
I'm uploading the big files using chunk method.If i make minimum number request to the server uploading is working fine.if make high number of request to the server Chrome browser has crashed with Aw Snap! error message.But other browsers are working fine with high number of request.
How to resolve this.Is there workaround?is it chromium bug?
Updated
Below function will slice the file then upload chunk to server .After all chunks uploaded. Merge Api will merge the chunk.
Code:
function readFile (file) {
var uploadBatchKey = this.guid;
var start = 0; //Start Index
var stop = file.size; //End Index
var chunksize = (document.getElementById('chunkSize').value * 1048576);
var index = this.chunkUploadIndex;
var reader = new FileReader();
var filecontent = null;
var waitingInterval = null;
var totalsegment = Math.ceil(stop / chunksize);
var isPreviousChunkUpload = true;
var match = ko.utils.arrayFirst(JSViewmodel.SelectedFiles(), function (item) {
return item.UploadManager == undefined ? false : (uploadBatchKey === item.UploadManager.guid);
});
match.UploadBatchKey(uploadBatchKey);
var handle = setInterval(function () {
if (isPreviousChunkUpload) {
if (!match.IsUploading()) {
clearInterval(handle);
}
else if (index > totalsegment) {
isPreviousChunkUpload = false;
var filename = match.IsRelativePath() ? file.webkitRelativePath : file.name;
console.log(file.size);
var batchData = { uploadBatchKey: uploadBatchKey, fileName: filename, fileSize: file.size };
$.ajax({
url: "/Home/MergeChunk",
type: 'POST',
async: false,
data: batchData,
success: function (result) {
debugger;
console.log(result);
if (result == "False")
match.IsFailed(true);
},
error: function (result) {
console.log(result);
debugger;
match.IsFailed(true);
}
});
match.IsUploading(false);
match.IsCompleted(true);
clearInterval(handle);
}
start = (index - 1) * chunksize;
stop = (index * chunksize) - 1;
reader.onloadend = function (evt) {
if (evt.target.readyState == FileReader.DONE) { // DONE == 2
filecontent = evt.target.result;
var chunkContent = { chunkContent: window.btoa(filecontent), chunkIndex: index - 1, uploadBatchKey: uploadBatchKey };
console.log("onloadend" + chunkContent.chunkIndex);
$.ajax({
url: "/Home/Upload",
type: 'POST',
async: false,
data: chunkContent,
success: function (result) {
match.Percentage(Math.round((chunkContent.chunkIndex / totalsegment) * 100));
isPreviousChunkUpload = true;
}
});
}
};
var blob = file.slice(start, stop + 1);
reader.readAsBinaryString(blob);
isPreviousChunkUpload = false;
console.log("file slice:" + index);
index++;
match.UploadManager.chunkUploadIndex = index;
}
}, 500);
}
REQUEST URL http://localhost:9090/rest-api/fetchDetailedProductInfo?prodId=1&tempId=123
fetchDetailedProductInfo: function (prodId) {
var self = this;
var URL = 'http://localhost:9090/rest-api/fetchDetailedProductInfo'
$.ajax({
url: URL,
dataType: 'json',
contentType:'json',
type:'GET',
data: {
'prodId':prodId,
'tempId':123
},
success:function(responce) {
self.renderUI(responce.json);
},
error: function (err) {
console.log('ERROR',err)
}
});
},
# SERVER SIDE
router.get('/rest-api/fetchDetailedProductInfo', function (req, res) {
var prodId = req.param('prodId');
var tempId = req.param('tempId');
res.send(prodId + '----' + tempId);
}
I think you confused with req.params and req.query. Here is link to another question
Use req.query
var prodId = req.query.prodId;
var tempId = req.query.tempId;
Please see this
folks
we are facing a strange issue with jquery ( 1.8.3) and we are using cakePHP
as per the image
Our assumption is we are sending the data( about 500 +) with ajax call in POST method.
we are having this issue in all the major browsers.
as above( in chrome) , we are getting this error in console we passed 618 destinations in ajax call.
let us know the work around to solve this problem.
My ajax call is as below
function validate_test() {
$("#btn1").empty();
var ele = document.getElementById('frm_searchDateFrom').value;
var ele2 = document.getElementById('frm_searchDateTo').value;
var sub_url = '<?php echo $this->Html->url('/', true); ?>';
var url = sub_url + "admin/reports/check_originator/" + ele +"/"+ ele2 +"/"+ $("#destination").val();
alert(url);
jQuery.ajax({
type: "POST",
datatype: "json",
url: url,
success: function(data)
{
var el = $("select#btn1").multiselect();
var d;
var results=data.split(",");
for(d=0;d<results.length;d++) {
var d;
var v = results[d], opt = $('<option />', {
value: v,
text: v
});
opt.appendTo( el );
el.multiselect('refresh');
}
}
})
}
In your JQuery Ajax method instead of posting all those details as url query para meter send by wrapping those details in a object.
function validate_test() {
$("#btn1").empty();
var ele = document.getElementById('frm_searchDateFrom').value;
var ele2 = document.getElementById('frm_searchDateTo').value;
var sub_url = '<?php echo $this->Html->url('/', true); ?>';
var url = sub_url + "admin/reports/check_originator/";
var formdata=ele +"/"+ ele2 +"/"+ $("#destination").val();//put form data's in an object
alert(url);
jQuery.ajax({
type: "POST",
datatype: "json",
data:formdata,//send the form data object in post
url: url,
success: function(data)
{
var el = $("select#btn1").multiselect();
var d;
var results=data.split(",");
for(d=0;d<results.length;d++) {
var d;
var v = results[d], opt = $('<option />', {
value: v,
text: v
});
opt.appendTo( el );
el.multiselect('refresh');
}
}
})
}
Also refer this fiddle(not mine):
http://jsfiddle.net/clickthelink/Uwcuz/1/