ajax uploader success event: unable to get json value - javascript

I am using this script
http://hayageek.com/docs/jquery-upload-file.php
for my uploader.
The uploading is great, everything works, my server side script returns a JSON upon successful upload, however, in the success event, i am not able to get the json value
$("#fileuploader").uploadFile({
url: site.url + 'main/upload',
fileName: 'cpp',
multiple: false,
method: "POST",
allowedTypes: "png,gif,jpg,jpeg",
dragDrop:true,
onSuccess:function(files,data,xhr)
{
if(data.error){
//there is an error
} else {
//there is no error
console.log('no errors ' + data.path);
$('.img-thumbnail').attr('src', data.path);
}
},
onError: function(files,status,errMsg)
{
console.log('uplaod failed');
}
});
The JSON returned by my server side script is
(as seen in firebug)
{"error":false,"msg":"Success","path":"http:\/\/www.domain.com\/uploads\/thumb.png"}
However, data.path returns undefined(i use console.log to check), but when I output it with alert(data), the data seems to be intact there.
(p/s: data.error, data.msg also returns undefined value).
Is this something wrong with my logic or i am missing something out?

Use returnType: "json" and
Try to use parseJSON() like,
onSuccess:function(files,data,xhr)
{
data=$.parseJSON(data); // yse parseJSON here
if(data.error){
//there is an error
} else {
//there is no error
console.log('no errors ' + data.path);
$('.img-thumbnail').attr('src', data.path);
}
},

Related

AJAX error is returned as Success

AJAX error is being returned as Success. How to return JSON error from ASP.NET MVC? Could you tell me what I'm doing wrong? Thank you.
[HttpPost]
public JsonResult Register(int EventID)
{
try
{
// code
return Json(new { success = true, message = "Thank you for registering!" });
}
catch (Exception ex)
{
return Json(new { success = false, message = ex.Message });
}
}
$.ajax({
url: "#Url.Action("Register", "Home")",
type: "post",
dataType: "json",
contentType: "application/json",
data: JSON.stringify(postData),
success: function(data) {
},
error: function (data) {
}
});
The error function gets executed only when the HTTP Response Code is not HTTP 200 Ready. You handle the error in the server-side and return proper response, which will be picked up by success function in the AJAX call. Instead, use the status variable in your JSON and handle it on the client side:
success: function(data) {
if (typeof data == "string")
data = JSON.parse(data);
if (data.success) {
// Code if success.
} else {
// Code if error.
}
},
From the docs (scroll down to the error section):
A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and cross-domain JSONP requests. This is an Ajax Event.
The Ajax error method is hit only when you get a Yellow Screen Error in the server side. In your scenario you are handling the error using try catch and returning a valid response. So this is not considered as a error but a valid response. Remove your try catch so that Ajax will pick up the error event, else if you want to show the actual error message from server then you can use the success property to decide if the response was a success or a error , its similar to what Praveen has already posted in his answer.
success: function(data) {
if (data.success) { //as you are passing true/false from server side.
// Code if success.
} else {
// Code if error.
}
},

Parse server query each with useMasterKey parameter

I'm migrating from Parse to Parse server. Most of my code is made without promises.
For this to work, I have to send the parameter: useMasterKey: true (where necessary) for each query / save.
For find and get queries or fetch objects, I have no problems, example:
Parse.com (find)
query.find({
success: function(results) {
//...
Parse Server (find)
query.find({useMasterKey: true
}).then(function(results) {
//....
Parse.com (fetch)
user.fetch({
success: function(user) {
//...
Parse Server (fetch)
user.fetch({useMasterKey: true,
success: function(user) {
//....
The problem is with each functions:
Parse.com (each)
query.each(function(comment) {
//...
Parse Server (each)
query.each({useMasterKey: true
}).then(function(comment) {
//....
It does not work.
Thanks
Although the docs don't suggest that the useMasterKey option is supported for an each query, having tested and verified myself it is in fact possible. Syntax as follows:
query.each(callback, {useMasterKey: true})
Where callback is a function that is called for each result of the query.
The each method of a query support useMasterKey, it's passed as an argument after the callback function, that will be executed for each result of the query.
The syntax is:
query.each(function (object, error) {
// Your function code
}, {
useMasterkey: true
})
Where object is a result for the query and error is a possible error that happened.
But, as shown here, it's better to just use useMasterKey for when you're actually changing something in the database:
query.each(function (object, error) {
object.destroy({
success: function (object) {
console.log("Successfully destroyed object.")
},
error: function (error) {
console.log("Error: " + error.code + " - " + error.message)
},
useMasterKey: true
})
})

Dynamic / Changing variable in AJAX get Request

I have a page on a project I'm developing that is attempting to make an ajax request with a specific value assigned by the button's (there are multiple) id tag. This works; the value is successfully passed and an ajax call is triggered on every click.
When I try to make the call again to the same page with a different button the variables are reassigned however the GET request that is sent remains unchanged.
How do I pass a NEW variable (in this case id) passed into the GET request?
function someAJAX(target) {
var trigger = [target.attr('id')];
console.log[trigger];
$.ajax({
// The URL for the request
url: "onyxiaMenus/menuBase.php",
// The data to send (will be converted to a query string)
data: {
//class: target.attr("class"),
tableCall: true,
sort: trigger,
sortOrder: 'DESC',
},
// Whether this is a POST or GET request
type: "GET",
// The type of data we expect back
//The available data types are text, html, xml, json, jsonp, and script.
dataType: "html",
// Code to run if the request succeeds;
// the response is passed to the function
success: function (data) {
console.log("AJAX success!");
$('#prop').replaceWith(data);
}
,
// Code to run if the request fails; the raw request and
// status codes are passed to the function
error: function (xhr, status, errorThrown) {
console.log("Sorry, there was a problem!");
console.log("Error: " + errorThrown);
console.log("Status: " + status);
console.dir(xhr);
}
,
// Code to run regardless of success or failure
complete: function (xhr, status) {
console.log("The request is complete!");
$('#view').prepend(xhr);
}
});
}
$(document).ready(function () {
$(".sort").on( "click", function (e) {
//e.stopPropagation();
//e.preventDefault();
target = $(this);
//console.log(target.attr("class"));
console.log(target.attr("id"));
/* ADD CHILDREN TO ELEMENT*/
if (target.hasClass('asc')) {
target.removeClass('asc')
} else {
target.addClass('asc')
}
/* MANAGE CLASS ADD/REMOVE FOR TARGET AND SIBLINGS */
if (target.hasClass('btn-primary')) {
} else {
target.addClass('btn-primary')
}
someAJAX(target);
target.siblings().removeClass('btn-primary');
})
});
Try to call your ajax like this someAJAX.bind(target)();
Then in function become
function someAJAX() {
$.ajax({
// The URL for the request
url: "onyxiaMenus/menuBase.php",
// The data to send (will be converted to a query string)
data: {
//class: this.attr("class"),
tableCall: true,
sort: this.attr('id'),
sortOrder: 'DESC',
},
// Whether this is a POST or GET request
type: "GET",
// The type of data we expect back
//The available data types are text, html, xml, json, jsonp, and script.
dataType: "html",
// Code to run if the request succeeds;
// the response is passed to the function
success: function (data) {
console.log("AJAX success!");
$('#prop').replaceWith(data);
}
,
// Code to run if the request fails; the raw request and
// status codes are passed to the function
error: function (xhr, status, errorThrown) {
console.log("Sorry, there was a problem!");
console.log("Error: " + errorThrown);
console.log("Status: " + status);
console.dir(xhr);
}
,
// Code to run regardless of success or failure
complete: function (xhr, status) {
console.log("The request is complete!");
$('#view').prepend(xhr);
}
});
}
trigger doesn't seem to be defined anywhere. That's the only data that would be changing between your requests as the other ones are statically coded.
You just need to make sure trigger is defined and changes between the two requests.
Thanks for the input on this problem. I got down to the bottom of my problem. My requests were being handled correctly but dumping the tables was creating syntax errors preventing the appending of new information to my page.
Thanks for the quick replies!
It wall works now.

recpatcha returns 200, still get error with jQuery ajax

All of my other searches yield responses about cross-domain requests. It appears that I'm not having a problem with that. I'm getting a response from the recaptcha server, but it's not being interpreted correctly.
<script>
function verifyCaptcha() {
jQuery.ajax({
method: "POST" ,
url: "https://www.google.com/recaptcha/api/siteverify",
data: { secret: "xxxxxxxxxxxxxxxxxxx" , response: "<% $recaptcha_response %>" },
dataType: 'jsonp' ,
success: function( result ) {
alert( result.success ) ;
},
error: function( xhr ) {
alert('Request Status: ' + xhr.status + ' Status Text: ' + xhr.statusText + ' Response Text: ' + xhr.responseText);
}
})
}
onload=verifyCaptcha ;
</script>
This function lives in a page that's the target of a submitted form. When I check fireBug for the results, I get this in my alert message:
Request Status: 200 Status Text: success Response Text: undefined
And the response captured by FireBug is
{
"success": true
}
It seems that it gets mad without the parens wrapped around the returned JSON which I thought were supposed to come free with dataType: 'jsonp'
How do I resolve the success of this?
UPDATE
Adding additional return parameters to the error funcion: ( xhr , message , errorThrown ) produced the following:
Request Status: 200
Status Text: success
Response Text: undefined
Message: parsererror
ErrorThrown: Error: jQuery1120043068059910713263_1455115913634 was not called
I'm guessing that the jQuery1120043068059910713263_1455115913634 was not called message is the callback function randomly named by jQuery. Does this mean that I need to add something to my logic, or that the reCaptcha server does not indeed support jsonp ?
Setting the dataType to "json" gives me a request status of 0.
UPDATE 2
I added this to my function:
jsonp: false,
jsonpCallback: 'onJSONPLoad',
and my errorThrown text changed to:
Error: onJSONPLoad was not called which leads me to conclude that reCaptcha does not support jsonp. Can anyone confirm this?
I guess the Answer is:
The POST method is not available for jsonp, only GET
update:
As well as in the comment stated setting the dataType to"json" and it will automatically converted to jsonp, maybe try that
also you can add a third argument to the error function
error: function( xhr, message, errorThrown ) {
and errorThrown maybe is more explicit

Tried all jquery methods and js to check for file exist but all doesn't work

Tried all jquery methods and js to check for file exist but all doesn't work all give me that any file that exist or doesn't on my server / with my domain that it does exist although some dont... idk why it say that all does although they dont?!!! maybe something wrong with my server? idk :( i need help tried all of that
$.get('http://MyUrl/file.wav')
.done(function() {
alert('exists');
}).fail(function() {
alert('does not exist');
})
&
$.ajax({
url: 'http://MyUrl/file.wav', //or your url
type: 'GET',
success: function(data){
alert('exists');
},
error: function(data){
alert('does not exist');
},
})
&
function doesFileExist(urlToFile)
{
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://MyUrl/file.wav', false);
xhr.send();
if (xhr.status == "404") {
//return false;
console.log('not exist');
} else {
//return true;
console.log('file with that name exists exists');
}}
&
$.ajax({
url:'http://MyUrl/file.wav',
type:'HEAD',
error: function()
{
//file not exists
},
success: function()
{
//file exists
console.log('file with that name exists exists');
}
});
idk what else i do really but it frustrate me that it always give me exists or true no matter file exists or not.....
I guess you are using rewrite rules on your server? If yes, most likely your server is rewriting your requests for non-existing files and you are getting response from some script which handles requests. Did you check response from your server? For example, open developer tools in chrome browser and then open the url of non-existing file in chrome, what do you see in network tab of developer tools? If you are always getting 200 http response, you will need to change your rewrite conditions or modify your script to check for file existence and send back 404 if file does not exist.
$.get("/path/to/file/")
.always(function(data, textStatus, errorThrown) {
// if file does not exist, or `error` , log `textStatus`, `errorThrown`
if (textStatus !== "success") console.log(textStatus, errorThrown);
// else, log response `data`
else console.log(data);
});
Create a new route for ajax
Server side:
echo json_encode(new Array(exists => file_exists(filePath + $_POST['filename]));
Client side:
$.ajax({
url:'http://MyUrl/fileexists.php', // new route
type:'POST', // post data
data: { filename: 'new.wav' }, // data to post
dataType: 'json', // returned data type
error: function()
{
//file not exists
},
success: function(resp) {
//file exists?
console.log('file with that name exists exists?' + resp.exists);
}
});

Categories

Resources