Uncaught syntax error during photo upload using AjaxFileUpload - ajax

if(myData)
{
$('.overlay_content').html('<img src="'+baseurl+'resource/img/loading.gif" width="30"> LOADING');
$('#loader_overlay').fadeIn(100);
$.ajaxFileUpload({
url:baseurl+"invoice_settings/manage/post_settings/",
secureuri :false,
fileElementId :'invoice_logo',
dataType : 'JSON',
data : myData,
success : function (data)
{
var data = $.parseJSON(data);
$('.overlay_content').html('<img src="'+baseurl+'resource/img/tick.jpg" width="30"> Updation Successfull<br/>');
$('#loader_overlay').fadeOut(5000);
$("#settings_form").data('bootstrapValidator').resetForm();
}
handleError: function( s, xhr, status, e ) {
// If a local callback was specified, fire it
if ( s.error ) {
s.error.call( s.context || window, xhr, status, e );
}
// Fire the global callback
if ( s.global ) {
(s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] );
}
}
});
}
This is my js file. when I run my page the data is not uploading and it returns uncaught syntax error. I added handle error function after getting the error "jQuery.handleError is not a function". After adding handleError function now its returning this error.please help me

There are plenty of answer available over internet. whenever you stuck do initial workaround as suggested.
How to use ajax in codeigniter: https://www.formget.com/codeigniter-jquery-ajax-post/
Sample code:
$('form').on('submit', uploadFiles);
// Catch the form submit and upload the files
function uploadFiles(event)
{
event.stopPropagation(); // Stop stuff happening
event.preventDefault(); // Totally stop stuff happening
// START A LOADING SPINNER HERE
// Create a formdata object and add the files
var data = new FormData();
$.each(files, function(key, value)
{
data.append(key, value);
});
$.ajax({
url: 'submit.php?files',
type: 'POST',
data: data,
cache: false,
dataType: 'json',
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function(data, textStatus, jqXHR)
{
if(typeof data.error === 'undefined')
{
// Success so call function to process the form
submitForm(event, data);
}
else
{
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log('ERRORS: ' + textStatus);
// STOP LOADING SPINNER
}
});
}

Related

merge ajaxform with ajax to upload image

I try to create upload photos in my nodejs site.
I used this code to choose file and upload the image:
var fileData = null;
function loadFile() {
var preview = document.querySelector('file');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
reader.onloadend = function () {
fileData = file;
}
if (file) {
reader.readAsDataURL(file);
}
}
function uploadFile() {
data = new FormData();
data.append('file', fileData);
$.ajax({
url: "/post_pdf/",
type: "POST",
data: data,
enctype: 'multipart/form-data',
processData: false,
contentType: false,
success: function(data) {
document.getElementById("result").innerHTML = 'Result: Upload successful';
},
error: function(e) {
document.getElementById("result").innerHTML = 'Result: Error occurred: ' + e.message;
}
});
}
With loadfile funcion i choose my image, and with Uploadfile function i upload the image with ajax.
if i use it alone its work perfect and upload the image to the location.
but when i try to add this code to my code, it make alot of errors.
in my code i send to back end all the forms in the pug file:
$('#account-form').ajaxForm({
error : function(e){
if (e.responseText == 'title-empty'){
av.showInvalidTitle();
}
},
success : function(responseText, status, xhr, $form){
if (status == 'success')
{
$('.modal-alert').modal('show');
console.log(responseText)
}}
});
i try to merge the ajaxform with the ajax but when i merege the formdata or i send in ajaxform the data of the file is send error.
how can i merge the codes?
thanks for helping.
Try to submit form it will submit form with your image.
let form = $("#form_id");
$.ajax({
url : $(form).attr("action"),
type: "POST",
dataType: "json",
processData: false,
contentType: false,
cache: false,
data: new FormData(form[0]),
success:function(data){
},
error: function (xhr, status, e) {
}
});
#Yogesh Patel
when i use this code:
$('#account-form-btn2').on('click', function(e) {
let form = $("#account-form");
$.ajax({
url: $(form).attr("action"),
type: "POST",
dataType: "json",
processData: false,
contentType: false,
cache: false,
data: new FormData(form[0]),
error: function (e) {
if (e.responseText == 'title-empty') {
av.showInvalidTitle();
}
},
success: function (responseText, status, xhr, $form) {
if (status == 'success') {
$('.modal-alert').modal('show');
}
}
});
});
for some reason it sends the values to "routes" three times.
and it doesn't catch the erorrs or success.
and it sends me to a white window with the value of the callback.
if needed, i can send the function that gets the values and returns them (app.post).

File upload using jquery/ajax for REST API

I was trying to upload file to a remote server using REST api by ajax/jquery with the following script, but it returns 400 error with a Bad request. I have tested the end point with curl, which is giving correct response and file is being uploaded.
$(document).ready(function () {
$("#btnSubmit").click(function (event) {
//stop submit the form, we will post it manually.
event.preventDefault();
fire_ajax_submit();
});
});
function fire_ajax_submit() {
// Get form
var form = $('#fileUploadForm')[0];
alert(form.files[0]);
var data = new FormData(form);
data.append("CustomField", "This is some extra data, testing");
$("#btnSubmit").prop("disabled", true);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "http://10.13.20.166:5332/fileUploadtoFolder",
data: data,
processData: false,
contentType: false,
cache: false,
timeout: 600000,
success: function (data) {
$("#result").text(data);
console.log("SUCCESS : ", data);
$("#btnSubmit").prop("disabled", false);
},
error: function (e) {
$("#result").text(e.responseText);
console.log("ERROR : ", e);
$("#btnSubmit").prop("disabled", false);
}
});
}
Change your code đŸ‘‡
var data = new FormData(form);
Use this code đŸ‘‡
// Create an FormData object
var data = new FormData(document.getElementById("fileUploadForm"));
Try again

jqgrid onclickSubmitLocal using ajax

I am using the example here as a starting point. Everything works fine, I can submit the data back to the server and get a response. However I don't know how to connect the callback from the ajax to the jqgrid onclickSubmitLocal. I don't want to use alerts because even if there is an error the row is updated. I would like some how if there is an error the modal edit dialog to show the error and prevent it from updating the row. On success I would like the user to get a message saying data was saved.
Here is the relevant code:
function submitData(rowData){
var dataToSend = JSON.stringify(rowData);
$.ajax({
url: '/save',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: dataToSend,
dataType: 'json',
success: function (result) {
alert(' successfully saved.');
},
error: function(xhr, status, error) {
alert('Error processing submit ' + xhr.responseText);
}
});
}
I called the previous function from
onclickSubmitLocal = function (options, postdata) {
var $this = $(this), p = $(this).jqGrid("getGridParam"),// p = this.p,
idname = p.prmNames.id,
id = this.id,
idInPostdata = id + "_id",
rowid = postdata[idInPostdata],
addMode = rowid === "_empty",
oldValueOfSortColumn,
newId,
idOfTreeParentNode;
... same as in example from link above
if (postdata[p.sortname] !== oldValueOfSortColumn) {
// if the data are changed in the column by which are currently sorted
// we need resort the grid
setTimeout(function () {
$this.trigger("reloadGrid", [{current: true}]);
}, 100);
}
// !!! the most important step: skip ajax request to the server
options.processing = true;
submitData([postdata]);
},

How do I convert this IE AJAX code to jQuery AJAX call which works?

I am trying to call a .NET API which accepts JSON and responds with JSON.
I have a javascript example that is IE only that works.
But when I try to convert the code into a jQuery / AJAX call I am unable to make it work.
I have tried every parameter combination I can think of with no success.
Here's the IE code that works.
<script language="javascript" type="text/javascript">
var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
function callService() {
var url = "http://hrdtssiw01:8700/JsonWCF/DoJsonWork"; //use this url on RDN server for access.
var body = '{"LevelOneString":"hello world","LevelTwoClass":{"LevelThreeClass":{"LevelThreeString":"Hello Level Three"},"LevelTwoString":"Hello Level Two"}}';
xmlHttp.open("POST", url, true);
xmlHttp.setRequestHeader("Content-type", "application/json");
xmlHttp.send(body);
}
// Create result handler
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) {
alert('working!!!!');
document.getElementById("Text1").value = xmlHttp.responseText;
}
}
</script>
And here's the jQuery code...
<script>
function callAjax() {
jQuery.support.cors = true;
var temp_url = 'http://hrdtssiw01:8700/JsonWCF/DoJsonWork';
var temp_data = '{"LevelOneString":"hello world","LevelTwoClass":{"LevelThreeClass":{"LevelThreeString":"Hello Level Three"},"LevelTwoString":"Hello Level Two"}}';
$.ajax(temp_url,
{
'type': 'POST',
'data': temp_data,
'dataType': 'json',
'processData': false,
//'contentType': 'application/json; charset=utf-8',
'headers': {'contentType':'application/json'},
'success': function(data) { alert('data: ' + data); },
'error': function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
$(document).ready(function() {
$('#thebutton').click(function() { callAjax(); return false;});
});
</script>
In the jQuery example I have contentType commented out.
If I include the contentType the request is sent as JSON, but the body is not set.
If I comment out contentType the body is set correctly, but then the contenType is set to the default.
How can I make this work???
The data object should be an object, unless the server-side is decoding the json. Try changing to
var temp_data = {"LevelOneString":"hello world","LevelTwoClass":{"LevelThreeClass":{"LevelThreeString":"Hello Level Three"},"LevelTwoString":"Hello Level Two"}};
If you are using cross domain request, you need to be using a CORS supported browser(IE does not support), then try
$.ajax(temp_url, {
'type' : 'POST',
'data' : temp_data,
'dataType' : 'json',
'processData' : false,
'contentType' : 'application/json',
'success' : function(data) {
alert('data: ' + data);
},
'error' : function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});

BlockUI Ajax loading wrong moment

I know there's other post about this. but there's no answer.
Situation, I have an ajax command. It take time because I have somes things to get.
I want to include a loading between the execution of the ajax.
I want to use jquery BlockUI because its simple and good looking.
But I dont know why the visual effect not working until ajax load the entire data(like when "success" begin).
I try multiple way but not working.
here's my last code :
function from http://www.codeproject.com/Articles/382390/An-Example-to-Use-jQuery-Global-AJAX-Event-Handler
var AjaxGlobalHandler = {
Initiate: function(options) {
$.ajaxSetup({ cache: false });
// Ajax events fire in following order
$(document).ajaxStart(function() {
$.blockUI({
message: options.AjaxWait.AjaxWaitMessage,
css: options.AjaxWait.AjaxWaitMessageCss
});
}).ajaxSend(function(e, xhr, opts) {
}).ajaxError(function(e, xhr, opts) {
if (options.SessionOut.StatusCode == xhr.status) {
document.location.replace(options.SessionOut.RedirectUrl);
return;
}
$.colorbox({ html: options.AjaxErrorMessage });
}).ajaxSuccess(function(e, xhr, opts) {
}).ajaxComplete(function(e, xhr, opts) {
}).ajaxStop(function() {
$.unblockUI();
});
}
};
call ready
var options = {
AjaxWait: {
AjaxWaitMessage: '<h1 class="ui-overlay-loading-content"><img class="ui-overlay-loading-image" src="_inc/img/loading3circle1.gif" />Chargement des données ...</h1>',
AjaxWaitMessageCss: { backgroundColor: '#ffffff' }
},
AjaxErrorMessage: "<h6>Erreur!/h6>"
};
AjaxGlobalHandler.Initiate(options);
call execution
$.ajax({
type: "POST",
url: location.href.split('/').pop() + "?action=" + actionName + "&recherche=" + recherche,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
FillDataGridOnSuccess(response, gridId, dataTypeName);
},
error: function(xhr, ajaxOptions, thrownError) {
alert("xhr.status : " + xhr.status);
alert("thrownError : " + thrownError);
}
});
I try also
var ajaxSettings = function(options) {
return $.extend(
{
beforeSubmit: function() {
//beforeSend: function() {
$.blockUI({ overlayCSS: { backgroundColor: '#ffffff' },
message: '<h1 class="ui-overlay-loading-content"><img class="ui-overlay-loading-image" src="_inc/img/loading3circle1.gif" />Chargement des données ...</h1>'
});
},
complete: function() {
$.unblockUI();
}
},
options
);
};
Every test that I did end with a loading who seems to only appear on ajaxSuccess.
I know there's sample on official blockUI site http://jquery.malsup.com/block/#demos
and they working there, but I cant on my own. did anybody see why?
tank you

Resources