i have a javascript function to call ajax to write some stuff to database. So far it has worked on chrome and firefox without any problem. However, Safari randomly fails without much clue. (This is tested within localhost)
This is the error :
write failed : {"readyState":0,"status":0,"statusText":"error"}
This is my ajax function :
function writeToDB() {
var data = {
setting: 'some data'
} ;
$.ajax({
type: "POST",
url: 'Admin/write_to_db',
data: {
data:
btoa(unescape(encodeURIComponent(JSON.stringify(data))))
},
success: function(response) {
consoe.log('success');
console.log('response : ' + JSON.stringify(response));
},
error: function(response) {
console.log('write failed : ' +
JSON.stringify(response));
},
complete: function(response) {
console.log('completed');
},
});
}
I simplified the actual function for ease of reading. I have tried many similar responses given for a similar problem but nothing worked. Pls help me with this. Thank You.
Managed to fix the problem.
The above function writeToDB is triggered by a button click. So all that i had to do is add
event.preventDefault()
to the function. That worked!
Related
I am sending a post request to the REST web service using the following code:
<script type="application/javascript">
$(document).ready(function() {
$("#logbutton").click(function(event){
$.post(
"http://localhost:8080/CredentialsOnDemand/loginexpert/dologin",
{
ephone: $("#mobile").val(),
epassword: $("#password").val()
},
function(data) {
data = $.parseJSON( data );
$(".ray").html("$" + data.tag);
console.log( "You clicked a paragraph!" );
}
);
});
});
The web service gives a JSON response in format below:
{"tag":"login","status":true}
The call from the jquery code is running i.e. the web service is running fine, but the function that I have created to parse JSON is not working.
NOTE:
I tried to run this code without providing any value in the text field. The console displayed the json response and also console.log line. But when I again entered the values into the fields, then it didn't. I am unable to understand this thing.
Anyone having any idea?
Thanks in advance.
You could try the more verbose and detailed form using $.ajax:
$(document).ready(function() {
$("#logbutton").click(function(event) {
var req = {
ephone: $("#mobile").val(),
epassword: $("#password").val()
};
$.ajax({
url: "http://localhost:8080/CredentialsOnDemand/loginexpert/dologin",
data: req,
dataType: 'json',
type: 'POST'
}).done(function(data) {
console.log(data);
$(".ray").html("$" + data.tag);
console.log("You clicked a paragraph!");
}).fail(function(err) {
console.error(err);
});
});
});
This will be easier for you to pinpoint where the error is coming from
I have the following json response:
{"data":[{"series":{"id":"15404","series_code":"TOS","publisher_id":"280","series_short_name":"Tales
of
Suspense","start_year":"1959","end_year":"1968","published":"1959-1968","type_id":"1","no_issues":"99","published_gcd":"January
1959-March 1968","series_long_name":"Tales of Suspense (Marvel
1959-1968)","volume":"1","first_issue":"1","last_issue":"99","comment":"","created_date":"2013-03-24
01:00:00","user_id":"1","last_updated":"2013-03-24
01:00:00","note":"","is_active":"1","wiki_stem":null}}],"error":"boo"}
Here is the ajax call:
$.ajax({
type: 'get',
url: '/series/lookup?year='+json.IssueYear+'&title='+json.Title,
beforeSend: function(xhr) {xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
},
success: function(response) {
if (response.error) {
alert(response.error);
console.log(response.error);
}
else {
//console.log(response.content);
alert(response.data[0].series.id);
}
},
error: function(e) {
alert("An error occurred: " + e.responseText.message);
console.log(e);
}
});
I would have thought that this would return the id but it says data is undefined?
alert(response.data[0].series.id)
I must be missing something, any help appreciated.
Need a little bit more information. How are you getting the response back to your code? if this was JQuery, I know that this would work:
$.post("/path/to/script.php", {
var1: 'test',
var2: 'test2'
}, function(response) {
alert(response.data[0].series.id); // This will work here
}, 'json');
That said, this little snippet shows what would work. Without know what your javascript code is, it makes it very near impossible to determine if what you are doing is right or wrong.
I have the following ajax post:
$.ajax({
type: "POST",
url: "http://sampleurl",
data: {
'email':$('#email').val(),
'password':$('#password').val(),
},
cache: false,
async: false,
crossDomain: "true",
beforeSend: function() { },
complete: function() { },
success: function(resp) {
alert(resp);
var result = $.parseJSON(resp);
if (result.result == "Success") {
alert(emailID,password);
}
else {
alert(result.msg);
}
},
error: function(request, status, error) {
//$("#LoadingImage").hide();
alert("Result = " + error);
}
});
return false;
});
It is returning with this error: NETWORK_ERR: XMLHttpRequest Exception 101 on android tablet.
I have read a bunch of SO posts on this error, most suggest that I set async to true. This DOES remove the error message- but it is still an error, and I never get valid data. It just seems to remove the error message which is not helpful.
Please help me.
Finally i got solution.. Android 4.1 and 4.2 introduce this new method: getAllowUniversalAccessFromFileURLs
Since it's not working on API below 16 the solution needs some few more lines, to assure that this inexistent method do not cause errors in previous API.
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= android.os.Build.VERSION_CODES.JELLY_BEAN){
fixNewAndroid(webView);
}
#TargetApi(16)
protected void fixNewAndroid(WebView webView) {
try {
webView.getSettings().setAllowUniversalAccessFromFileURLs(true);
} catch(NullPointerException e) {
}
try use location in your domain , like ./directory/yourfile.php
I have this problem in IE7
I'm using the Ajax.Request in prototype.js(1.6) like this:
new Ajax.Request(URL, {method: "get",
onSuccess: cbFn,
onCreate: function(req) {
$("fetchBtn").value = "Fetching..."
},
onFailure: function(req){
console.log(req)
alert("nima")
},
parameters: {"id": pmid}});
however there is a bug in cbFn, and when cbFn is called by Ajax.Request, it just stops in the statement which has bugs. However, it just stops silently that I can not see the error information in Firebug. I also tried onFailure, but it seems that it is not even called when onSuccess is failed.
Does anyone have ideas about how to check the debug information of cbFn function? Thanks!
I saw you have been use jquery in your java script. In that case, you can using the jquery ajax GET/POST to solve your problem with effiency.
Some thing like that:
jqxhr = $.get("example.php", function() {
alert("success");
})
.done(function() { alert("second success"); })
.fail(function() { alert("error"); })
.always(function() { alert("finished"); });
jquery do better in multiple browser for you
I am trying to POST some data to my ASP.Net MVC Web API controller and trying to get it back in the response. I have the following script for the post:
$('#recordUser').click(function () {
$.ajax({
type: 'POST',
url: 'api/RecordUser',
data: $("#recordUserForm").serialize(),
dataType: 'json',
success: function (useremail) {
console.log(useremail);
},
error: function (xhr, status, err) {
},
complete: function (xhr, status) {
if (status === 'error' || !xhr.responseText) {
alert("Error");
}
else {
var data = xhr.responseText;
alert(data);
//...
}
}
});
});
The problem with this script is that whenever I try to post the data, the jQuery comes back in "error" instead of "success".
I have made sure that there is no problem with my controller. I can get into my api method in debug mode whenever the request is made and can see that it is getting the data from the POST request and is returning it back. This controller is quite simple:
public class RecordUserController : ApiController
{
public RecordUserEmailDTO Post(RecordUserEmailDTO userEmail)
{
return userEmail;
}
}
I am not sure how I can get jQuery to print out any useful error messages. Currently when I try to debug the jQuery code using Chrome console it shows an empty xhr.responseText, nothing in "err" object and "status" set to "error" which as you see is not quite helpful.
One more thing that I have tried is to run the following code directly from the console:
$.ajax({
type: 'POST',
url: 'api/RecordUser',
data: {"Email":"email#address.com"},
dataType: 'json',
success: function (useremail) {
console.log(useremail);
},
error: function (xhr, status, err) {
console.log(xhr);
console.log(err);
console.log(status);
alert(err.Message);
},
complete: function (xhr, status) {
if (status === 'error' || !xhr.responseText) {
alert("Error");
}
else {
var data = xhr.responseText;
alert(data);
}
}
});
i.e. using the same script without actually clicking on the button and submitting the form. Surprisingly, this comes back with the right response and I can see my data printed out in console. For me this atleast means that my Web API controller is working fine but leaves me with no clue as to why it is not working on clicking the button or submitting the form and goes into "error" instead of "success".
I have failed to find any errors in my approach and would be glad if someone could help me in getting a response back when the form is posted.
As suggested by Alnitak, I was using complete callback along with success and error ones. Removing complete from my code fixed the issue.
Thanks to Alnitak.