I am tring to send an object to my node server:
cropData: { x: '0', y: '300', width: '5760', height: '3240' }
via ajax:
$.ajax({
type: "POST",
url: "/",
data: {cropData:cropData},
success: function(data) {
console.log('Success!')
},
error: function(jqXHR, textStatus, err) {
console.log('text status '+textStatus+', err '+err)
}
});
then get that in my server.js file:
app.post('/', function(req, res) {
console.log(req.body.cropData);
});
when I log that into console I get:
first:
proper object => { x: '0', y: '300', width: '5760', height: '3240' }
and second:
nonsense result => undefined
Why is that happening? first the proper object, and then undefined!
My bodyParser:
app.use(bodyParser.urlencoded({extended: true}));
I really cannot understand. Please help me.
Related
Trying to use Uppy JS lib to upload file throug Laravel. Setted up simple upload form with there params:
const options = {
endpoint: '/parts/image-upload',
headers: {
'X-XSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
},
};
uppyDashboard.use(XHRUpload, options);
And on the backend I'm getting
Illuminate\Contracts\Encryption\DecryptException: The payload is invalid. in file /Users/rd/Projects/xxx/vendor/laravel/framework/src/Illuminate/Encryption/Encrypter.php on line 195
It's like Laravel trying to decrypt something what is already decrypted, anyway I'm in dead end.
You can this code
var uppy = new Uppy.Core({
// debug: (...args) => console.debug(`[Uppy] [${getTimeStamp()}]`, ...args),
// warn: (...args) => console.warn(`[Uppy] [${getTimeStamp()}]`, ...args),
// error: (...args) => console.error(`[Uppy] [${getTimeStamp()}]`, ...args),
autoProceed: true,
restrictions: {
maxFileSize: 2000000,
maxNumberOfFiles: 10,
minNumberOfFiles: 1,
allowedFileTypes: ['image/*']
}
});
uppy.use(Uppy.Dashboard, {
target: ".UppyDragDrop",
inline: true,
showLinkToFileUploadResult: false,
showProgressDetails: true,
hideCancelButton: true,
hidePauseResumeButton: true,
hideUploadButton: true,
proudlyDisplayPoweredByUppy: false,
locale: {} });
Here's how I implemented it
<script type="text/javascript">
$(document).ready(function() {
$('[id*=drag-drop-area]').each(function(){
var listing_id = $(this).attr('class');
var uppy = new Uppy.Core({
allowMultipleUploadBatches: true,
restrictions: {
maxFileSize: 100000000,
// maxNumberOfFiles: 8,
minNumberOfFiles: 1,
allowedFileTypes: ['image/*', '.jpg', '.jpeg', '.png']
}
})
.use(Uppy.Dashboard, {
inline: true,
target: "#"+$(this).attr('id')+""
})
.use(Uppy.XHRUpload, {
endpoint: 'upload',
formData: true,
bundle: true,
headers: {
'X-CSRF-Token': " {{ csrf_token() }} "
},
});
uppy.on('upload-success', (file, response) => {
response.body.data.forEach(function (item, index) {
console.log(listing_id);
var token =
$('meta[name="csrftoken"]').attr('content');
$.ajax({
url: 'attach',
type: 'POST',
data: { '_token' : token, item, listing_id},
success: function(response)
{
console.log('Updated');
},
error:function (e) {
console.log(e);
}
});
});
window.location.reload();
});
});
});
</script>
You create the endpoint which is the route name and attach at
endpoint: ""
Then you return a response which you grab and do whatever on the last section.
uppy.on('upload-success', (file, response) => {
response.body.data.forEach(function (item, index) {
console.log(listing_id);
var token =
$('meta[name="csrftoken"]').attr('content');
$.ajax({
url: 'attach',
type: 'POST',
data: { '_token' : token, item, listing_id},
success: function(response)
{
console.log('Updated');
},
error:function (e) {
console.log(e);
}
});
});
window.location.reload();
});
I hope this helps
I am trying to create an AJAX script that will pull data via an API and display it on a page as HTML. Everything using the route below seem to work fine in Postman, but I can't get it to translate in my JS file.
I know I'm calling the URL incorrectly and I'm pretty sure it's because of the :id. I'm not sure how to correct it. I feel like I've tried every URL iteration, but I'm missing something.
// router.REST_VERB('EXPRESS_ROUTE', api.ACTION)
router.get('/', api.list);
router.post('/', api.create);
router.get('/:id', api.read);
router.put('/:id', api.update);
router.get('/delete/:id', api.delete);
Here are my update and delete:
/ AJAX PUT - Update Reminder
function updateReminder(id) {
$.ajax({
type: 'PUT',
url: '/api/',
data: JSON.stringify({
'id': $('#editId').val(),
'name': $('#name').val(),
'occasion': $('#occasion').val(),
'lastgift': $('#lastgift').val()
}),
success: (item) => {
document.location.href="/";
},
contentType: "application/json",
dataType: 'json'
});
}
// AJAX DELETE request - Delete Reminder
function deleteReminder(id) {
$.ajax({
type: 'DELETE',
url: '/api',
data: JSON.stringify({
'id': id
}),
success: (item) => {
document.location.href="/delete";
},
contentType: "application/json",
dataType: 'json'
});
}
EDIT
Here is the controller code for update and delete:
ApiController.update = (req, res) => {
reminderService.update(
req.params.id,
{
name: req.body.name,
occasion: req.body.occasion,
lastgift: req.body.lastgift,
prefgift: req.body.prefgift
},
{new: true}
)
.then((item) => {
res.json(item);
})
.catch((err) => {
if (err) console.log(err);
});
};
ApiController.delete = (req, res) => {
reminderService.delete(req.params.id)
.then((item) => {
res.json(item);
})
.catch((err) => {
if (err) {
res.end("Didn't delete")
}
});
};
and here is the service code:
ReminderService.update = (id, reminderObj) => {
return Reminder.findByIdAndUpdate(
id,
{
$set: reminderObj
},
{
new: true
}
)
.then((item) => {
return item;
})
.catch((err) => {
if (err) {
res.end("You're in reminderService!")
}
});
};
ReminderService.delete = (reminderId) => {
return Reminder.deleteOne({ '_id': reminderId })
.then((item) => {
return item;
})
.catch((err) => {
throw err;
});
};
Your route for delete is wrong, you should use delete instead of get.
router.get('/', api.list);
router.post('/', api.create);
router.get('/:id', api.read);
router.put('/:id', api.update);
router.delete('/:id', api.delete);
In your ajax requests, your url is missing the ids
// AJAX PUT - Update Reminder
function updateReminder(id) {
$.ajax({
type: 'PUT',
url: '/'+id,
data: JSON.stringify({
'id': $('#editId').val(),
'name': $('#name').val(),
'occasion': $('#occasion').val(),
'lastgift': $('#lastgift').val()
}),
success: (item) => {
document.location.href="/";
},
contentType: "application/json",
dataType: 'json'
});
}
// AJAX DELETE request - Delete Reminder
function deleteReminder(id) {
$.ajax({
type: 'DELETE',
url: '/'+id,
data: JSON.stringify({
'id': id
}),
success: (item) => {
document.location.href="/delete";
},
contentType: "application/json",
dataType: 'json'
});
}
One thing I'm skeptical about is that you use JSON.stringify on your data. Does your API specifically require JSON or did you do just do that to try to get it t work?
I would like to pass in an array of IDs that will be used to select the events I want to display. The fullcalendar displays all of the events if I do not use the 'data' attribute with the ID array. When the data attribute is added I get the error message 'There was an error fetching events!'
This is the document ready function:
var groupSelectedArray = [];
groupSelectedArray[0] = '1';
groupSelectedArray[1] = '2';
$('#calendar').fullCalendar({
header:
{
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
titleFormat: {month: 'MMMM'},
defaultView: 'month',
editable: false,
events: function (start, end, groupSelectedArray, callback) {
$.ajax({
type: "POST",
url: '#Url.Action("GetAllEvents", "Home")',
data: { selectedGroups: groupSelectedArray },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (doc) {
var events = [];
$(doc).each(function () {
events.push({
title: $(this).attr('title'),
start: $(this).attr('start'),
end: $(this).attr('end'),
id: $(this).attr('id'),
description: $(this).attr('description'),
color: $(this).attr('color'),
textColor: 'black'
});
});
callback(events);
} ,
error: function () {
alert("There was an error fetching events!")
}
});
}
This is the C# method:
public JsonResult GetAllEvents(string[] selectedGroups)
{
var eventList = GetEventsFromDatabase(selectedGroups);
var rows = eventList.ToArray();
return Json(rows, JsonRequestBehavior.AllowGet);
}
Can anyone see where I am going wrong?
Thanks.
What I did to get this to work was change the 'data' part of the ajax call:
Replace this:
{ selectedGroups: groupSelectedArray },
to this:
data: JSON.stringify(groupData),
I want to build a morris.js plot dynamically by using ajax, php, and mysql.
i have been searching with no success how to achieve this.
I get the array data successfully with ajax but now i can't pass these data to build the plot.
From the PHP script i get the following json array:
[{"concurso":"2736","R1":"7","R2":"24","R3":"27","R4":"39","R5":"45","R6":"52","R7":"12"},{"concurso":"2737","R1":"16","R2":"19","R3":"23","R4":"29","R5":"33","R6":"49","R7":"36"},{"concurso":"2738","R1":"4","R2":"6","R3":"20","R4":"21","R5":"45","R6":"55","R7":"38"},{"concurso":"2739","R1":"5","R2":"16","R3":"17","R4":"24","R5":"41","R6":"47","R7":"36"},{"concurso":"2745","R1":"1","R2":"13","R3":"19","R4":"29","R5":"41","R6":"46","R7":"50"}]
Where morris.js y is the value after 'concurso', and ykeys are the values after R1, R2, R3, ... R7.
My jQuery looks like this so far:
$.ajax({
url: "ajax/default_chart_numbers.php",
cache: false,
dataType: "json",
timeout:3000,
success : function (data) {
new Morris.Line({
// ID of the element in which to draw the chart.
element: 'revancha',
data: $.parseJSON(data),
xkey: 'concurso',
ykeys: ['R1', 'R2', 'R3', 'R4', 'R5', 'R6', 'R7'],
labels: ['n1', 'n2', 'n3', 'n4', 'n5', 'n6', 'n7'],
hideHover: 'auto',
resize: true
});
},
error : function (xmlHttpRequest, textStatus, errorThrown) {
alert("Error " + errorThrown);
if(textStatus==='timeout')
alert("request timed out");
}
});
I can't see the plot. There's nothing. What am i missing?
Well, fortunately i could fix it myself. Here is my working jQuery ☺:
$.ajax({
url: "ajax/some_handler.php",
cache: false,
type: "POST",
data: {anyVar: 'specialValue4PHPScriptAndDataBaseFilter'},
dataType: "json",
timeout:3000,
success : function (data) {
//console.log(data); alert(JSON.stringify(data));
Morris.Line({
element: 'TheElementName',
data: data,
xkey: 'someID',
ykeys: ['R1', 'R2', 'R3', 'R4', 'R5', 'R6'],
labels: ['n1', 'n2', 'n3', 'n4', 'n5', 'n6'],
hideHover: 'auto',
resize: true
});
},
error : function (xmlHttpRequest, textStatus, errorThrown) {
alert("Error " + errorThrown);
if(textStatus==='timeout')
alert("request timed out");
} /*References: http://stackoverflow.com/questions/22746646/ajax-i-cant-get-data-from-php-by-using-json-encode*/
});
You can use the setData() function on the Morris.Line returned object to update data. Here is a snippet from the morris examples which I've commented. (https://github.com/morrisjs/morris.js/blob/master/examples/updating.html)
// build array filled with placeholder data
var nReloads = 0;
function data(offset) {
var ret = [];
for (var x = 0; x <= 360; x += 10) {
var v = (offset + x) % 360;
ret.push({
x: x,
y: Math.sin(Math.PI * v / 180).toFixed(4),
z: Math.cos(Math.PI * v / 180).toFixed(4)
});
}
return ret;
}
// create the morris chart.
var graph = Morris.Line({
element: 'graph',
data: data(0),
xkey: 'x',
ykeys: ['y', 'z'],
labels: ['sin()', 'cos()'],
parseTime: false,
ymin: -1.0,
ymax: 1.0,
hideHover: true
});
// update the chart with the new data.
function update() {
nReloads++;
// called on the returned Morris.Line object.
graph.setData(data(5 * nReloads));
$('#reloadStatus').text(nReloads + ' reloads');
}
setInterval(update, 100);
I have following code in jQgrid and I am using jQuery ui autocomplete in one of the field. But the pop up of autocomplete displays somewhere else as shown in figure. From IE developer tools I noticed the results are attached to body tag, which is at the end of the page. I tried using appendTo, but that doesn't help.
{
name: 'nameAccount',
index: 'nameAccount',
width: 300,
editable: true, sortable: false, resizable: false,
shrinkToFit: true
,editoptions: {
dataInit: function (elem) {
var autocompleteSource = function(request, response,term) {
var param = request.term;
$.ajax({
url: myUrl,
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "GET",
success: function (myyydata) {
//alert('HI-Success');
//response( myyydata );
response($.map(myyydata, function (item) {
return {
label: item.AccountInfo,
value: item.AccountInfo
}
}));
} ,
error: function (res, status) {
alert('HI-error');
//alert(res.status+" : "+res.statusText+". Status: "+status);
}
});//END AJAX
};
$(elem).autocomplete({
source: autocompleteSource,
//appendTo: "#"+elem.id,
position: { collision: "flip" },
minLength: 2
});//END AUOTOCOMPLETE
}//END Dataint
}//END Dataint
},
minnu4515. i guess it is because of the css misalignment. i faced the similar problem and i manually set the z-index alignmnet. that solved my issue.
$('.ui-autocomplete').css('zIndex',1000);