How to make the right yii2 validation manually? - javascript

It should be on the page where a list of users , open the modal window for editing . This page should not be updated . Clicking on the link opens a modal window ActiveForm after the data filled by AJAX. How can I transfer that is now id like to pass validation . With help yii.ActiveForms.js or something else?
public function actionEditUser($id) {
if (!Yii::$app->user->isGuest && Yii::$app->user->identity->role == 2) {
$model = new EditUserForm();
$model->id = (int) $id;
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
if ($model->load(Yii::$app->request->post()) && $model->updateUser()) {
return Yii::$app->response->redirect(Url::to(Yii::$app->request->referrer, true));
} else {
$user = $this->findModel($id);
$model->login = $user->login;
$model->email = $user->email;
$model->fullName = $user->full_name;
return $this->renderAjax('editModalUserForm', [
'model' => $model,
]);
}
}
return Yii::$app->response->redirect(Url::to('site/sign-in', true));
}
InitEditUser: function (event) {
var target = $(event.target);
var id = target.attr('id');
var url = 'http://' + window.location.hostname + '/users/' + id;
var urlGet = window.location.href;
$.ajax({
type: 'GET',
url: urlGet,
data: 'id=' + id,
success: function (data, textStatus, jqXHR) {
console.log('ok');
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
$('#editUser').modal('show');
$.ajax({
type: 'GET',
url: url,
success: function (data, textStatus, jqXHR) {
console.log(data);
$('#editUserInput').val(data.login);
$('#editUserFullNameInput').val(data.full_name);
$('#editUserEmailInput').val(data.email);
$('#editUserForm').on('beforeSubmit', function () {
console.log("a");
return false;
});
$('#editUserForm').on('afterValidate', function () {
console.log("b");
});
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
},
};
InitEditUser: function (event) {
var target = $(event.target);
var id = target.attr('id');
var url = 'http://' + window.location.hostname + '/users/' + id;
var urlGet = window.location.href;
$.ajax({
type: 'GET',
url: urlGet,
data: 'id=' + id,
success: function (data, textStatus, jqXHR) {
console.log('ok');
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
$('#editUser').modal('show');
$.ajax({
type: 'GET',
url: url,
success: function (data, textStatus, jqXHR) {
console.log(data);
$('#editUserInput').val(data.login);
$('#editUserFullNameInput').val(data.full_name);
$('#editUserEmailInput').val(data.email);
$('#editUserForm').on('beforeSubmit', function () {
console.log("a");
return false;
});
$('#editUserForm').on('afterValidate', function () {
console.log("b");
});
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
},
};

Related

it showing "undefined" in tree view using ASP.NET MVC with javascript

While fetching data from the oracle database it showing "undefined" in Tree View structure using ASP.NET MVC and Gijgo tree view JQuery plug-in, The Tree View control can display a hierarchical (or nested, or recursive) collection of data in a tree of expandable nodes.. How to solve this?.Please, anyone helps me.
I am trying this link
https://www.codeproject.com/Articles/1185174/How-to-create-Dynamic-draggable-and-droppable-Tree
#section Scripts {
#Scripts.Render("~/bundles/Scripts/jqueryval") <script src="~/Scripts/jquery.validate.min.js"></script> <script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<script src="#Url.Content("~/Scripts/conditional-validation.js")" type="text/javascript"></script>
<script src="~/Scripts/Gijgo/gijgo.js"></script>
<link href="http://code.gijgo.com/1.3.0/css/gijgo.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
//'Hierarchy/GetHierarchy'
$(document).ready(function () {
var Usertree = "";
var tree = "";
$.ajax({
type: 'get',
dataType: 'json',
cache: false,
url: '/Hierarchy/GetHierarchy',
success: function (records, textStatus, jqXHR) {
tree = $('#tree').tree({
primaryKey: 'Id',
dataSource: records,
dragAndDrop: true,
checkboxes: true,
iconsLibrary: 'glyphicons',
//uiLibrary: 'bootstrap'
});
Usertree = $('#Usertree').tree({
primaryKey: 'ID',
dataSource: records,
dragAndDrop: false,
checkboxes: true,
iconsLibrary: 'glyphicons',
//uiLibrary: 'bootstrap'
});
tree.on('nodeDrop', function (e, ID, PID) {
currentNode = ID ? tree.getDataById(Id) : {};
console.log("current Node = " + currentNode);
parentNode = PID ? tree.getDataById(PID) : {};
console.log("parent Node = " + parentNode);
if (currentNode.PID === null && parentNode.PID === null) {
alert("Parent node is not droppable..!!");
return false;
}
// console.log(parent.HierarchyLevel);
var params = { id: ID, parentId: PID };
$.ajax({
type: "POST",
url: "/Hierarchy/ChangeNodePosition",
data: params,
dataType: "json",
success: function (data) {
$.ajax({
type: "Get",
url: "/Hierarchy/GetHierarchy",
dataType: "json",
success: function (records) {
Usertree.destroy();
Usertree = $('#Usertree').tree({
primaryKey: 'ID',
dataSource: records,
dragAndDrop: false,
checkboxes: true,
iconsLibrary: 'glyphicons',
//uiLibrary: 'bootstrap'
});
}
});
}
});
});
$('#btnGetValue').click(function (e) {
var result = Usertree.getCheckedNodes();
if (result == "") { alert("Please Select Node..!!") }
else {
alert("Selected Node id is= " + result.join());
}
});
//delete node
$('#btnDeleteNode').click(function (e) {
e.preventDefault();
var result = tree.getCheckedNodes();
if (result != "") {
$.ajax({
type: "POST",
url: "/Hierarchy/DeleteNode",
data: { values: result.toString() },
dataType: "json",
success: function (data) {
alert("Deleted successfully ");
window.location.reload();
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error - ' + errorThrown);
},
});
}
else {
alert("Please select Node to delete..!!");
}
});
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error - ' + errorThrown);
}
});
// show model popup to add new node in Tree
$('#btnpopoverAddNode').click(function (e) {
e.preventDefault();
$("#modalAddNode").modal("show");
});
//Save data from PopUp
$(document).on("click", "#savenode", function (event) {
event.preventDefault();
$.validator.unobtrusive.parse($('#formaddNode'));
$('#formaddNode').validate();
if ($('#formaddNode').valid()) {
var formdata = $('#formaddNode').serialize();
// alert(formdata);
$.ajax({
type: "POST",
url: "/Hierarchy/AddNewNode",
dataType: "json",
data: formdata,
success: function (response) {
// $("#modalAddNode").modal("hide");
window.location.reload();
},
error: function (response) {
alert('Exception found');
// $("#modalAddNode").modal("hide");
window.location.reload();
},
complete: function () {
// $('.ajax-loader').css("visibility", "hidden");
}
});
}
});
//Close PopUp
$(document).on("click", "#closePopup", function (e) {
e.preventDefault();
$("#modalAddNode").modal("hide");
});
$('.rbtnnodetype').click(function (e) {
if ($(this).val() == "Pn") {
$('.petenddiv').attr("class", "petenddiv hidden");
$("#ParentName").val("");
}
else {
$('.petenddiv').attr("class", "petenddiv");
}
});
});
</script>
}
Just make sure you name the property “text”, including lowercases, as the library binds this field to the label. Not having a property with this name renders it undefined.

Data from response is symbols unable to set to iframe

I want to check if a response was successful from an Api and then put it in the iframe.
If I call it twice like this... it works.
function getPDF(fileDirectorGuid) {
if ($('#viewDownloadWindow').is(":visible")) {
$.ajax({
url: $('#fdApiURL').val() + 'getDocAsPDF' + FIRST_ARGS + '&guid=' + fileDirectorGuid + '&fallbackToNative=true',
type: 'GET',
success: function (data) {
if (data == null) {
alert("failed");
}
else {
$('#pdfFrame').attr('src', $('#fdApiURL').val() + 'getDocAsPDF' + FIRST_ARGS + '&guid=' + fileDirectorGuid + '&fallbackToNative=true');
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Failed");
}
});
}
however I don't want to call this twice and this doesn't work out like I thought
function getPDF(fileDirectorGuid) {
if ($('#viewDownloadWindow').is(":visible")) {
$.ajax({
url: $('#fdApiURL').val() + 'getDocAsPDF' + FIRST_ARGS + '&guid=' + fileDirectorGuid + '&fallbackToNative=true',
type: 'GET',
success: function (data) {
if (data == null) {
alert("failed");
}
else {
$('#pdfFrame').attr('src', data);
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Failed");
}
});
}
When viewing this in the debugger data looks like this
"%PDF-1.6
1 0 obj
<<
/Length 2 0 R
/Filter /FlateDecode
>>
stream
x��[�%Iv�wO�����H�|��8&`%ِږ8�.���D�J�h ��^of�Z�;wsj�g�<�4��O�X�Nq���c��������l����������7��?����>���S������4��>�y||��z�<J����Gݏ�c�?C����6�����?
so on and so forth.
The src attribute of an iframe is a url, you're setting the actual pdf data. You can use a blob url to achieve your goal
$.ajax({
url: $('#fdApiURL').val() + 'getDocAsPDF' + FIRST_ARGS + '&guid=' + fileDirectorGuid + '&fallbackToNative=true',
type: 'GET',
xhr:function(){
var xhr = new XMLHttpRequest();
xhr.responseType= 'blob'
return xhr;
},
success: function (data) {
if (data == null) {
alert("failed");
}
else {
var url = window.URL.createObjectURL(data);
$('#pdfFrame').attr('src', url);
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Failed");
}
});

Cannot insert data from frontend Javascript to database using Mongoose

I am working on an Node.js-Express.js-Mongoose application.
I want to accept user details (Name and Age) in an html form (EJS file), save into databse (using mongoose) display the added user details on the webpage .
I am using AJAX for the same. The files used are :
userview.ejs (contains the Form) --> frontend.js (uses jquery) --> users.js (router file- calls the add() function defined in the userController) --> userController.js (attached below) --> userService.js (performs DB operations).
Check the image of how the list should look like.
What actually happens is that a new user is created but the name isnt displayed.
A peek into database shows that only IDs of the blank entries are added.
FRONTEND.js
console.log('Frontend Reached');
$(document).ready(function() {
var url = '/users/delete_user';
var user_url = '/users/add_user';
function load_users(e) {
$.ajax({
url: 'userview.ejs',
dataType: 'text',
type: 'post',
ContentType: 'html',
data: $('#user_form').serialize(),
success: function(data, textStatus, jQxhr) {
console.log(data);
$('#list').html(data);
//$('#user_form').submit( load_users );
},
error: function(jqXhr, textStatus, errorThrown) {
console.log(errorThrown);
}
});
e.preventDefault();
}
//ADDING A USER
$(document).on('click', '.btn btn-success', function(e) {
e.preventDefault();
var user_name = $("#nameinput").val();
var user_age = $("#ageinput").val();
console.log(user_name);
console.log(user_age);
$.ajax({
url: 'userview.ejs',
dataType: 'text',
type: 'post',
ContentType: 'html',
data: {
'user_name': user_name,
'user_age': user_age
},
success: function(data, textStatus, jQxhr) {
console.log(data);
load_users();
},
error: function(jqXhr, textStatus, errorThrown) {
console.log(errorThrown);
}
});
e.preventDefault();
}); //onclick
}); //document ready
This is userController.js
Console logging in this file shows that the record is undefined.
var User = require('../models/usermodel.js');
var userService = require('../services/userService');
var userController = {
add: function(request, response) {
var user_name = request.body.user_name;
var user_age = request.body.user_age;
console.log(user_name); //SHOWS UNdEFINED
var newUser = new User({
name: user_name,
age: user_age
});
console.log(newUser);
//var userName = request.body.user_name;
//var userAge = request.body.user_age;
userService.add(newUser, function(err, added) {
if (err != null) {
response.send(500);
} else {
response.send(200);
}
});
},
delete: function(request, response) {
var userId = request.body.user_id;
userService.delete(userId, function(err, deleted) {
if (err != null) {
response.send(500);
} else {
response.send(200);
}
});
}
};
module.exports = userController;
Send your data using JSON.stringify(),
and specify the content-type to 'application/json' so your server will know to expect a JSON.
var data = {
'user_name': user_name,
'user_age': user_age
},
$.ajax({
url: 'userview.ejs',
type: 'post',
contentType: 'application/json',
data: JSON.stringify(data),
success: function(data, textStatus, jQxhr) {
console.log(data);
load_users();
},
error: function(jqXhr, textStatus, errorThrown) {
console.log(errorThrown);
}
});

Getting error trying to submit data using JQuery ajax

When I try to run the following JQuery ajax, I get an error saying that a parameter is missing and it will not send the data. I can't find any syntax errors. What am I doing wrong?
Here is the javascript with the JQuery ajax code:
function submitAction(actionname) {
if (actionname == "illustrationgenerate.htm") {
var thisForm = document.getElementById("illustrationTypeForm");
var fd = new FormData(thisForm);
$.ajax({
url: "illustrationgenerate.htm",
type: "POST",
data: fd,
datatype: "xml",
cache: false,
success: function (result, status, xhr) {
document.getElementById('errorMessage0').value="Success";
},
error: function (xhr, status, error) {
alert(xhr.status);
alert(request.responseText);
}
});
} else {
document.forms[0].action = actionname;
document.forms[0].method = "POST";
document.forms[0].target = '';
document.forms[0].submit();
}
}
Why not use jQuery native form encoder?
$.ajax({
...
data: $('#illustrationTypeForm').serializeArray(),
...
});
Try This
Here is the javascript with the JQuery ajax code:
function submitAction(actionname) {
if (actionname == "illustrationgenerate.htm") {
var thisForm = document.getElementById("illustrationTypeForm");
var fd = new FormData(thisForm);
$.ajax({
url: "illustrationgenerate.htm",
type: "POST",
data: $('#illustrationTypeForm').serializeArray(),
datatype: "xml",
cache: false,
success: function (result, status, xhr) {
document.getElementById('errorMessage0').value="Success";
},
error: function (xhr, status, error) {
alert(xhr.status);
alert(request.responseText);
}
});
} else {
document.forms[0].action = actionname;
document.forms[0].method = "POST";
document.forms[0].target = '';
document.forms[0].submit();
}
}
To make ajax request using jQuery a type 'POST' you can do this by following code :
$.ajax({
url: "test.php",
type: "post",
data: values ,
success: function (response) {
// you will get response from your php page (what you echo or print)
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});

how to call javascript function from jQuery ajax?

I have jQuery ajax call to get results from the server, and in success, the code should call javascript function which is not in jQuery region code, so I got error in firebug: that the call of function doesnt have reference.
here is my code (see the ajax call in function addGMarker):
function test1234(res) {
PreInfo = res;
popupContentHTML = deviceMoreinfo_callBack_ForGoogle(PreInfo);
var sum = '<p>Please, Select <b>[Sensors Reading List]</b> tab to view vehcile sensors reading, and select <b>[Device Communication Commands]</b> tab to send commands for the device:</p><br/>';
var tabs = [
new MaxContentTab('Sensors Reading List', maxContentDiv),
new MaxContentTab('Device Communication Commands', maxContentDivForCommands)];
this.openMaxContentTabsHtml(map, popupContentHTML, sum, tabs, { maxTitle: "Sensors and Features" });
var iw = map.getTabbedMaxContent();
iw.id = this.id;
GEvent.addListener(iw, 'selecttab', function (tab) {
var node = tab.getContentNode();
switch (tab.getLabel()) {
case 'Sensors Reading List':
maxContentDiv.innerHTML = '<IMG SRC="../../../images/FullModeIcons/LoadingImage.gif" /> Loading...';
//GetSensorsReading(this.id, ClientID, "En", GetSensorsReading_CallBack);
jQuery.ajax({
type: "POST",
url: "../../../DevicesManagerAjax.asmx/GetSensorsReading",
data: "{Device_ID: '" + this.id + "', ClientID: '" + ClientID + "', Page_ID: 'En'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
timeout: 70000,
success: function (msg) {
var res = msg.d;
GetSensorsReading_CallBack(res);
},
error: function (xhr, status, errorThrown) {
alert("An error occered, " + errorThrown);
}
});
break;
case 'Device Communication Commands':
maxContentDivForCommands.innerHTML = '<IMG SRC="../../../images/FullModeIcons/LoadingImage.gif" /> Loading...';
//GetContorolableSensors(this.id, ClientID, "En", GetContorolableSensors_CallBack);
jQuery.ajax({
type: "POST",
url: "../../../DevicesManagerAjax.asmx/GetContorolableSensors",
data: "{Device_ID: '" + this.id + "', ClientID: '" + ClientID + "', Page_ID: 'En'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
timeout: 70000,
success: function (msg) {
var res = msg.d;
GetContorolableSensors_CallBack(res);
},
error: function (xhr, status, errorThrown) {
alert("An error occered, " + errorThrown);
}
});
break;
}
});
}
function addGMarker(ID, point, Marker_Icon) {
icon = new GIcon(G_DEFAULT_ICON);
if (_IconClientID == "0") {
if (Marker_Icon == "blue") {
if (ID == FollowVechicleID) {
icon.image = "../../Images/Icons/" + _Follow_Icon;
}
else {
icon.image = "../../Images/Icons/" + _Normal_Icon;
}
if (ID == FollowVechicleID) {
ShowLastThreePositions();
}
}
else {
icon.image = "../../Images/Icons/" + _Speed_Icon;
}
}
else {
if (Marker_Icon == "blue") {
if (ID == FollowVechicleID) {
icon.image = "../../Images/Icons/ClientsIcons/" + _Follow_Icon;
}
else {
icon.image = "../../Images/Icons/ClientsIcons/" + _Normal_Icon;
}
}
else if (Marker_Icon == "red") {
icon.image = "../../Images/Icons/ClientsIcons/" + _Speed_Icon;
}
}
icon.iconSize = new GSize(32, 32);
icon.dragCrossSize = new GSize(0, 0);
icon.shadowSize = new GSize(32, 32);
icon.iconAnchor = new GPoint(5, 5);
marker = new GMarker(point, icon);
marker.id = ID;
GEvent.addListener(marker, 'click',
function() {
popupContentHTML = Device_Option_forGoogle(this.id);
this.openInfoWindowHtml(popupContentHTML);
}
);
GEvent.addListener(marker, 'mouseover',
function() {
//PreInfo = getDeviceInfoForPopUp(this.id, ClientID, "En");
jQuery.ajax({
type: "POST",
url: "../../../DevicesManagerAjax.asmx/getDeviceInfoForPopUp",
data: "{deviceID: '" + this.id + "', IDclient: '" + ClientID + "', Page: 'En'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
timeout: 70000,
success: function (msg) {
var res = msg.d;
test1234(res);
},
error: function (xhr, status, errorThrown) {
alert("An error occered, " + errorThrown);
}
});
});
var markers = [];
markers.push(marker);
mgr.addMarkers(markers, 0);
mgr.refresh();
ClientPOI.refresh();
POImgr.refresh();
}
It's the same code for calling Javascript function from jQuery. It's working fine. The problem is elsewhere in your code.
This might not be the exact solution, but given not to divert from the solution.
function test1234(res) {
alert(res)
}
function Test() {
jQuery.ajax({
type: "POST",
url: "/TestWebApp/ProcessServlet.do",
success: function (res) {
alert(res);
test1234(res);
},
error: function (xhr, status, errorThrown) {
alert("An error occered, " + errorThrown);
}
});
}

Categories

Resources