I am currently developping a new website
When I am trying to create an account, I get an error like this :
Uncaught TypeError: Cannot read property 'hasError' of null.
And this is the code
function submitFunction()
{
$('#create_account_error').html('').hide();
//send the ajax request to the server
$.ajax({
type: 'POST',
url: baseUri,
async: true,
cache: false,
dataType : "json",
data: {
controller: 'authentication',
SubmitCreate: 1,
ajax: true,
email_create: $('#email_create').val(),
back: $('input[name=back]').val(),
token: token
},
success: function(jsonData)
{
if (jsonData.hasError())
{
var errors = '';
for(error in jsonData.errors)
//IE6 bug fix
if(error != 'indexOf')
errors += '<li>'+jsonData.errors[error]+'</li>';
$('#create_account_error').html('<ol>'+errors+'</ol>').show();
}
else
{
// adding a div to display a transition
$('#center_column').html('<div id="noSlide">'+$('#center_column').html()+'</div>');
$('#noSlide').fadeOut('slow', function(){
$('#noSlide').html(jsonData.page);
// update the state (when this file is called from AJAX you still need to update the state)
bindStateInputAndUpdate();
$(this).fadeIn('slow', function(){
document.location = '#account-creation';
});
});
}
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
alert("TECHNICAL ERROR: unable to load form.\n\nDetails:\nError thrown: " + XMLHttpRequest + "\n" + 'Text status: ' + textStatus);
}
});
}
It seems to be the jsonData, on the function, which is not working as well. Any idea or suggestions?
The success handler will be passed the data returned from the ajax request.
It will not have a function called hasError() because it is just a json object it will not have any functions.
The error handler should be fired if there is an http error i.e. if the ajax call returns an http 500.
I'm not familiar with prestashop, but looking over the prestashop documentation hasError is returned as a bool (not a function), so instead try (without the parenthesis).
if (jsonData.hasError)
You may also want to check if any data is returned first.
if (jsonData)
Related
This javascript within an Office js add-in always fails when making a get request:
function update() {
Excel.run(function (ctx) {
return ctx.sync()
.then(function () {
var company = $('#company').val();
var environment = $('#environment').val();
var apiUrl = "https://localhost:44321/api/Country";
var params = "company=" + company + "&environment=" + environment;
$.getJSON(apiUrl, params)
.done(function (result) {
showNotification(result.length);
})
.fail(function (xhr, status, error) {
//showNotification(error.statusText);
showNotification(error.length);
});
});
}).catch(function (error) {
showNotification(error);
});
}
I can see the json being returned successfully within Fiddler and JSONLint says the json is valid. Here it is:
[{"country":"UK","countryLongName":"United Kingdom","currency":"GBP"}]
I'm running on localhost with https, and have the following AppDomains in my manifest (belt and braces):
<AppDomain>https://localhost:44321/api/Country</AppDomain>
<AppDomain>https://localhost:44321</AppDomain>
<AppDomain>https://localhost</AppDomain>
However, getJSON.fail() is always invoked, with the following parameters:
xhr.responseJSON: undefined
xhr.statusText: "error"
status: "error"
error: ""
Why does getJSON always fail?
Further edit
I've tried this js instead...
$.ajax({
url: apiUrl,
dataType: 'json',
async: false,
data: params,
success: function (data) {
showNotification(data);
},
error: function (msg) {
showNotification('error : ' + msg.d);
}
});
...and now the error function is being invoked with the following parameters:
msg.responseJSON: undefined
msg.status: 0
msg.statusText: "NetworkError"
It's all to do with CORS, I found the solution in rick-strahl's post:
https://weblog.west-wind.com/posts/2016/Sep/26/ASPNET-Core-and-CORS-Gotchas#ApplythePolicy
Specifically,
"UseCors() has to be called before UseMvc()
Make sure you declare the CORS functionality before MVC so the middleware fires before the MVC pipeline gets control and terminates the request."
I am working on a piece of code where the user clicks on a button to make a call and the status of the call is displayed to him/her.
Everything is working fine and the calls are being made too, but the server which sends the json response is on another domain and I have no control over its response. I therefore used jsonp to get the response, but no matter what i did, i keep getting the error of Uncaught SyntaxError: Unexpected token.
I am attaching my code. please help as this is a live project and I am badly stuck in it. I need a response to be alerted with the message received by the server. the message received by the server in case of success is {"success": {"status": "success", "message": "Call successfully placed"}} and in case of error is {"error": {"message": "Invalid API Key"}}. I just need to display the message part.
my code:
function makecall() {
document.getElementById('<%=click2call_submitbtn.ClientID%>').disabled = true;
var agentNum = document.getElementById('<%=lblCallFrom.ClientID%>').innerHTML;
var custNum = "+91";
custNum = custNum + document.getElementById('<%=txtNotoCall.ClientID%>').value;
document.getElementById('<%=lblCallStatus.ClientID%>').innerHTML = "Calling...";
if (validatePhone(agentNum) && validatePhone(custNum)) {
$.ajax({
url: 'http://www.knowlarity.com/vr/api/click2call/?api_key=9e69eab0-1ec7-11e3-866c-16829204aaa4&agent_number=agent_number_variable&phone_number=Caller_number_variable&sr_number=%2B918881692001&response_format=json'.replace('Caller_number_variable', custNum.replace('+', '%2B')).replace('agent_number_variable', agentNum.replace('+', '%2B')),
type: 'GET',
cache: false,
dataType: 'jsonp',
success: function (res) {
alert(JSON.stringify(res));
},
error: function (res) {
alert(JSON.stringify(res));
}
});
} else {
document.getElementById('<%=lblCallStatus.ClientID%>').innerHTML = "Num. should be a valid 10 digit mobile no.";
document.getElementById('<%=click2call_submitbtn.ClientID%>').disabled = false;
}
}
Try using this as an absolute minimum where you can pass in valid hard wired values for the numbers:
var url = 'http://ip.jsontest.com/ ';
$.ajax({
url: url,
cache: false,
dataType: 'jsonp',
success: function (res) {
if (res != undefined) console.log(res);
},
error: function (res) {
if (res != undefined) console.log(res);
}
});
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.
This is related to my previous question. The answer there seemed to solve the problem.
But I am literally doing the exact same thing from another route, and now I get an error. The application passes over the ajax function twice. The first time, I get a TypeError. If I reload the page, then the function executes correctly.
I know in the docs, it mentions having to create and object that is defined. Could somebody point me to an example of how extended controller needs to be created in order to execute a function when it is called.
I get an error: TypeError: this.init is undefined
Here is my route:
App.RegisterPickRoute = Em.Route.extend({
redirect: function() {
var registerTestController=this.controllerFor('registerTest')
var isRegistered=registerTestController.registerContacts();
if(!isRegistered)
this.transitionTo('registerTest');
else
alert('holla')
}
});
Here is my function in my controller:
registerContacts: function(){
var isRegistered=false;
var self=this
self.contactsToAdd=self.get('contactList').filterProperty('isSelected', true);
$.ajax({
type: 'POST',
cache: false,
url: contextPath + 'user/regTest',
data:{contactList:self.contactsToAdd},
success: function(data) {
isRegistered=true;
},
error: function(jqXHR, textStatus, errorThrown) {
isRegistered=false;
},
async: false
});
return isRegistered
}
I have a syntax error. The value passed to the data attribute of the ajax call needs to be self.contactsToAdd.toArray()
I am using jQuery to make an AJAX request to a remote endpoint. That endpoint will return a JSON object if there is a failure and that object will describe the failure. If the request is successful it will return HTML or XML.
I see how to define the expected request type in jQuery as part of the $.ajax() call. Is there a way to detect the request type in the success handler?
$.ajax(
{
type: "DELETE",
url: "/SomeEndpoint",
//dataType: "html",
data:
{
"Param2": param0val,
"Param1": param1val
},
success: function(data) {
//data could be JSON or XML/HTML
},
error: function(res, textStatus, errorThrown) {
alert('failed... :(');
}
}
);
Have you application generate correct Content-Type headers (application/json, text/xml, etc) and handle those in your success callback. Maybe something like this will work?
xhr = $.ajax(
{
//SNIP
success: function(data) {
var ct = xhr.getResponseHeader('Content-Type');
if (ct == 'application/json') {
//deserialize as JSON and continue
} else if (ct == 'text/xml') {
//deserialize as XML and continue
}
},
//SNIP
);
Untested, but it's worth a shot.
how about using the complete option?
$.ajax({
...
complete : function(xhr, status) {
// status is either "success" or "error"
// complete is fired after success or error functions
// xhr is the xhr object itself
var header = xhr.getResponseHeader('Content-Type');
},
...
});
By the time it calls your success handler, the data has already been deserialized for you. You need to always return the same data type for any successful result. If there truly is an error, you should probably throw an exception and let it get handled by the error callback instead. This should be able to parse the resulting error and package it for your callback, that is, it will detect that the response did not have 200 OK status and parse the result to obtain the error information.