So I have this function that gets the user details via UUID;
function getUserDetails(uuid){
$.ajax({
url:'http://localhost/hrms/controller/php/getUserDetails.php',
method: 'POST',
dataType: 'json',
data: { uuid: uuid },
success:function(result){
console.log(result);
},
error: function(xhr, status, error){
if(xhr.status == 401){
toastr.error(xhr.responseText);
}
}
});
}
which give me the result of
AJAX RESULT
Now I wonder how to access that data. The function is from different js page. How can I throw the json result to another js page?
Im using JQUERY. Thanks and more powers.
When you use ajax it takes some time to return the data form server to client, so you can use promise or callbacks:
Callbacks:
function.js
function getUserDetails(uuid, callback){
$.ajax({
url:'http://localhost/hrms/controller/php/getUserDetails.php',
method: 'POST',
dataType: 'json',
data: { uuid: uuid },
success:function(result){
callback(result);
},
error: function(xhr, status, error){
if(xhr.status == 401){
toastr.error(xhr.responseText);
}
}
});
}
index.js
getUserDetails(uuid, function(data){
console.log(data);
});
Promises
function.js
function getUserDetails(uuid){
return new Promise((resolve, reject) => {
$.ajax({
url:'http://localhost/hrms/controller/php/getUserDetails.php',
method: 'POST',
dataType: 'json',
data: { uuid: uuid },
success:function(result){
resolve(result);
},
error: function(xhr, status, error){
if(xhr.status == 401){
toastr.error(xhr.responseText);
}
const reason = new Error('Error');
reject(reason);
}
});
});
}
index.js
getUserDetails(uuid).then(function(data){
console.log(data);
});
Related
So I'm using axios to be able to access Cloudinary API and upload photos. Then I want to be able to do an AJAX request that communicates with my own API to store the url for the photo I just uploaded. Here's my code:
$("#file-upload").change(function (event) {
file = event.target.files[0];
$("#add-article").click(function () {
formData.append('file', file);
formData.append('upload_preset', CLOUDINARY_UPLOAD_PRESET);
axios({
url: CLOUDINARY_URL,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: formData
}).then(function (res) {
console.log(res);
fileSource = res.data.secure_url;
$.ajax({
url: 'https://127.0.0.1:5000/api/admin/add_news',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
'title': newsTitle,
'imgSrc': fileSource
}),
method: 'POST',
dataType: 'json',
crossDomain: true,
success: function (res) {
alert(res.message);
location.reload();
},
error: function () {
console.log('error')
},
complete: function (jqXHR) {
if (jqXHR.status == '401') {
console.log(jqXHR.status)
}
}
});
}).catch(function (err) {
console.log(err);
});
});
I put all of this inside a document.ready function. It returns an error like this:
I read about jQuery and JavaScript being compatible together, so what am I missing here?
I have a problem on my code. I want to upload the image file by using formdata and ajax to the server side python program. But I got django.utils.datastructures.MultiValueDictKeyError: "'image'" error in my server uwsgi.log. I think it may not upload the image file to the server, but I don't understand what is wrong on my code.
My client code is the following.
function imageFileUploader(imageType, image) {
var credentials = {
filetype: imageType,
};
var image_file = image;
$.ajax({
url: HOST_NAME + "user/api/get_filename/",
type: 'GET',
dataType: 'json',
data: credentials,
timeout: 10000,
})
.done(function (data) {
jsondata = JSON.parse(data);
image_file_name = jsondata.fileurl;
// Test if the image is shown -> success
document.getElementById("previewimage").src = image
var formData = new FormData();
formData.append('filename', image_file_name);
formData.append('image', image);
$.ajax({
url: HOST_NAME + "user/api/file_uploader/",
type: 'POST',
timeout: 10000,
data: formData,
processData: false,
contentType: false,
})
.done(function (data) {
jsondata = JSON.parse(data);
alert("File upload completed...");
})
.fail(function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
})
.fail(function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
})
}
function snapPicture () {
navigator.camera.getPicture (onSuccess, onFail,
{quality: 50, destinationType: Camera.DestinationType.FILE_URI,
saveToPhotoAlbum: true});
function onSuccess (imageURI) {
var file_name = imageFileUploader("T", imageURI);
if (file_name == "") {
console.log("False");
}
else {
image_send(file_name);
}
}
function onFail (message) {
console.log("False");
}
}
And my server side code is the following.
def post(self, request, format=None):
outputLogFile("Upload Function is called...")
req_file_name = request.data['filename']
req_image = request.FILES['image']
I can get filename from the client when I comment the code of image. Please give me an advice.
I try send a binary file with jquery to node js.
This is my jquery code:
$('#addLabel').click(function(){
$.ajax({
url: "http://127.0.0.1:3030/label/66806",
type: 'PUT',
data: files,
contentType: 'application/octet-stream',
dataType: 'binary',
contentType: false,
processData: false,
success: function (data) {
console.log("sent file");
},
error: function (xhr, status, error) {
console.log("error " + status + " " + error);
}
});
});
var files;
$('input[type=file]').on('change', prepareUpload);
function prepareUpload(event)
{
files = event.target.files;
}
For example I need only show in console a data like below:
update(id, data, params) {
console.log(data);
return Promise.resolve(data);
}
Firebug show me that a data was sent but node show me only {}. Sent data are empty. What is wrong?
I'm sending an ajax request to a remote api.
This is the response I receive when i'm just browsing to the URL:
{
"organizations":[],
"displayName":"Asaf Nevo",
"roles":[
{
"name":"provider",
"id":"106"
}
],
"app_id":"app_id",
"email":"email",
"id":"id"
}
Now the api is in a different ORIGIN so I needed to use JSONP in my call:
$.ajax(
{
url: KeyrockConfig.defaultInstanceUrl + uri,
type: method,
dataType: "jsonp",
data: params,
success: function (result, status, xhr) {
callback(result, status, xhr);
},
//TODO consider having a different callback for error
error: function (xhr, status, error) {
callback(error, status, xhr);
}
}
);
But I'm keep getting Uncaught SyntaxError: Unexpected token :
I tried to do:
$.ajax(
{
url: KeyrockConfig.defaultInstanceUrl + uri,
type: method,
dataType: "jsonp",
jsonp:false,
jsonpCallback: function (response) {
alert(response);
},
data: params,
success: function (result, status, xhr) {
callback(result, status, xhr);
},
//TODO consider having a different callback for error
error: function (xhr, status, error) {
callback(error, status, xhr);
}
}
);
But the alert was never called. What do I do wrong?
This is my server side code
var response = new HttpResponseMessage
{
Content = new StringContent("FAIL FAIL"),
StatusCode = HttpStatusCode.InternalServerError,
};
response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
return Task<HttpResponseMessage>.Factory.StartNew(() => response);
This is my client side code using jquery
$.ajax({
type: 'POST',
url: 'someurl',
data: somevalues,
success: function (data) {
console.log(data);
},
error: function (jqxhr) {
console.log(jqxhr);
}
});
But when I check using firebug, my jqxhr.responseText is "".
How do I retrieve "FAIL FAIL"?
Try like this:
var ajaxReult = $.ajax({
type: 'POST',
url: 'someurl',
data: somevalues,
success: function (data) {
// console.log(data);
},
error: function (jqxhr) {
// console.log(jqxhr);
}
}).responseText;
console.log(ajaxReult);