based on that a link!, I'm trying adapt this code to my project. however when I click save this error appears:
SyntaxError: missing ) in parenthetical Warning: main(): It is not
safe to rely on the system's timezone se
My js
function saveItem(index) {
var row = $('#dgusu').datagrid('getRows')[index];
var url = row.isNewRecord ? 'app/cadusuarios_acao.php?opcao=C' :
'app/cadusuarios_acao.php?opcao=A?id=' + row.id;
$('#dgusu').datagrid('getRowDetail', index).find('form').form('submit', {
url: url,
onSubmit: function () {
return $(this).form('validate');
},
success: function (data) {
data = eval('(' + data + ')');
data.isNewRecord = false;
$('#dgusu').datagrid('collapseRow', index);
$('#dgusu').datagrid('updateRow', {
index: index,
row: data
});
}
});
}
Someone can tell me where I am going wrong?
Thanks
Related
Right now I'm trying to do a simple delete / update / get through the User Id but I'm not getting the data correctly and I don't know if it's because of the ajax function, if it's for my web Api or if it's because of gRPC ,
My question is similar to this link I already asked, so I'll maybe show the simplest part which is the delete and also show the ajax call
Old Link: gRPC and/or WebAPI: How to do a simple Update but using an Id
gRPC Delete:
public override async Task<Empty> Delete(UserFilter requestData,
ServerCallContext context)
{
var data = await _context.Users_5.FindAsync(requestData.UserID);
if(date == null)
{
throw new Exception("User Not Found");
}
_context.Users_5.Remove(data);
await _context.SaveChangesAsync();
return await Task.FromResult(new Empty());
}
WebApi:
[HttpDelete("{Id_user}")]
public async Task<ActionResult<Empty>> DeleteUser([FromBody] UserFilter Id_user)
{
_logger.Log(LogLevel.Information, "Request Received for AuthController::Delete");
/**
if(Id_user == null)
{
return BadRequest("Id not Found idk why");
}
if(Id_user.ToString() != Request.Cookies["LoginUserId"])
{
return BadRequest("Id's is Different");
}
*/
var results = await _userClient.DeleteAsync(Id_user);
_logger.Log(LogLevel.Information, "Sending Response from AuthController::Delete");
return Ok(results);
}
The Javascript Code:
var $users_A = $('#users_A');
var $Id_user = $('#Id_user')
$users_A.delegate('.remove', 'click', function () {
var $li = $(this).closest('li');
var self = this;
debugger;
$.ajax({
url: uri_7 + $Id_user,
type: 'DELETE',
success: function() {
$li.fadeOut(300, function () {
$(this).remove();
});
},
error: function (xhr, textStatus, errorThrown) {
console.log('XHR:' + JSON.stringify(xhr) + '\nTextStatus:' + textStatus + '\nErrorThrown:' + errorThrown);
}
});
});
The stupid error:
XHR:{"readyState":4,"responseText":"{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title" :"One or more validation errors occurred.","status":400,"traceId":"00-82ac37132e06d497f2f7ec082e382273-ba6109fbfa7fd9f8-00","errors":{"$\ ":["The input does not contain any JSON tokens. Expected the input to start with a valid JSON token, when isFinalBlock is true. Path: $ | LineNumber: 0 | BytePositionInLine: 0."],"Id_user":["The Id_user field is required."]}}","responseJSON":{"type":"https://tools.ietf.org/ html/rfc7231#section-6.5.1","title":"One or more validation errors occurred.","status":400,"traceId":"00-82ac37132e06d497f2f7ec082e382273-ba6109fbfa7fd9f8-00","errors":{ "$":["The input does not contain any JSON tokens. Expected the input to start with a valid JSON token, when isFinalBlock is true. Path: $ | LineNumber: 0 | BytePositionInLine: 0."],"Id_user": ["The Id_user field is required."]}},"status":400,"statusText":"error"}
--Conclusion--
Idk what's happening, I have the post and the getAllUsers correct but getting a specific user it gives me a lot of pain, so how to correct this code??
Any Answer/Help is always welcome
While following a tutorial to use the openweathermap api using jquery and an ajax call, I'm unable to get results and see the following error in chrome console:
Uncaught SyntaxError: Unexpected token '<'
I'm not sure how to fix this, here is my JS code which i'm adding into a JS file to use in index.html:
const apiKey = '9f15d4ade842c933c2675067904450f0';
$(document).ready(function () {
let searchKey = '';
$('#submit').click(function () {
let location = $('#location').val();
if (!isNaN(location)) {
searchKey = 'zip';
} else {
searchKey = 'q';
}
if (location) {
console.log('here');
$.ajax({
name:
'https://api.openweathermap.org/data/2.5/weather?' +
searchKey +
'=' +
location +
'&appid=' +
apiKey,
dataType: 'jsonp',
type: 'GET',
success: function (data) {
const result = outputData(data);
$('#outputData').html(result);
$('#outputData').val('');
},
});
function outputData(data) {
return (
'<div><h2>Weather in ' + data.name + '</h2>' + '</div>'
);
}
}
});
});
$.ajax({name... should be $.ajax({url:..
(answer given in comments)
I'm using p5.js to do some drawing using data from json fed by my Django backend. I have a my draw function defined at the base level of my html doc in the script element like so:
function draw(json) {
if (json["leaf_text"]) {
stroke(100)
ellipse(json["leaf_center_x"], json["leaf_center_y"], json["leaf_height"], json["leaf_width"]).rotate(json["leaf_rotate"]);
}
if (json["twig_text"]) {
stroke(100);
console.log("drawing twig....");
line(json["twig_base_x"], json["twig_base_y"], json["twig_tip_x"], json["twig_tip_y"]);
}
if (json["branch_text"]) {
stroke(150);
line(json["branch_base_x"], json["branch_base_y"], json["branch_tip_x"], json["branch_tip_y"]);
console.log("x1 " + json["branch_base_x"]);
console.log("x2 " + json["branch_base_y"]);
console.log("y1 " + json["branch_tip_x"]);
console.log("y2 " + json["branch_tip_y"]);
}
if (json["trunk_text"]) {
stroke(255);
line(json["trunk_base_x"], json["trunk_base_y"], json["trunk_tip_x"], json["trunk_tip_y"]);
}
}
This function is called upon receipt of a successful ajax response as follows. My problem is, I get a error in the js console because of the draw function.
TypeError: json is undefined
My understanding is that (please correct me where I am wrong) the 'draw' function is agnostic concerning whether or not 'json' exists or not and will wait and see what sort of object it is passed before it begins complaining that the parameter is not defined. Is this not the idea of a function in javascript?? I must be missing something. If this is the case, why would it complain that json is not defined?
if (json["leaf_text"]) {
$("#grow").click(
function(e) {
console.log("attempting ajax...");
e.preventDefault();
var csrftoken = getCookie('csrftoken');
var open_parens = ($("#txt").val()).indexOf("(");
var close_parens = ($("#txt").val()).indexOf(")");
var child = $("#txt").val().slice(0, open_parens);
var parent = $("#txt").val().slice(open_parens + 1, close_parens);
$.ajax({
url: window.location.href,
type: "POST",
data: {
csrfmiddlewaretoken: csrftoken,
child: child,
parent: parent,
mode: "grow"
},
success: function(json) {
setup();
draw(json);
...
}
},
error: function(xhr, errmsg, err) {
console.log(xhr.status + ": " + xhr.responseText);
}
});
});
If you use import called json, you should use different name as parameter for draw function (for example: draw(json_bar) or, in import, re-name json (for example: import json as json_foo).
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
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..