prototype javascript ajax request runs back end perl script but continues to return 500 - ajax

Newbie to this - This code is works - in that the call to the script does what it is supposed to but returns the condition 500 and I can not see why. I am looking for any suggestions or changes that I should be making to make this work.
Thanks to all who respond.
function get_update_odometer(vehicle_key,odometer_value){
var url = "[%Catalyst.uri_for('/invoice/dispatch_util/get_update_odometer')%]";
new Ajax.Request(url, {
method: 'get',
parameters: {
key: vehicle_key,
ovalue: odometer_value
},
asynchronous:false,
onSuccess: successFunc,
onFailure: failureFunc
});
var return_v = $('rcontainer').innerHTML;
document.getElementById('odometer').value = return_v;
return true;
}
function successFunc(response){
if (200 == response.status){
var container = $('rcontainer');
var content = response.responseText;
container.update(content);
}
}
function failureFunc(response){
alert("Call has failed " + response.status );
}

Error code is coming from server side, and you provided the client part.
So have a look if your server script get_update_odometer is working, is callable by your web server and etc ...

Related

Ajax request with CORS redirect fails in IE11

I'm trying to make an ajax request to a resource on the same domain. Under certain circumstances the request gets redirected(303) to an external resource. The external resource supports CORS.
In browsers like Chrome, Firefox or Safari the request succeeds.
In IE11 the request fails with error:
SCRIPT 7002: XMLHttpRequest: Network Error 0x4c7, The operation was canceled by the user
The ajax request is made with jQuery:
$.ajax({
url: "/data",
type: "POST",
dataType: "json",
contentType: "application/json;charset=UTF-8",
data: JSON.stringify({name: 'John Doe'})
}).done(function () {
console.log('succeeded');
}).fail(function () {
console.log('failed');
});
I've build a little example which demonstrates the problem. You could see the code here.
w/o redirect
w/ redirect
Is there a way to solve this problem? What am I missing?
In the initial definition of the CORS-standard, redirects after a successful CORS-preflight request were not allowed.
IE11 implements this (now outdated) standard.
Since August 2016, this has changed, and all major browsers now support it (Here's the actual pull request).
I'm afraid to support <=IE11 you'll have to modify your server-side code as well to not issue a redirect (at least for <=IE11).
Part 1) Server-side (I'm using node.js express here):
function _isIE (request) {
let userAgent = request.headers['user-agent']
return userAgent.indexOf("MSIE ") > 0 || userAgent.indexOf("Trident/") > 0
}
router.post('data', function (request, response) {
if (_isIE(request)) {
// perform action
res.set('Content-Type', 'text/plain')
return res.status(200).send(`${redirectionTarget}`)
} else {
// perform action
response.redirect(redirectionTarget)
}
})
Part 2 Client-side
Note: This is pure Javascript, but you can easily adapt it to your jQuery/ajax implementation.
var isInternetExplorer = (function () {
var ua = window.navigator.userAgent
return ua.indexOf("MSIE ") > 0 || ua.indexOf("Trident/") > 0
})()
function requestResource (link, successFn, forcedRedirect) {
var http
if (window.XMLHttpRequest) {
http = new XMLHttpRequest()
} else if (window.XDomainRequest) {
http = new XDomainRequest()
} else {
http = new ActiveXObject("Microsoft.XMLHTTP")
}
http.onreadystatechange = function () {
var OK = 200
if (http.readyState === XMLHttpRequest.DONE) {
if (http.status === OK && successFn) {
if (isInternetExplorer && !forcedRedirect) {
return requestResource(http.responseText, successFn, true)
} else {
successFn(http.responseText)
}
}
}
}
http.onerror = http.ontimeout = function () {
console.error('An error occured requesting '+link+' (code: '+http.status+'): '+http.responseText)
}
http.open('GET', link)
http.send(null)
}
its already answered - have a look - https://blogs.msdn.microsoft.com/webdev/2013/10/28/sending-a-cors-request-in-ie/

Wait for node.js callback to be completed before ending AJAX request

I am using jQuery on the front to make an AJAX post request using $.post(). I also pass a success function which will do something with the data returned. On my node.js server, I am using express to handle requests, the post request calls another function passing a callback which in the callback does a res.send(). How can I get the request not to finish until the callback is done?
My client-side code is:
$.post("/newgroup/", {name: newgroupname}, function(data) {
console.log(data); // Returns undefined because requests ends before res.send
});
My server-side code is:
app.post('/newgroup/', function(req, res){
insertDocument({name:req.body.name, photos:[]}, db.groups, function(doc){
res.send(doc);
});
});
The insertDocument function is:
function insertDocument(doc, targetCollection, callback) {
var cursor = targetCollection.find( {}, {_id: 1}).sort({_id: -1}).limit(1);
cursor.toArray(function(err, docs){
if (docs == false){
var seq = 1;
}
else {
var seq = docs[0]._id + 1;
}
doc._id = seq;
targetCollection.insert(doc);
callback(doc);
});
}
If the code you've shown us is the real code then the only possibility is that the thing you are returning doc is actually undefined. The callback on the client will not fire before res.send() is triggered.
Are you sure that the callback in insertDocument is exactly as you think? Often callbacks are of the form function(err,doc), i.e. try this:
app.post('/newgroup/', function(req, res){
insertDocument({name:req.body.name, photos:[]}, db.groups, function(err, doc){
res.send(doc);
});
});
Okay I found the answer, I am not sure why this works, I just had to change the name of the variable I was sending to the callback, I assume this is because it had the same name as a parameter, so I changed my insertDocument function to look like this
function insertDocument(doc, targetCollection, callback) {
var cursor = targetCollection.find( {}, {_id: 1}).sort({_id: -1}).limit(1);
cursor.toArray(function(err, docs){
if (docs == false){
var seq = 1;
}
else {
var seq = docs[0]._id + 1;
}
doc._id = seq;
targetCollection.insert(doc);
var new_document = doc;
callback(new_document);
});
}
Could it be a sync/async issue? I don't know what library you are using for your saves, but is it a case were the call should be something more like this?
targetCollection.insert(doc, function(err, saveddoc) {
if (err) console.log(err);
callback(saveddoc);
});

not getting response from ajax call in codeigniter

I am trying to check if the user name is available for use using ajax and codeigniter. I have problem to get the response from the codeingniter controller in my js. file but without success.
Here is the controller function, relevant to the question:
if ($username == 0) {
$this->output->set_output(json_encode(array("r" => true)));
} else {
$this->output->set_output(json_encode(array("r" => false, "error" => "Username already exits")));
}
Rest assured that I do get 1 if username already exists in thedatabase and 0 if it does not exist.
I have the following js.file
// list all variables used here...
var
regform = $('#reg-form'),
memberusername = $('#memberusername'),
memberpassword = $('#memberpassword'),
memberemail = $('#memberemail'),
memberconfirmpassword = $('#memberconfirmpassword');
regform.submit(function(e) {
e.preventDefault();
console.log("I am on the beggining here"); // this is displayed in console
var memberusername = $(this).find("#memberusername").val();
var memberemail = $(this).find("#memberemail").val();
var memberpassword = $(this).find("#memberpassword").val();
var url = $(this).attr("action");
$.ajax({
type: "POST",
url: $(this).attr("action"),
dataType: "json",
data: {memberusername: memberusername, memberemail: memberemail, memberpassword: memberpassword},
cache: false,
success: function(output) {
console.log('I am inside...'); // this is never displayed in console...
console.log(r); // is never shonw in console
console.log(output); is also never displayed in console
$.each(output, function(index, value) {
//process your data by index, in example
});
}
});
return false;
})
Can anyone help me to get the username value of r in the ajax, so I can take appropriate action?
Cheers
Basically, you're saying that the success handler is never called - meaning that the request had an error in some way. You should add an error handler and maybe even a complete handler. This will at least show you what's going on with the request. (someone else mentioned about using Chrome Dev Tools -- YES, do that!)
As far as the parse error. Your request is expecting json data, but your data must not be returned as json (it's formatted as json, but without a content type header, the browser just treats it as text). Try changing your php code to this:
if ($username == 0) {
$this->output->set_content_type('application/json')->set_output(json_encode(array("r" => true)));
} else {
$this->output->set_content_type('application/json')->set_output(json_encode(array("r" => false, "error" => "Username already exits")));
}

response.responseText adds previous responseText (node.js, prototype)

This is my node.js function that uses res.write:
function: ping(){
res.write(JSON.stringify({"datatype":"ping"}));
setTimeout(ping, 30000);
}
This is the client, request written in prototype:
this.pushconnection = new Ajax.Request(pushserveraddress, {
method: 'get',
evalJSON: 'false',
onInteractive: this.pushconnectionInteractive.bind(this)
});
}
pushconnectionInteractive: function(response) {
}
The problem is that response.responseText will grow with every res.write that comes through.
Example:
1st ping() received: response.responseText = {"datatype":"ping"}
2nd ping() received: response.responseText = {"datatype":"ping"}{"datatype":"ping"}
3rd ping() received: response.responseText = {"datatype":"ping"}{"datatype":"ping"}{"datatype":"ping"}
I'm not sure if node.js is re-sending the data, or if prototype is storing the data. What I need to do is have response.responseText = the last data sent without using res.end();
You're probably calling this.pushconnection more than once.
If you instantiate this.pushconnection as it's own Ajax Object and continue to use the same ajax object then your response will grow.
Try this instead:
this.pushconnection = function (pushserveraddress) {
return new Ajax.Request(pushserveraddress, {
method: 'get',
evalJSON: 'false',
onInteractive: this.pushconnectionInteractive.bind(this)
});
}
Then you can call this by saying:
var ajax = this.pushconnection("example.com");
every response add to previous one, to get last object sent if u use that php function :
(1st add headers)
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('connection: keep-alive');
(2 send data)
function send_message($data_array) {
echo json_encode($data_array).PHP_EOL;
ob_flush();
flush();
}
in your js (Prototype): to get last response
new Ajax.Request(sUrl, {
onInteractive:function(xhr){
var lastString = xhr.responseText.split("\n");
var lastObjectSent = lastString[lastString.length-2].evalJSON();
if(lastObjectSent.bValid){
if(parseInt(lastObjectSent.bValid,10) === 1){
this.status="finished";
loadPage('done.php');
}else{
setNotification(oResult.sText,"Failure",5000);
}
}else if(lastObjectSent.progress){
$('duplicatePassDates').down('.bar').setStyle('width:'+lastObjectSent.progress+'px');
}
},
onSuccess:function(xhr){
if(this.status!=="finished"){
this.onInteractive(xhr);
}
},

AJax Testing - Add a delay

I'm trying to run some tests on some Ajax code we have written, now obviously when tested locally it runs very fast and is great. I need to enforce a delay of 3 seconds so that I can see that the loader is being displayed and the user experiance is good enough.
I have tried the following but recieve the error "Useless settimeout" any other suggestions to achieve this? Any browser plugins?
$('#formAddPost').submit(function() {
//Load the values and check them
var title = $(this).find('#Title');
var description = $(this).find('#Description');
var catId = $(this).find('#Categories');
if (ValidateField(title) == false || ValidateField(description) == false) {
$('.error-message').show();
return false;
}
$('.error-message').hide();
//Show the loading icon
$('.add-post').hide();
$('.add-post-loader').show();
//Temp for testing - allows the showing to the loader icon
setTimeout(MakeAJAXCall(title.val(), catId.val(), description.val()), 1500);
return false;
});
function MakeAJAXCall(title, catId, description) {
$.ajax({
url: "/Message/CreatePost/",
cache: false,
type: "POST",
data: ("title=" + title + "&description=" + description + "&categories=" + catId + "&ajax=1?"),
dataType: "html",
success: function(msg) {
$('#TableMessageList').replaceWith(msg);
$('.add-post-loader').hide();
$('.add-post').show();
}
});
}
As you're testing your page for a delay in the server response, can you put a delay in the server side code instead of client side?
You might be able to do that using fiddler.
The examples scripts include some samples that pause the response.
Would this tool from jsFiddle.net be helpful?
Echo Javascript file and XHR requests
http://doc.jsfiddle.net/use/echo.html

Resources