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
Related
I have a Ajax call that is working, but the success function isn't. I have a a few dates that I am inputting, after hitting submit, there should be a little alert popup saying "Data saved to the DB". The data is getting saved to the DB, however I am not getting the popup alert window.
$("#btnSubmit").bind("click", function () {
createUpdateArrays();
var url = "/Sample/Selection";
$.ajax({
type: "GET",
url: url,
data: { ids: ids, dates: dates },
success: function (success) {
if (success === true) {
alert("Success");
}
else {
alert("error");
}
}
});
ids = "";
dates = "";
});
function createUpdateArrays() {
var i = 0;
$('input.remedy-id:checkbox').each(function () {
if ($(this).is(':checked')) {
var rid = $(this).attr("id");
$('.planned-date').each(function () {
var did = $(this).attr("id");
if (did === rid) {
var date = $(this).val();
ids += rid + ",";
dates += date + ",";
}
});
};
});
};
I can't seem to understand the reason behind this..
EDIT: Before doing ANYTHING else, make sure that your server is actually returning a response to begin with.
Your success function is expecting a boolean to be returned by the server, but this is probably not what is happening. If you're returning a simple string "success" from the server, then the comparison should be if (success === "success"). This is entirely dependent on what your server is returning as a response.
Perhaps your server is returning a status code of 2xx. In either case, you can use the jQuery status code callbacks:
$.ajax({
type: "GET",
url: url,
data: { ids: ids, dates: dates },
statusCode: {
200: function(){alert("Success!")},
201: function(){alert("Success!")}
}
});
And if you don't want to do that and just want to use the success callback, try something like this:
success: function (success) {
if (success || (success.length && success.length == 0)) { // this will almost definitely evaluate to true
console.log(success) // Do this to see what is actually being returned. I guarantee it isn't a boolean value.
alert("Success");
}
else {
alert("error");
}
}
I am not able to figure out what is wrong with my code.I am getting data from post as an array and I am then displaying that data in box.
function worker() {
var a = $("#BeeperBox");
var delay =2000;
$.ajax({
url: '/index.php/admin/getLatest',
success: function(data) {
$.each(data.upda,function(i, v){
var out = v.name + v.mob ;
$('span.blueName').html(out);
$("#BeeperBox").show();
timerId = setTimeout(function () {
a.hide();
}, delay);
});
},
complete: function() {
// Schedule the next request when the current one's complete
setTimeout(worker, 50000);
}
});
}
When i run it firebug shows error: TypeError: e is undefined.
since your sending the response as JSON.. its better to specify your dataType as JSON (though If none is specified, jQuery will try to infer it based on the MIME type of the response ) so that you don't have to parse it manaully..i think the problem here is you havn't parsed the json that you got as response
try this
$.ajax({
url: '/index.php/admin/getLatest',
dataType: 'json',
success: function(data) {
$.each(data.upda,function(i, v){
var out = v.name + v.mob ;
......
},
Check if data.upda is undefined, I think the problem is that that variable doesn't exist and you're trying to iterate over a undefined element.
I'm a newbie in javascript, and I don't really understand the error I'm having.
I'm working on a MVC3 website, which has to monitor an embedded system.
Here is the javascript code that is running :
function GetTemp() {
var test = "gTe";
$.ajax({
url: '#Url.Action("../Carte/Get")',
type: 'GET',
data: {test: test},
success: function (result) {
if (result.charAt(4) == 'a') {
$("#LumAct").text(result.substr(0, 4) + " %");
alert('a');
}
...
And here is the c# action that returns a string
public String Get(String test)
{
flag = TCPClient.SendData(test);
if (flag == "1")
{
try
{
value = TCPClient.ReceiveData();
}
catch
{
value = "Erreur";
}
}
else value = "Erreur";
return value;
}
The error I have is in firebug, which tells me :
TypeError: result.charAt is not a function
[Stopper sur une erreur]
if (result.charAt(4) == 'a') {
So, what haven't I understood? According to me, I'm using an ajx function that sends a httpGet to the controller, which responds with a string. In javascript, I can work on a string like I did.
To use the string object, I haven't added any library. Should I have done that? I haven't found any information telling that.
Can you try this:
if (String(result).charAt(4) == 'a')
Also, as mentioned by #Musa, you should add a dataType attribute to the AJAX call:
$.ajax({
url: '#Url.Action("../Carte/Get")',
type: 'GET',
dataType: 'text',
data: {test: test},
success: function (result) {
if (result.charAt(4) == 'a') {
$("#LumAct").text(result.substr(0, 4) + " %");
alert('a');
}
If you check the jQuery.ajax api page you'll see that the first argument is an Object formatted to the dataType parameter. Honestly I'd console.log the result and see what it looks like. If you can't charAt() then the result is probably is not a string.
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..