I'm using the recommendations laid down here (http://www.odetocode.com/articles/473.aspx) to write a JavaScript AJAX webchat system using simulated Namespacing and prototyping.
In one of my prototype methods I'm calling the $.ajax method in jQuery. What I then want to do is pass the returned JSON data into a method inside my JavaScript webchat namespace.
The problem seems to be because I've created an instance of my JavaScript webchat, I can't directly call a method inside it because I need to address it through the instance.
The key part in the code below is
success: function(data, textStatus) {
this.GetUpdate_Success(data)
},
I'm thinking because we're inside the $.ajax() method, that this no longer refers to our WebchatV3 object.
The full JavaScript code is shown below:
/// <reference path="/JavaScript/jquery-1.3.2-vsdoc2.js" />
// Simulated 'namespace'
var AvonAndSomerset = {}
// Chatroom run time data
AvonAndSomerset.WebchatV3 = function(memberId, passcode) {
this.Members = new Array(); // Members in the chatroom
this.Questions = new Array(); // The questions queue in the chatroom
// Details about the current user
this.currentMember = new AvonAndSomerset.WebchatV3.Member(memberId, passcode, null, null, null, null, null);
// Set-up AJAX defaults
$.ajaxSetup({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json"
});
}
AvonAndSomerset.WebchatV3.prototype = {
// Get latest Member,Quetsion,Transcript and Room data from server
GetUpdate: function(StartUp) {
$.ajax({
url: "JSON.aspx/Members_GetChanges",
data: "{ MemberID: " + this.currentMember.memberId + ", Passcode: \"" + this.currentMember.passcode + "\", ReturnAll: " + StartUp + " }",
success: function(data, textStatus) {
this.GetUpdate_Success(data)
},
error: function(result) {
alert('Members_GetChanges() failed: ' + result.responseText);
}
});
},
// Callback - on success of GetUpdate()
GetUpdate_Success: function(data) {
alert('The AJAX call was successful!');
},
// Does the MemberID exist in the local array?
Members_DoesExist: function(MemberID) {
alert('Searching for ' + MemberID);
alert(this.Members.length);
}
The easiest way to fix this is to create a variable that references this at the proper scope required. this and scope work differently in javascript then most languages, in this case it is referring to the object being passed into the function.
// Get latest Member,Quetsion,Transcript and Room data from server
GetUpdate: function(StartUp) {
//here
var self = this;
$.ajax({ url: "JSON.aspx/Members_GetChanges",
data: "{ MemberID: " + this.currentMember.memberId + ", Passcode: \"" + this.currentMember.passcode + "\", ReturnAll: " + StartUp + " }",
success: function(data, textStatus) {
self.GetUpdate_Success(data)
},
error: function(result) {
alert('Members_GetChanges() failed: ' + result.responseText);
}
});
},
Try
success: function(data, textStatus) {
AvonAndSomerset.WebchatV3.GetUpdate_Success(data)
},
That may work.
Related
The user of my Cordova/PhoneGap app has to sign in, so I group all the form's data into a Javascript array, then I JSON.strigify() it and I send it to the server via an Ajax request.
The PHP script has been tested by manually sending the CGI command, it does perfectly works.
Also, I used alert() to check if the function sendDataToServer() is called, it is.
The problem is that Ajax doesn't output success() neither error(). AND there is no difference (exept the command, obviously) with an other working script that I use for checking a login.
Note: I use GET for testing purposes, at the end it will be POST.
Here is the WORKING script:
$("#connectionFormSubmit").click(function () {
$.ajax({
type: "POST",
url: "http://" + host + "/my_app/check_login.php",
data: "login=" + $("#login-conn").val() + "&password=" + $("#password-conn").val(),
success: function (msg) {
navigator.notification.alert(msg, alertDismissed, 'Result', 'OK');
},
error: function (jqXHR, exception) {
navigator.notification.alert(getError(jqXHR, exception), alertDismissed, 'Error', 'OK');
}
});
});
Here is the NOT WORKING script:
function sendDataToServer(dataGuest, dataChild1, dataChild2, dataChild3) {
$.ajax({
type: "GET",
url: "http://" + host + "/my_app/insert_new_user.php",
data: "guest=" + dataGuest + "&child1=" + dataChild1 + "&child2=" + dataChild2 + "&child3=" + dataChild3,
/* async: false, not changing anything */
success: function (msg) {
navigator.notification.alert(msg, alertDismissed, 'Result', 'OK');
},
error: function (jqXHR, exception) {
navigator.notification.alert(getError(jqXHR, exception), alertDismissed, 'Error', 'OK');
}
});
}
(in both cases the server script works perfectly fine).
This is how I call the function:
sendDataToServer( JSON.stringify(dataGuest), JSON.stringify(dataChild1), JSON.stringify(dataChild2), JSON.stringify(dataChild3) );
I didn't find anything simiar to my problem on Google.
I need to pass a JSON array to to PHP, and receive it as $_POST['data']. This will contain my data through json_parse.
I got an error, no clue what happens here. The Ajax call throws the following error:
[object Object] parsererror SyntaxError: Unexpected token <
My code:
function testJson() {
var arr = { };
arr['action'] = "anaction";
arr['type'] = "atype";
$.ajax("test2.php", {
type: "POST",
data: JSON.stringify({ data: arr}),
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (data) {
$("#result").html(data);
},
error: function (a, b, c) {
$('#error').html(a + " " + b + " " + c);
}
});
More info: The error mentioned before is from error function call.
Edited based on suggestions and testing the function now works like this:
function testJson() {
var arr = { };
arr['action'] = "anaction";
arr['type'] = "atype";
$.ajax("test2.php", {
type: "POST",
data: {data : arr}, /* Stringify deleted and added an array there, i remove too a non needed json related stuff */
success: function (data) {
$("#result").html(data);
},
error: function (a, b, c) {
$('#error').html(a + " " + b + " " + c);
}
});
Now I'm recieving the array in post as expected.
Dilemma, boths answers helps in the solution of the problem .
Multiple issues here:
var arr = { }; defines an object whereas var arr = [ ]; defines an array.
The use as arr['action'] = "anaction"; implies, that it is an object and not an array although named so.
Usually, jQuery is doing the job internally:
$.ajax("test2.php", {
type: "POST",
data: { "data": arr} } // no need to stringify anything here ...
...
If you setting the dataType as 'json' in the ajax function, this means that the php file should return valid json. Use json_encode in your php file.
My coworker created a website with statistics that now I need to implement on a mobile app.
He used JavaScript and now I'm developing on Android.
I want to show one specific function from the JavaScript according to the Activity on Android.
I've been searching but it is not showing anything. Any ideas? Probably I'm missing something really logical, but I can't figure out.
Code from the web:
function GetUsersLastEventID(userID, labelID) {
var message = { UserID: userID };
$.ajax({
url: "GetData.aspx/GetUsersLastEventID",
type: "POST",
async: true,
data: JSON.stringify(message),
contentType: "application/json; charset=utf-8",
success: function (msg) {
$('#label' + labelID).text("UserID: " + userID + " was last seen in event : " + msg.d);
},
failure: function (response) {
$('#label' + labelID).text(eventTitle + ": INFORMATION UNAVAILABLE!");
console.log("Error in: GetUsersLastEventID(), params: " + userID);
}
});
}
Code from the call on Android:
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("javascript:GetUsersLastEventID(userID, labelID);");
may be you should pass userID and labelID as variable if every thing is okay with webservice call in javascript
webView.loadUrl("javascript:getUsersLastEventID("+userID+","+labelID+")");
I am looking for advice to ensure that I am using callbacks and javascript coding using generally accepted js guidelines. What is listed below is two functions which are chained together. Basically its a list of checks which need to be completed prior to creating the entity. I don't expect the final version to use a ajax POST but it is a good way to test all of the error handling.
Advice or recommendations would be appreciated!! I will give credit to the best explained and critiqued answer.
function relationship_check(app_label, model, company_id, params, form, callback_function){
// This will check to see if a relationship exists. This works even on new objects.
kwargs = $.extend({}, params);
kwargs['app_label'] = app_label;
kwargs['model'] = model;
kwargs['relationship__company'] = company_id;
kwargs['error_on_objects_exists_and_no_relation'] = true;
ajax_req = $.ajax({
url: "{% url 'api_get_discover' api_name='v1' resource_name='relationship' %}",
type: "GET",
data: kwargs,
success: function(data, textStatus, jqXHR) {
callback_function(form, params)
},
error: function(data, textStatus, jqXHR) {
results = $.parseJSON(data.responseText)
if (results['object_exists'] && ! results['relationships_exists']){
django_message(results['create_string'], "info");
} else {
django_message(results['error'], "error");
}
return false
}
})
return false
};
function create_community(form, data){
var self = $(this),
ajax_req = $.ajax({
url: self.attr("action"),
type: "POST",
data: data,
success: function(data, textStatus, jqXHR) {
django_message("Saved successfully.", "success");
},
error: function(data, textStatus, jqXHR) {
var errors = $.parseJSON(data.responseText);
$.each(errors, function(index, value) {
if (index === "__all__") {
console.log(index + " : " + value )
django_message(value[0], "error");
} else {
console.log(index + " : " + value )
apply_form_field_error(index, value);
}
});
}
});
}
$(document).on("submit", "#community_form", function(e) {
e.preventDefault();
clear_form_field_errors("#community_form");
var data = {
name: $(this).find("#id_name").val(),
city: $(this).find("#id_city").val(),
cross_roads: $(this).find("#id_cross_roads").val(),
website: $(this).find("#id_website").val(),
latitude: $(this).find("#id_latitude").val(),
longitude: $(this).find("#id_longitude").val(),
confirmed_address: $(this).find("#id_confirmed_address").val()
};
console.log(data)
relationship_check(
'community', 'community', '{{ request.user.company.id }}',
data, "#community_form", create_community);
});
I have this functions
//send JSON-RPC request
var json_rpc = (function() {
var id = 1;
return function(url, method, params, success) {
if (typeOf(params) != 'array') {
params = [params];
}
var request = JSON.stringify({
'jsonrpc': '2.0',
'method': method,
'params': params,
'id': id++});
return $.ajax({
url: url,
data: request,
success: success,
error: function (XMLHttpRequest, textStatus, errorThrown) {
error_msg('XHR error ' + XMLHttpRequest.status + ' ' +
XMLHttpRequest.responseText);
},
beforeSend: function(xhr) {
console.log('before send');
console.log(dir(xhr));
xhr.onreadystatechange = function(){
console.log('state');
};
},
contentType: 'application/json',
dataType: 'json',
type:"POST"});
}
})();
var rpc = function(method, success_callback) {
//I use functional javascript library
var fun = json_rpc.partial('rpc.php', method, _, function(data) {
if (data['error']) {
var e = 'Json-RPC (' + method + ') ' + data['error']['code'] + ": " +
data['error']['message'];
error_msg(e);
} else {
info_msg("rpc sucess for method '" + method + "'");
success_callback(data['result']);
}
});
return function() {
fun(Array.slice(arguments));
};
};
and when I create function with rpc
var update_news = rpc('get_news', function(data) {
if (data) {
//update news
}
});
and call it
$(document).ready(function() {
...
update_news();
...
});
In Firefox everythig is fine, but in Opera and Chrome the function update_news is not executing, beforeSend is fired but onreadystatechange is not, but when I add
setTimeout(update_news, 0);
Then It's call normaly, also when I create synchronous call by putting async: false in $.ajax call or when I put timeout, timeout: 1. In click handlers it also run as expected.
$('#some_id').click(function() {
update_news();
});
Anybody know why this is happening.