My code is this:
var username = "john";
var password = "doe";
var url = '//api.bos2.cf/?type=verify&username=' + username + '&password=' +
password + '&callback=?';
$.getJSON(url, function(data) {
success: readData(data)
});
function readData(data) {
alert(data);
}
Although this code alerts object Object instead of {'success' : false, 'msg' : 'Unknown API function'}
Any Ideas as to why this is happening??
Thanks,
CSF
You are trying to display the raw object. You need to turn it into a string first:
function readData(data) {
alert(JSON.stringify(data));
}
function readData(data) {
alert(data.success);
alert(data.msg);
}
just go through simple way.
Related
Ive included the very end of my script below, where I'm trying to put a JSON file into a website using Ajax callback function. When I inspect the page, I'm seeing that the JSON file is not well formed and I can't seem to find an answer. The webpage is also just showing that the JSON file is "undefined".
function debugCallback(response){
var mydata;
$("#mydiv").append('GeoJSON data: ' + JSON.stringify(mydata));
};
function debugAjax(){
var mydata;
$.ajax("data/MegaCities.GeoJSON", {
dataType: "json",
success: function(response){
//mydata = response;
debugCallback(mydata);
}
});
$("#mydiv").append('<br>GeoJSON data:<br>' + JSON.stringify(mydata));
};
//$("#mydiv").append('GeoJSON data: ' + JSON.stringify(mydata));
if(typeof mydata === 'undefined') {
console.log("undefined data")
} else {
console.log("not undefined")
}
$(document).ready(debugAjax());
Avoid defining several functions and try just using this:
$(document).ready(function(){
$.ajax("data/MegaCities.GeoJSON", {
dataType: "json",
success: function(response){
$("#mydiv").append('<br>GeoJSON data:<br>' + JSON.stringify(response));
}
});
});
Note that after we get response/data from ajax call, we proceed formatting as JSON.
You are using var mydata and it is not defined so it is showing correct message undefined when you are passing it as value.
You should probably modify your code like this.
$(document).ready(function(){
$.ajax({
url: "data/MegaCities.GeoJSON",
method: 'GET' ,
aysnc: false,
success: function(response){
$("#mydiv").append('GeoJSON data:' +response);
}
});
});
I have been stuck at this problem for almost two days now and I don't seem to find any solution. I have hosted a WCF service on my machine that contains a method SendCredentials which accepts two string parameters.
Now I am supposed to send a public key to my service through which it will do encryption(Asymetric cryptography) and send some information back to the client.
I am not able to pass that public key to the service method from the client as it is in XML format.Here is my client side code:
$(document).ready(function () {
$("#btnSend").click(function () {
debugger;
jQuery.support.cors = true;
var doOaepPadding = true;
var rsa = new System.Security.Cryptography.RSACryptoServiceProvider();
_privateKey = rsa.ToXmlString(true);
_publicKey = rsa.ToXmlString(false);
var data = $("#txtName").val();
var name = "testvalue";
var _privateKey = rsa.ToXmlString(true);
**var _publicKey = rsa.ToXmlString(false);**
//<![CDATA[ and ]]>;
$.ajax({
type: "POST",
url: 'http://localhost:51348/TestService.svc/SendCredentials',
crossDomain: true,
data:JSON.stringify({ mac: "bac", pubKey: _publicKey }),
contentType: "application/json",
dataType: "json",
success: function (result) {
var ans = JSON.stringify(result);
alert(ans);
// result = new XMLSerializer().serializeToString(result.documentElement);
},
error: function (xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
}
});
return false;
});
});
</script>
_publicKey is the variable I want to pass but throws above said error. Any suggestions How do i pass this XML variable would be really appreciated.
I would suggest you to convert _publicKey to base64 string
convert your _publicKey to string then byte Array and use
Convert.ToBase64String(byte[] inArray)
and on the service side do the reverse
System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(endodedString), true));
I've been stuck at this error for a few days and still couldn't figure out what is wrong. Would be great if someone could just point me to the right direction of solving this issue.
Update:
I realise that error is gone when I commented "addMessages(xml)" in the updateMsg() function. How do I make it work then?
Error:
http://i.imgur.com/91HGTpl.png
Code:
$(document).ready(function () {
var msg = $("#msg");
var log = $("#log");
var timestamp = 0;
$("#name").focus();
$("#login").click(function() {
var name = $("#name").val();
if (!name) {
alert("Please enter a name!");
return false;
}
var username = new RegExp('^[0-9a-zA-Z]+$');
if (!username.test(name)){
alert("Invalid user name! \n Please do not use the following characters \n `~!##$^&*()=|{}':;',\\[\\].<>/?~##");
return false;
}
$.ajax({
url: 'login.php',
type: 'POST',
dataType: 'json',
data: {name: name},
success: function() {
$(".login").hide();
}
})
return false;
});
$("#form").submit(function() {
if (!msg.val()) {
return false;
}
$.ajax({
url: 'add_message.php',
type: 'POST',
dataType: 'json',
data: {message: msg.val()},
})
msg.val("");
return false
});
window.setInterval(function () {
updateMsg();
}, 300);
function updateMsg() {
$.post('server.php', {datasize: '1024'}, function(xml) {
addMessages(xml);
});
}
function addMessages(xml) {
var json = eval('('+xml+')');
$.each(json, function(i, v) {
tt = parseInt(v.time);
if (tt > timestamp) {
console.log(v.message);
appendLog($("<div/>").text('[' + v.username + ']' + v.message));
timestamp = tt
}
});
}
function appendLog(msg) {
var d = log[0]
var doScroll = d.scrollTop == d.scrollHeight - d.clientHeight;
msg.appendTo(log)
if (doScroll) {
d.scrollTop = d.scrollHeight - d.clientHeight;
}
}
});
It might help to read up on eval a bit. It looks like it doesn't do what you think it does.
eval() is a dangerous function, which executes the code it's passed with the privileges of the caller.
Also
There are safer (and faster!) alternatives to eval() for common use-cases.
It looks like what you're trying to do is get data from the server in the form of JSON. You'll need to make sure that your server returns something that is valid JSON, which you can verify here. Most server-side programming languages have a library that will turn an object into JSON to make that a piece of cake. Here's an example for php.
On the client-side, you'll need to change var json = eval('(' + xml + ')'); to var json = JSON.parse(xml); This will give you the javascript version of your php/perl/python/etc object. If it's an array, you can then iterate through it with a for loop, Array.prototype.forEach, or a variety of functions from different libraries, such as $.each or _.each.
SyntaxError: expected expression, got ')' usually cause by something like
exeFunction(a,b,)
See if your form submit function ajax causing such error
$("#form").submit(function() {
if (!msg.val()) {
return false;
}
$.ajax({
url: 'add_message.php',
type: 'POST',
dataType: 'json',
data: {message: msg.val()}, <-------
})
msg.val("");
return false
});
If you are triggering the java script on click or trigger any click. sometimes missing of 0 gives the above error.
delete
would JSON.stringify({datasize: '1024'}) do the trick? just a guess
I am receiving a JSON string from an ajax call and would like to convert a value to a predefined variable:
var predefined = "hello world";
var foo = {"msg":"predefined"}; // JSON string
I want to echo out the standard string accessing it with
alert(foo.msg)
EDIT: to make the answer more clear here is my call:
var success_msg = "Your email is send successfully!";
$.ajax({
url: "ajax-share-email.php",
type: "POST",
dataType: "json",
data: {},
success: function(data) {
if (data.status == "success") {
msg.text(data.msg).addClass("email-msg-success");
} else {
msg.text(data.msg).addClass("email-msg-error");
}
}
})
ajax-share-email.php responds:
{"status":"success", "msg":"success_msg"}
var strings = {"predefined":"hello world"};
alert(strings[foo.msg]);
or e.g.
var messages = {};
messages.success_msg = "Your email is send successfully!";
// ...
msg.text(messages[data.msg]).addClass("email-msg-success");
How about this -- just use the message inline on success and don't even bother to make it part of the JSON. On an error, do include the entire message and use it directly. Also, I'd have your server return something like:
{ "status": true }
or
{ "status": false, "msg": "The mail server is down." }
Then you can just evaluate it as a boolean without comparing it to a string value.
$.ajax({
url: "ajax-share-email.php",
type: "POST",
dataType: "json",
data: {},
success: function(data) {
if (data.status) {
msg.text('Your email has been sent successfully!').addClass("email-msg-success");
} else {
msg.text(data.msg).addClass("email-msg-error");
}
}
});
If, and only if, you start reusing your messages for multiple functions, then refactor to a message dictionary and reference it from there. Note your messages object would likely need to be a global variable, or at least in the outer scope of all the functions that use it.
var messages = {};
messages.mail_success = 'Your email has been sent successfully!';
messages.post_success = 'Your data has been updated!';
$.ajax({
url: "ajax-share-email.php",
type: "POST",
dataType: "json",
data: {},
success: function(data) {
if (data.status) {
msg.text(messages.mail_success).addClass("email-msg-success");
} else {
msg.text(data.msg).addClass("email-msg-error");
}
}
});
var predefined = "hello world";
var foo = {"msg":predefined}; // JSON string
alert(foo.msg)
?
IFF I understand what you are asking, I think I have all of the pieces here.
You have a variable predefined and you want to be able to return that in your json and have the resulting parsed object contain the value in predefined
JSON.parse will not work for you (at least not in Chrome), but eval will.
var predefined = "Hi! I'm predefined";
// ...
var json = '{"foo": predefined}'; // notice no quotes
var response = eval("(" + json + ")");
alert(response.foo);
var out = eval(foo.msg); // out is now "hello world"
Note: do not use eval() if you are not sure what the content of foo.msg is.
or
var out = foo.msg=="predefined" ? predefined : foo.msg;
When this function is hit , it does not call my function in code behind? Why could it be doing this? How can I fix this error.
$(document).ready(function() {
$('[id$=btn_Update]').click(function() {
var reten = $('[id$=txt_Reten]').val();
var i=0;
var selectValues = "";
var ProdID = new Array();
$("#lst_ProdId option").each(function() {
selectValues = selectValues + $(this).text() + ",";
ProdID[i] = $(this).text();
i++;
});
for(var j=0; j < ProdID.length;j++)
{
// alert(ProdID[j]);
}
var params = "{'ProdID':'" + ProdID + "','RetenP':'" + reten + "'}";
$.ajax({
type: "POST",
url: "/ProductPricing/Products/RetenPeriod.aspx/UpdateRetenPeriod",
data: params,
contentType: "application/json; charset=utf-8",
datatype: "json",
success: function(result) {
alert("sucess");
},
error:function(e) {
alert(e.statusText);
// if(errorThrown != null)
// alert(textStatus+ ":"+errorThrown);
// else
// alert("fail");
}
});
return false;
});
return false;
});
This is my webmethod in code behind:
[WebMethod]
public static bool UpdateRetenPeriod(string[] ProdID,string RetenP)
{
for (int i = 0; i < ProdID.Length; i++)
{
update(ProdID[i],RetenP);
}
return true;
}
You're passing your parameters as a string instead of as an object literal:
var params = "{'ProdID':'" + ProdID + "','RetenP':'" + reten + "'}";
should (almost certainly) be:
var params = {'ProdID': ProdID,'RetenP': reten};
Also, how do you know that the ajax request is not making it to the server? Have you tried tracing the HTTP requests with something like TamperData (for Firefox) or Firebug (also Firefox)?
Does it call the error method?
You need to return JSON. Not a boolean. Perhaps something like {success: true}.
Then:
success: function(data) {
if(data.success) {
...
}
else {
...
}
}
jQuery expects JSON and will throw an error if it doesn't receive well-formed JSON. Also, what is the exact response you're getting back? You can use something like Firebug to figure this out.
One more thing. Can you verify that you can successfully hit that URL? Are you able to successfully point your browser to http://your.url.here/ProductPricing/Products/RetenPeriod.aspx/UpdateRetenPeriod?
Also look at Pointy's solution. Your request is unlikely to succeed since you aren't passing in an actual object literal.
Do you have a ScriptManager defined in the markup with EnablePageMethods set to true?
Also, I believe your params line should be:
var params = "{ProdID:'" + ProdID + "', RetenP:'" + reten + "'}";
I have several functions in my own apps that do it this way. You want the value of params to look like this: "{ProdID:'1,2', RetenP:'undefined'}"
Can you place a breakpoint at alert(e.statusText); to see what the error message is?
Have u got error message.. please, try to get the error message
I think, u can use this by replacing error block
error:
function(XMLHttpRequest, textStatus, errorThrown){
alert( "Error Occured!" + errorThrown.toString());
}
I think, problems occurred in code behind method.. if in [web method] has any problem, then ajax doesn't call the method..