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.
Related
I trying call webmethod in my web project. I didnt found a problem in my codes and I called webmethod thousands of times before but I never see mistake like this before. Never enter my methods codes and it return my html page codes to me. ( sorry my bad english :)).. Please someone help me about that.
My Web method codes :
[WebMethod]
public static string GirisKontrol(string UserName, string Pass)
{
try
{
string strSonuc = "";
var context = new DBEntities();
var Kisi = context.users.Where(t => t.eposta== UserName && t.sifre == Pass).FirstOrDefault();
if (Kisi != null && Kisi.uye_onay==1)
{
HttpContext.Current.Session["UyeID"] = Kisi.ID;
HttpContext.Current.Session["Gorev"] = Kisi.gorev;
return Kisi.adsoyad;
}
else
return "0";
}
catch (Exception ex)
{
return "";
}
}
My javascript codes:
function GirisKontrol() {
PageMethods.GirisKontrol("asd", "sad", function(a) {
alert(a);
});
}
or I tried this but I got same result:
function test() {
$.ajax({
type: "POST",
url: "indexDeneme.aspx/GirisKontrol",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg);
}
});
}
This is result and it never go in c# codes:
enter image description here
Try this:
[WebMethod(EnableSession=true)]
Otherwise your method won't have access to the current SessionState, and the part where you try to save data to Session won't work.
The first example where you call PageMethods.GirisKontrol is unclear - your JavaScript isn't going to know about the server-side methods.
The second example using Ajax looks closer, but you're not passing any data.
data: "{}",
perhaps you mean this:
data: "{'UserName': 'asd', 'Pass': 'sad'}",
I am really new to CefSharps Chromium browser and have difficulty figuring out how to get the result of a jquery ajax request.
My first attempt was to pass my AJAX requesto to EvaluateScriptAsync. In fact the script works. It does exactly what I want, but I do not get any results/status codes, because my Cef-Task does not wait until AJAX has completed its work.
Here an example (just a sample code):
var tasks = pdBrowser.EvaluateScriptAsync(#"
(function(){
$.ajax({
type: ""POST"",
dataType: ""json"",
cache: false,
url: ""_resources/php/ajaxRequests.php"",
async: false,
data: {
action: ""insertCrossPlatform"",
type: """",
values: JSON.stringify(""foo bar"")
},
success: function(response) {
if (typeof response === 'string' && response.substring(0, 5) == ""ERROR"")
{
return response;
}
else
{
//pageReload();
return ""OK"";
}
},
error: function(xhr, textStatus, errorThrown) {
return errorThrown + ""\n"" + xhr.responseText;
},
complete: function() {
return ""COMPLETE"";
}
});
})();", null);
tasks.ContinueWith(t =>
{
if (!t.IsFaulted)
{
var response = t.Result;
if (response.Success)
{
if (response.Result != null)
{
MessageBox.Show(response.Result.ToString());
}
}
else
{
MessageBox.Show(response.Message, "Ein Fehler ist aufgetreten", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
}, TaskScheduler.Default);
Afterwards I have read that there is a SchemeHandler, but I do not properly understand how to implement it. Can anyone help me out?
Thanks in advance.
Firstly SchemeHandler is unlikely to be suitable in this scenario, you would typically implement a SchemeHandler when your providing the response.
Most people choose to bind an object, and call a method on their bound object when they wish to communicate with the parent application. See the FAQ for an example. https://github.com/cefsharp/CefSharp/wiki/Frequently-asked-questions#3-how-do-you-expose-a-net-class-to-javascript
With 49.0.0 you can implement ResponseFilter to gain access to the underlying response buffer, it's complex and not well documented, so if your not comfortable digging through reference C++ code then this option isn't for you. Here's a reference https://github.com/cefsharp/CefSharp/blob/cefsharp/49/CefSharp.Example/Filters/PassThruResponseFilter.cs#L17
Something that I did was create an element on the page through javascript with an ID that is the response of the ajax call. So for example, when you make an ajax call assign an ID to the ajax call.
When the ajax call returns, write an element on the page with the pre-assigned id and callback information. Then you can just use cefsharp to read the element content from the page and this will be your callback information.
var myDivElement =document.getElementById('textareaInfo');
if( myDivElement === null)
{
var input = document.createElement('textarea');
input.id = "textareaInfo";
input.value = "Test"
input.rows="4";
input.cols="50";
input.style="height:100%;width:900px;"
var dom = document.getElementsByClassName("page-body")[0];
dom.insertAdjacentElement('afterbegin', input)
}
Then later with ajax
var root = 'https://jsonplaceholder.typicode.com';
var _holder = callbackObj;
callbackObj.showMessage(""ajax"");
$.ajax({
url: root + '/posts/1',
contentType: 'application/json; charset=utf-8',
method: 'GET',
complete: function(data){
},
success: function(response) {
$(#'textareaInfo').value(response);
}
}).then(function(data) {
callbackObj.showMessage(data);
});
Then read the texarea from cefsharp in c#
chromeBrowser.GetMainFrame().EvaluateScriptAsync(function()...$(textareaInfo).value).Result
You can use PostMessage javascript method to notify .NET application:
CefSharp.PostMessage('Your data Here');
Here is .NET code example for headless browser:
var browser = new ChromiumWebBrowser("", null, RequestContext);
browser.JavascriptMessageReceived += (sender, e) =>
{
if ((string)e.Message.notificationid == "notification1")
{
// Your processing code goes here
}
};
browser.Load(destinationUrl);
browser.ExecuteScriptAsync("(function() { ... ; CefSharp.PostMessage({data: data, notificationid: 'notification1'});})()");
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 have a function that takes an XML file (obtained via AJAX) as input, parses it as XML and then execute some functions on it. A stripped down version can be found below.
AJAX
$.ajax({
type: "GET",
url: "./default.xml",
dataType: "xml",
success: function(data) {
parseMech(data);
}
});
parseMech function
function parseMech(xml) {
try {
var xmlObject = $(xml);
// See the output function below
$(".tree.base").html(treeBuilder(xmlObject.find("node").first()));
console.log("succes?");
} catch(e) {
$("#error-msg > .the-msg").text(" Invalid XML structure").parent().fadeIn(250);
console.log("Failed");
}
}
treeBuilder function
function treeBuilder(nodes) {
var newList = $("<ol>");
nodes.each(function (x, e) {
var newItem = $('<li> </li>');
for (var i = 0, l = e.attributes.length, a = null; i < l; i++) {
// Don't forget to add properties as data-attributes
a = e.attributes[i];
newItem.attr("data-" + a.nodeName, a.value);
if (a.nodeName == "cat" || a.nodeName == "word") {
newItem.html('' + a.value + '');
}
}
if ($(this).children('node').length) {
newItem.append(output($(this).children('node')));
}
newList.append(newItem);
});
return newList;
}
This works as it should when default.xml is a valid xml file. However, when it's not (for instance when I leave out a closing tag) the catch blok is not executed. In other words: when executing all functions with an invalid XML as source, neither console logs are executed, even though you would expect at least one (in try or in catch) to be logged.
Am I missing something here?
You need a fail handler in your ajax call.
According to the docs, a jquery ajax call with a dataType of xml returns a xml doc, so the data stream is being parsed in the course of the ajax call.
Alter the ajax call as follows (behaviour verified):
//...
error: function() {
console.log("ajax failed!");
},
//...
Note
Consider to change the way you specify your handlers,as error and success attributes are deprecated:
top.$.ajax({
type: "GET",
url: url,
crossDomain: true,
dataType: "xml",
})
.fail ( function() {
console.log("ajax failed!");
})
.done ( function(data) {
console.log("ajax ok!");
parseMech(data);
});
When I ran below code for bttn click event it doesn't return a data for success method.
But it goes for controller method and return false (boolean value) as a out put.I need to pick that boolean value from javascript code.
Why it doesn't work ?
Javascript code is as below:
$('#btnClockInTime').off('click').on('click', function () {
var isClockOutTimeCompleted = true;
$.ajax({
url: "/Employees/IsClockOutTimeCompleted",
type: "GET",
dataType: "json",
cache: false,
data: { employeeId: employeeId },
success: function (data) {
if (!data) {
isClockOutTimeCompleted = data;
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
return false;
});
Controller Action Method is as below:
[HttpGet]
public JsonResult IsClockOutTimeCompleted(Guid employeeId)
{
var clockingDate = Convert.ToDateTime(DateTime.Today);
var isClockOutTimeCompleted = Repository.IsClockOutTimeCompleted(employeeId, clockingDate);
return Json(isClockOutTimeCompleted, JsonRequestBehavior.AllowGet);
}
Repository code is as below:
public bool IsClockOutTimeCompleted(Guid employeeId, DateTime clockingDate)
{
var clockOutTime = (from c in Catalog.EmployeeClockInOutTimes
where (c.Employee.Id == employeeId && c.Created == clockingDate && c.ClockOut == null)
select c).FirstOrDefault();
return clockOutTime == null;
}
UPDATE :
Response is as below :
UPDATE 2 :
Screen 1 :
Screen 2 :
Screen 3 :
As shown above images my debug doesn't come into success method.
After 2nd screen (when debug at error) it goes to controller and brings data.
3rd screen shows a status after returning from controller.Any idea ?
I would have thought that if you're return value is just false as a string then that will become your data value and as a result:
if (!data) { // won't fire }
As Darin says, if you wrap up your response Json inside an object and then use that to assign to your isClockOutTimeCompleted variable.
I wouldn't have thought you'd want to perform a boolean evaluation of your return value if it's a true/false return type, wouldn't you just want to assign it to isClockOutTimeCompleted either way?
if ur posting data to a controller method always use
'type':'POST' in ur ajax call &
change the [HTTPget] attribute from ur controller method to [httpPost]
below is my sample code which works fine
$.ajax({
url: 'Home/temp',
type: 'POST',
dataType: "json",
data: {'name':'surya'},
success: function (data) {
console.log(data);
//here i'm getting the data which i have passed
},
error: function () {
console.log("inside error")
}
});
and my controller code
[HttpPost]
public JsonResult temp(string name) {
return Json(name);
}
i'm getting back the data which i have passed in to the controller method via my jquery ajax..
may be u ought to change ur 'IsClockOutTimeCompleted' method where u are performing linq queries.just validate ur linq queries once..and also employeeId which ur passing into the controller is of type integer then instead of GUID as a parameter why dont u change the parameter type as int and see..
Regards