Why doesnt this javascript code work? - javascript

I have a javascript function
function TxEncrypt(event)
{ //perform encryption of token data, then submit the form like normal
//obtain public key and initial JSEncrypt object
var txPubKey = txJ$(".zwitch_encryptionkey").val();
var txEncrypter = new JSEncrypt();
txEncrypter.setPublicKey(txPubKey);
//get Data and encrypt it
var txData = '{}';
var txCryptData = '';
if(txJ$(".zwitch_data").length > 1)
{ //if there are more than one element with this class, convert it to json string
txData = txJ$(".zwitch_data").serializeObject();
txCryptData = txEncrypter.encrypt(JSON.stringify(txData));
}
else
{ //else, just encrypt the value
txData = txJ$(".zwitch_data").val();
txCryptData = txEncrypter.encrypt(txData);
}
dataString = txCryptData; // array?
$.ajax({
type: "POST",
url: "tokenize.php",
data: {data : dataString},
cache: false,
success: function(data) {
returnedvalue = data;
console.log(data); //alert isn't for debugging
}
});
alert(dataString);
}
I could get the value of dataString.But the ajax parrt is not working.I have added the jquery library.But doesnt seem to work

What's the error you are getting?
I think this should be:
$.ajax({
type: "POST",
url: "tokenize.php", //removed the dot
.....

Related

MVC Controller is not receiving the values that comes from the Ajax /Javascript script

I debugged the JS and Ajax code with console.log. I can see that what I entered into the textbox, is displayed in the console. However, when these values are supposed to send to the controller, they are empty or null when I hover over the tbl_stuff List. Not sure where I am making a mistake.
Here is the JS:
$("body").on("click", "#btnSave", function () {
var table = $("table tbody");
var array= new Array();
table.find('tr').each(function (i) {
var $tds = $(this).find('td'),
Amount = $(this).find('.val').val();
valuestoupdate = { Amount: amount };
array.push(valuestoupdate);
});
$.ajax({
type: "POST",
url: "#Url.Action("StuffAction","Home")",
data: JSON.stringify(array),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
alert(r + " record(s) saved.");
}
});
Here is the controller action:
public JsonResult StuffAction(List<tbl_Stuff> stuffs)
{
int getID = (int)TempData["id"];
TempData.Keep();
var GetData = _context.tbl_Detail.Where(x => x.detId == getID).FirstOrDefault();
if (GetData != null)
{
foreach (tbl_Stuff moreThings in stuffs)
{
tbl_Stuff stuff = new tbl_Stuff();
stuff.Amount = moreThings.Amount;
_context.tbl_Stuff.Add(stuff);
}
}
int insertedRecords = _context.SaveChanges();
return Json(insertedRecords);
}
I get an error saying that moreThings.Amount is empty. But during debugging, the JS code gets the value entered into the textbox.
The .Net routing can't match the request
change the action signature to public JsonResult StuffAction(List< string > stuffs)
or in your ajax call change the array to an array of objects matching the properties of tbl_Stuff

error in serialization javascript from json to text

i have an error in serialisation i need someone to fix it and that 's code controller
public string Getrowselec(string id)
{
GestionprojetEntities ddb = new GestionprojetEntities();
Ressourcehumaine _ressource = new Ressourcehumaine();
_ressource = ddb.Ressourcehumaine.Find(Convert.ToInt32(id));
int id_ressource = int.Parse(id);
var query = (from u in ddb.Ressourcehumaine
where (u.Id == id_ressource)
select new
{
id = u.Id,
nom = u.Nom,
prixrevient = u.Prixrevient,
prixvente = u.Prixvente,
coutdirect = u.Coutdirect,
});
string javascriptJson = JsonConvert.SerializeObject(query);
return javascriptJson;
and this is my code in twig code javascript:
function Getrows(s, e) {
debugger;
var id = e.visibleIndex;
var key = s.GetRowKey(e.visibleIndex);
idProduit = key;
$.ajax({
url: "/Projet/Getrowsselec?id=" + key,
type: "POST",
dataType: "text",
success: function (response) {
debugger;
$("#nomclient_I").val(jsonObject[0]['nom']);
$("#codeclient_I").val(jsonObject[0]['id']);
}
})
}
can someone help me fix this issue the error in serialisation i think some error in serialisation
from json to text
i think that you need to add this to your response ajax try it and tell me if it work or not
success: function (response) {
debugger;
var jsonObject = JSON.parse(response);
$("#nomclient_I").val(jsonObject[0]['nom']);
$("#codeclient_I").val(jsonObject[0]['id']);
}

How to post a form with ajax and return data in array?

HI how to post a form and return data it will be a array as like this
{
"notes":'some notes',
"validUntil": '12/12/2015',
"status": 1,
"menuItemName": "HR Section",
"menuItemDesc": "gggg"
}
My code is this
$('#add-menu-list .btn[data-attr=submit-btn]').on('click', function(){
var formValidate = $('#add-menu-list').parsley().validate();
validateFront();
// console.log(formValidate);
var menuName = $('input[data-api-attr=menuItemName]').val();
var validUntil = $('input[data-api-attr=validUntil]').val();
var menuStatus = $('input[data-api-attr=status]').val();
var menuNote = $('textarea[data-api-attr=notes]').val();
var menuDesc = $('textarea[data-api-attr=menuItemDesc]').val();
var dataString = {
menuItemName: menuName,
validUntil : validUntil,
status : menuStatus,
notes : menuNote,
menuItemDesc : menuDesc
};
if(formValidate == true){
alert('success');
console.log(menuName + validUntil + menuStatus + menuNote + menuDesc);
var url = "xyz.html"; // the script where you handle the form input.
$.ajax({
type: "POST",
// url: url,
dataType: "json",
data: $(dataString).serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response
}
});
}else{
alert('Validation fail ');
}
});
Since "data" is a server response i guess that your server return a json object. In this case you have to somehow inform the jquery's ajax that you expect a json response from server or you have to translate the "data" to a json object by your self.
It is best to follow the first option so you don t have to deal with the translation your self you can easily do that by giving an extra parameter tou your ajax reuest : dataType: 'json', this will do the trick!
Now that you have a proper response object from your request you can either stringify it with var string_resp=JSON.stringify(data); and then alert it alert(string_resp) or you can access its elements like that : alert(data.status) which will alert your object's status field etc.
so your code will be :
$.ajax({
type: "POST",
url: url,
dataType: 'json',
data: $(menuName).serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // will alert an object
alert(data.status); // will alert object's status field in this case 1
alert(JSON.stringify(data)) // will alert the object as a string
}
});
you are sending only one value in serialize, serialize() should be on form element not on field element, like :
$('#add-menu-list .btn[data-attr=submit-btn]').on('click', function(){
...
$.ajax({
...
data:$("#form").serialize();
...
success: function(data)
{
alert(data.notes); // show response
....
}
var myObj = {
"notes":'some notes',
"validUntil": '12/12/2015',
"status": 1,
"menuItemName": "HR Section",
"menuItemDesc": "gggg"
};
myObj.toString = function()
{
var str = '';
for (var property in myObj)
{
if (myObj.hasOwnProperty(property) && (property != "toString") )
{
str += (property + ': ' + myObj[property] + "\n");
// do stuff
}
}
return str;
}
alert(myObj);

jQuery Ajax Race Condition best practice

In a button.click(function(){}); I have the following code:
var userId = $("#user-permission-edit").val();
var peId = $("#user-permission-entity-list").val();
var newParentPEId = $("#new-parent-pe").val();
var newPeName = $("#pe-name-add").val();
$.ajax({
type: "POST",
url: 'AddNewPE',
data: { 'targetUserId': userId, 'targetPEId': peId, 'newPeParentId': newParentPEId, 'newPeName': newPeName},
success: function (data) {
var dataObj = jQuery.parseJSON(data);
console.log(dataObj);
if (dataObj.status == "success") {
alert("Permissions have been updated.");
}
//update user PEs combo
}
});
However, I am concerned of a possible race condition of the variables not getting the values in time for the ajax call.
would something like this be safer?
var userId = $("#user-permission-edit").val();
var peId = $("#user-permission-entity-list").val();
var newParentPEId = $("#new-parent-pe").val();
var newPeName = $("#pe-name-add").val();
$.when(function() {
userId = $("#user-permission-edit").val();
peId = $("#user-permission-entity-list").val();
newParentPEId = $("#new-parent-pe").val();
newPeName = $("#pe-name-add").val();
}).done(function() {
$.ajax({
type: "POST",
url: 'AddNewPE',
data: { 'targetUserId': userId, 'targetPEId': peId, 'newPeParentId': newParentPEId, 'newPeName': newPeName},
success: function (data) {
var dataObj = jQuery.parseJSON(data);
console.log(dataObj);
if (dataObj.status == "success") {
alert("Permissions have been updated.");
}
//update user PEs combo
}
});
});
Is this even necessary?
The $('....').val() method is a synchronous call - your script execution won't continue past that line until you have received the value of that element.

Json stringify double quotes

I can't seem to get around this issue... Json I'm trying to pass to an MVC Controller keeps coming out like this
"\"{MaterialQuantity: { MaterialID :18, Quantity:1}}\""
This is the code that generates it:
function CreateJsonForQuantities() {
var inputs = $('input[name=MaterialQuantity]');
var total = inputs.length;
var data = "";
inputs.each(function (index) {
data = data + $(this).val();
if (index != total -1)
data = data + ',';
});
return data;
}
And this is the hidden which it reads data from (of course this is auto-generated as well)
<input name="MaterialQuantity" type="hidden" value="{MaterialQuantity: { MaterialID :12, Quantity:5}}" />
What am I doing wrong?
UPDATE
Ok so now I'm properly getting json object and my ajax requests looks like this. Problem now is that it does pass proper objects but all values are null in the controller action :(
var form_data = CreateJsonForNorm();
var quantity_data = CreateJsonForQuantities();
var data = { norm: form_data, mqvm: quantity_data };
$.ajax({
type: "POST",
url: form.attr("action"),
data: data,
success: function () {
location.href = "#Url.Action("Index")";
('#addDialog').dialog("close");
},
error: function () {
alert("Error");
}
});
Try using JSON.stringify(data) in your request

Categories