Why validation message is shown even after correcting values - javascript

I have html contact form in which i have handled validations in JS.
If there is any incorrect data/value in any field for e.g emailid, validation works correctly, but even after correcting the data it keeps popping.
Attaching the code and the screenshot for the same.
Please help.
function askfordemo() {
var path = document.URL;
var url = "";
url = new URL(path);
var frm = $(document.forms);
var formData = JSON.stringify(frm.serialize());
var name = $("#name").val();
var emailID = $("#emailID").val();
var phone = $("#phone").val();
var companyname = $("#companyname").val();
var filter = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (filter.test(emailID)) {
return true;
} else {
$("#emailID")[0].setCustomValidity('Invalid Email Address');
return false;
}
if ($('#date1') != null && $('#date1').is(':visible')) {
var contactdate = new Date($('#date1').val());
var dateNow = new Date();
var msg = "Date cannot be less than todays date";
if (contactdate < dateNow) {
$("#date1")[0].setCustomValidity('Date cannot be less than todays date');
return;
} else if (contactdate == 'Invalid Date') {
$("#date1")[0].setCustomValidity('Please fill out this field with Date and Time');
return
} else {
$("#date1")[0].setCustomValidity("");
}
}
if (name === '' || emailID === '' || phone === '' || companyname === '' || noofemployees === null || message === '' ||
radioValue === '' || (typeof radioValue === 'undefined')) {
return false;
}
var param = new Object();
param.name = encodeURIComponent(name);
param.emailID = encodeURIComponent(emailID);
param.phone = encodeURIComponent(phone);
param.companyname = encodeURIComponent(companyname);
param.noofemployees = encodeURIComponent(noofemployees);
param.message = encodeURIComponent(message);
param.radioValue = encodeURIComponent(radioValue);
param.date1 = encodeURIComponent(date1);
param.timezone = encodeURIComponent(timezone);
var paramjson = JSON.stringify(param);
path = path.substring(0, path.lastIndexOf("/"));
$.ajax({
url: path + '/ms/askForDemo/sendMail',
type: 'POST',
data: paramjson,
dataType: "json",
contentType: "application/json",
crossDomain: 'true',
success: function(formData) {
JSON.stringify(formData)
},
error: function(x, y, z) {
alert("Internet connection is lost. Please try again later.");
}
});
}

Related

Save values of dynamic generated HTML using javascript

I m generating dynamic html with its id. You can see the below link for the dynamic generated HTML.
Dymanic Generated HTML
So for saving this, I need some suggestion on how to save it in javascript. I tried the other fields of the HTML..
function SaveNPEDetails() {
var DashboardFields = {};
if ($('#ddlFiberised').val() == '--Select--' || $('#ddlFiberised').val() == null) {
alert('Please select FIBERISED');
return false;
}
else {
DashboardFields.NPEFiberised = $('#ddlFiberised').val();
}
if ($('#txtNoFDPSite').val() == '' || $('#txtNoFDPSite').val() == null) {
alert('Please add NO. OF FDP AT SITE');
return false;
}
else {
DashboardFields.NoOfFDPatSite = $('#txtNoFDPSite').val();
}
if ($('#txtNoOfRoutesTerAtFDP').val() == '' || $('#txtNoOfRoutesTerAtFDP').val() == null) {
alert('Please add NO. OF ROUTES TERMINATED AT FDP');
return false;
}
else {
DashboardFields.NoOfRoutesTermAtFDP = $('#txtNoOfRoutesTerAtFDP').val();
}
// Need to write saving logic for dynamic generated html here.
$.ajax({
type: "POST",
url: "DashboardData.aspx/UpdateNPEData",
data: JSON.stringify({ DashboardFields: DashboardFields }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d);
},
error: function (response) {
alert('Something went wrong..!!');
}
});
}
As per our discussion you can try something like
function SaveNPEDetails() {
var data = [];
var DashboardFields = {};
if ($('#ddlFiberised').val() == '--Select--' || $('#ddlFiberised').val() == null) {
alert('Please select FIBERISED');
return false;
}
else {
DashboardFields.NPEFiberised = $('#ddlFiberised').val();
}
if ($('#txtNoFDPSite').val() == '' || $('#txtNoFDPSite').val() == null) {
alert('Please add NO. OF FDP AT SITE');
return false;
}
else {
DashboardFields.NoOfFDPatSite = $('#txtNoFDPSite').val();
}
if ($('#txtNoOfRoutesTerAtFDP').val() == '' || $('#txtNoOfRoutesTerAtFDP').val() == null) {
alert('Please add NO. OF ROUTES TERMINATED AT FDP');
return false;
}
else {
DashboardFields.NoOfRoutesTermAtFDP = $('#txtNoOfRoutesTerAtFDP').val();
}
var chs = $("#dvNPEAddData").children(".addNPEData")
for (var i = 0; i < chs.length; i++) {
var d = {};
var ch = chs[i];
var val = $(ch).find("input[name='TerRouteName']").val();
d[$(ch).find("input[name='TerRouteName']").attr("name")] = val;
val = $(ch).find("select[name='CableType']").val();
d[$(ch).find("select[name='CableType']").attr("name")] = val;
val = $(ch).find("select[name='CableSize']").val();
d[$(ch).find("select[name='CableSize']").attr("name")] = val;
val = $(ch).find("input[name='NoLiveFibre']").val();
d[$(ch).find("input[name='NoLiveFibre']").attr("name")] = val;
data.push(d);
}
var d = JSON.stringify(data);
$.ajax({
type: "POST",
url: "DashboardData.aspx/UpdateNPEData",
data: JSON.stringify({ DashboardFields: DashboardFields , myJsonXML : d}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d);
},
error: function (response) {
alert('Something went wrong..!!');
}
});
}
Using your example in the fiddle I've done the following
$('#submit').click(function() {
var DashboardFields = {},
status = true;
$.each($('input[type="text"]'), function(i, v) {
var id = $(v).attr('id');
if ($(v).val() == '') {
alert(id + ' field is empty');
status = false;
} else {
DashboardFields[id] = $(v).val();
}
});
$.each($('select'), function(i, v) {
var id = $(v).attr('id');
if ($(v).val() == '--Select--' || $(v).val() == null) {
alert(id + ' select is empty');
status = false;
} else {
DashboardFields[id] = $(v).val();
}
});
if(!status){
alert('you have empty fields');
} else {
console.log(DashboardFields); //Here should be your Ajax Call
}
});
JsFiddle
I've used your example with ID's and created a filter in order to take dynamically the fields not by ID's, I used the ID's to map the DashboardFields object but I strongly encourage to use name or other data- param and change the jQuery code after (the line with var id=$(v).attr('id'))
Hope this helps you

Ajax still executing even an error found

Good day programmers! I'am trying to submit a form then validate it using jquery with 2 ajax events. I am using ajax(timeconflict.php) for validating if there is conflict with the user's time input. but even tho it returns an error, the other ajax event is still executing(reserveroom.php). sorry for my grammar, here's my code
$('#submitreserve').click(function(){
var error=false;
var inputtimeerror = false;
var conflict = false;
var message="";
var to="";
var from="";
var fromH="";
var fromM="";
var toH="";
var toM="";
var now = new Date();
if($("#datetimepicker").val()=="" || $("#trtitle").val()=="" || $("#from").val()=="" || $("#to").val()=="")
{
error = true;
message ="Please Fill all required Fields!";
}
if($("#from").val()!="" && $("#to").val()!="")
{
from = $("#from").val(); // start time
to = $("#to").val(); // end time
fromH = from.substr(0,2); // get hour from start time
fromM = from.substr(3,2); // get mins from start time
toH = to.substr(0,2); // get hour from end time
toM = to.substr(3,2); // get mins from end time
var timeerror = false;
var inputDate = $("#datetimepicker").val(); // date
inputFrom = new Date(inputDate+" "+from); // time and start date
inputTo = new Date(inputDate+" "+to); // time and end date
if(fromH > toH)
{
timeerror=true;
}
if(fromH == toH && fromM >= toM)
{
timeerror=true;
}
if(to == from)
{
timeerror=true;
}
if(inputFrom <= now || inputTo <= now)
{
inputtimeerror = true;
}
if(error == false && inputtimeerror == false)
{
$.ajax({
type:'post',
url: 'timeconflict.php',
data: { startTime : from,
endTime : to,
inputDate : inputDate,
room : target },
dataType: 'json',
success : function(e)
{
if (e.length == 0)
{
console.log("No value returned");
}
else
{
console.log(e[0]);
console.log("Conflict time schedule!");
conflict = true;
error=true;
alert("Conflict");
return false;
}
}
});
}
if(inputtimeerror)
{
error=true;
message = "Reservation time must be higher than time today!";
}
if(conflict)
{
error = true;
message = "Conflict Time Schedule!";
}
if(timeerror)
{
message = "Invalid End Time!";
error=true;
}
}
if(error==true)
{
$("#error").text(message);
return false;
}
if(error==false)
{
$.ajax({
type:'post',
url: 'reserveroom.php',
data: { trtitle : $("#trtitle").val(),
from : $("#from").val(),
to : $("#to").val(),
datetimepicker : $("#datetimepicker").val(),
ninjaday : $("#ninjaday").val(),
ninjaroom : $("#ninjaroom").val() },
dataType: 'json'
});
}
});
//timeconflict.php
<?php
include ('../conn.php');
// header("Content-Type: application/json");
$start_time = $_POST['startTime'];
$end_time = $_POST['endTime'];
$res_date = $_POST['inputDate'];
$res_room = $_POST['room'];
$sql = "SELECT * from tdc_reservation where ( ((`reserve_start` BETWEEN '".$start_time."' and '".$end_time."')";
$sql.= " or (`reserve_end` BETWEEN '".$start_time."' and '".$end_time."' )) or";
$sql.= " (('".$start_time."' BETWEEN `reserve_start` and `reserve_end`) or ";
$sql.= " ('".$end_time."' BETWEEN `reserve_start` and `reserve_end`)) or ";
$sql.= " ((`reserve_start` = '".$start_time."' ) or (`reserve_end`='".$start_time."' ))";
$sql.= " or ((`reserve_start` = '".$end_time."') or (`reserve_end` = '".$end_time."')) )";
$sql.= " and reserve_date='".$res_date."' and reserve_room = '".$res_room."' LIMIT 1 ";
$result = mysql_query($sql,$con);
$stack = array();
while($row = mysql_fetch_array($result))
{
$stack[] = $row;
}
$json = json_encode($stack);
mysql_close();
echo $json;
?>
I really hope someone would help me, this error already ate 2 days of my life :(
Modified your code, hope this will work
$('#submitreserve').click(function(){
var message="";
var to="";
var from="";
var fromH="";
var fromM="";
var toH="";
var toM="";
var now = new Date();
if($("#datetimepicker").val()=="" || $("#trtitle").val()=="" || $("#from").val()=="" || $("#to").val()=="")
{
message ="Please Fill all required Fields!";
}else{
from = $("#from").val(); // start time
to = $("#to").val(); // end time
fromH = from.substr(0,2); // get hour from start time
fromM = from.substr(3,2); // get mins from start time
toH = to.substr(0,2); // get hour from end time
toM = to.substr(3,2); // get mins from end time
var inputDate = $("#datetimepicker").val(); // date
inputFrom = new Date(inputDate+" "+from); // time and start date
inputTo = new Date(inputDate+" "+to); // time and end date
if(fromH > toH || (fromH == toH && fromM >= toM) || to == from)
{
message = "Invalid End Time!";
}
else if(inputFrom <= now || inputTo <= now)
{
message = "Reservation time must be higher than time today!";
}else{
$.ajax({
type:'post',
url: 'timeconflict.php',
data: { startTime : from,
endTime : to,
inputDate : inputDate,
room : target },
dataType: 'json',
success : function(e)
{
if (e.length == 0)
{
console.log("No value returned");
reserveRoom();
}
else
{
console.log(e[0]);
console.log("Conflict time schedule!");
alert("Conflict");
return false;
}
}
});
}
}
alert(message);
});
function reserveRoom(){
$.ajax({
type:'post',
url: 'reserveroom.php',
data: { trtitle : $("#trtitle").val(),
from : $("#from").val(),
to : $("#to").val(),
datetimepicker : $("#datetimepicker").val(),
ninjaday : $("#ninjaday").val(),
ninjaroom : $("#ninjaroom").val() },
dataType: 'json'
});
}

How to display alert after AJAX post success.alert?

In my Node application I have used get and post request. Using get just renders the page and using post insert data into MySQL database. Data is inserted properly but after post gets called and alert fade away very quickly.
This is my code from app.js:
app.get('/Associate', routes.Associate);
app.get('/addAssociate',routes.addAssociate);
app.post('/addAssociate',routes.postAssociate);
This is my code from routes.js:
Associate: function(req, res) {
sess = req.session;
var name = req.session.user;
var username = 'SELECT first_name from user_info where email_id=?';
if (sess.user) {
console.log('\n--------------------- Associate ----------------------');
var db = req.app.get('db')();
var id = req.query['id'];
// var newsquery='SELECT * from associate_info';
var assoquery = 'SELECT associate_id,doctor_id,CONCAT(initial," ",first_name," ",middle_name," ",last_name) As Name,qualification,address_line1,city,state,pincode,email_id,contact_no from associate_info ';
var redirect = 'Associate_Listing';
async.parallel({
one: function(callback) {
db.query(assoquery, function(error, rows, fields, next) {
console.log("length-\t", rows.length);
callback(error, rows);
});
},
two: function(callback) {
db.query(username, [name], function(error, rows, fields, next) {
// console.log(rows.length);
console.log(rows);
callback(error, rows);
});
}
},
function(error, results) {
var totalNews = results.one.length;
for (var i = 0; i < results.one.length; i++) {
if (!(results.one[i].views > 0) || results.one[i].views == null)
results.one[i].views = 0;
results.one[i].ids = i + 1;
// if(!(results.one[i].views>0))
// results.one[i].views=0;
}
// console.log("--------",results.one[0].id);
res.render(redirect, {
error: JSON.stringify(1),
from_period: 0,
to_period: 0,
state: JSON.stringify("All States"),
user2: "Dr" + " " + JSON.parse(JSON.stringify(results.two[0]["first_name"])),
user: JSON.parse(JSON.stringify(req.session.user)),
Associate: results.one,
str_journal: JSON.stringify(results.one),
user_type_id: req.session.user_type_id,
totalJournals: JSON.stringify(totalNews)
});
});
} else {
res.redirect('/login');
}
},
// addJournal:function(req,res){
addAssociate: function(req, res) {
console.log('\n-------------------- addAssociate ----------------------\n');
var name = req.session.user;
var db = req.app.get('db')();
var username = 'SELECT first_name from user_info where email_id=?';
if (req.session.user) {
async.parallel({
one: function(callback) {
db.query(username, [name], function(error, rows, fields, next) {
console.log("length-\t", rows.length);
callback(error, rows);
});
}
},
function(error, results) {
res.render('addAssociate', {
user: JSON.parse(JSON.stringify(req.session.user)),
// cases : results.one,
user2: "Dr" + " " + JSON.parse(JSON.stringify(results.one[0]["first_name"])),
user_type_id: req.session.user_type_id,
// totalNews :JSON.stringify(totalNews)
})
});
} else {
res.redirect('/login');
// res.redirect('addAssociate');
}
},
postAssociate: function(req, res) {
console.log('\n-------------------- postAssociate ----------------------\n');
var db = req.app.get('db')();
// res.send('Username: ' + req.body.doctorName);
// var title = req.body.title;
// var created =req.body.created;
// initial : req.body.doctorName,
// var id=1;
// var dateArray=created.split('/');
// var finalDate=""+dateArray[2]+"/"+dateArray[1]+"/"+dateArray[0];
// var date1=new Date(finalDate);
var initial;
var first_name;
var middle_name;
var last_name;
var qualification;
var address_line1;
var address_line2;
var city;
var state;
var pincode;
var email_id;
var contact_no;
var Uname = req.session.user;
var post = {
initial: req.body.initial,
first_name: req.body.first_name,
middle_name: req.body.middle_name,
last_name: req.body.last_name,
qualification: req.body.qualification,
address_line1: req.body.address_line1,
address_line2: req.body.address_line2,
city: req.body.city,
state: req.body.state,
pincode: req.body.pincode,
email_id: req.body.email_id,
contact_no: req.body.contact_no,
status: 1,
};
console.log('--------------------' + initial)
console.log(initial);
console.log(post);
db.query('SELECT * from user_info where email_id= ? ', [Uname], function(error, rows, fields) {
if (error) {
console.log(error);
} else {
console.log('name------------' + Uname);
console.log('rows---------' + rows.length);
for (var i in rows) {
console.log('----------hhh---' + rows[i].doctor_id);
}
db.query('INSERT INTO associate_info SET doctor_id=' + rows[i].doctor_id + ', creation_date=CURRENT_TIMESTAMP(), ? ', post, function(error, result) {
console.log('inside if');
if (error) {
console.log(error);
res.status(200).send({
success: 3,
error: error
});
return;
}
console.log('Associate added successfully.');
});
}
});
},
this is jquery ajax code
$(document).ready(function() {
$("#save").click(function() {
var initial = $("#doctorName").val();
var first_name = $("#firstName").val();
var middle_name = $("#middleName").val();
var last_name = $("#lastName").val();
var qualification = $("#qualification").val();
var address_line1 = $("#address1").val();
var address_line2 = $("#address2").val();
var city = $("#city").val();
var state = $("#state").val();
var pincode = $("#pincode").val();
var email_id = $("#email").val();
var contact_no = $("#mobile").val();
var dr = /^[a-zA-Z]+\.$/;
var alphaExp = /^[a-zA-Z]+$/;
var zipexp = /^[0-9]{1,6}$/;
var mobileexp = /^(\+91-|\+91|0)?\d{10}$/;
var emailexp = /^[A-Z0-9_'%=+!`#~$*?^{}&|-]+([\.][A-Z0-9_'%=+!`#~$*?^{}&|-]+)*#[A-Z0-9-]+(\.[A-Z0-9-]+)+$/i;
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'initial=' + initial + '&first_name=' + first_name + '&middle_name=' + middle_name + '&last_name=' + last_name + '&qualification=' + qualification + '&address_line1=' + address_line1 + '&address_line2=' + address_line2 + '&city=' + city + '&state=' + state + '&pincode=' + pincode + '&email_id=' + email_id + '&contact_no=' + contact_no;
if (initial == '' || first_name == '' || middle_name == '' || last_name == '' || qualification == '' || address_line1 == '' || address_line2 == '' || city == '' || state == '' || pincode == '' || email_id == '' || contact_no == '') {
alert("Please Fill All Mandatory Fields");
return false;
} else if (!initial.match(alphaExp) && !initial.match(dr)) {
alert("please insert valid initial");
$("#doctorName").val('');
document.getElementById('doctorName').focus();
return false;
} else if (!first_name.match(alphaExp)) {
alert("please insert valid first name");
$("#firstName").val('');
document.getElementById('firstName').focus();
return false;
} else if (!middle_name.match(alphaExp)) {
alert("please insert valid middle name");
$("#middleName").val('');
document.getElementById('middleName').focus();
return false;
} else if (!last_name.match(alphaExp)) {
alert("please insert valid last name");
$("#lastName").val('');
document.getElementById('lastName').focus();
return false;
} else if (!pincode.match(zipexp) || pincode.length != 6) {
alert("please insert valid pincode");
$("#pincode").val('');
document.getElementById('pincode').focus();
return false;
} else if (!email_id.match(emailexp)) {
alert("please insert email id");
$("#email").val('');
document.getElementById('email').focus();
return false;
} else if (!contact_no.match(mobileexp)) {
alert("please insert valid contact no");
$("#mobile").val('');
document.getElementById('mobile').focus();
return false;
} else {
// AJAX Code To Submit Form.
$.ajax({
type: "post",
url: "/addAssociate",
// contentType: 'application/json',
data: dataString,
cache: false,
success: function(data) {
console.log("data-----------" + data);
alert("hi");
}
});
}
// return;
// return false;
});
});
I want to display an alert after data inserted successfully into database.
Just Try the Following to make some delay.
jQuery :
$.ajax({
url:'path-to-process',
type:'POST',
data:{},
success:function(){
// Content to Display on Success.
setTimeout(function () {
// Content to Display on Success with delay.
}, 800);
}
});
Here, the "setTimeout()" will provide some specified time delay for display your content.
Have a Nice Day !
http://jsbin.com/jatuju/edit?js,output
If you are using the plan old JavaScript,you can using the XMLHttpRequest status code to determine whether is success or not

How to return JSON data in return view method in MVC using an Ajax call

I am working with MVC and Ajax and jQuery. I am returning my JSON value from my action method like below.
public ActionResult GetMYSDRViews(List<string> AssetNames, List<string> UtilizationHubs, string RedirectView)
{
try
{
//ViewBag.InitParams = MvcApplication.objInitParams;
string UserType = MvcApplication.objInitParams.UserType;
bool Execute;
List<MYSDR> MysdrListCollection = new List<MYSDR>();
ServiceClient objService = new ServiceClient();
objService.ClientCredentials.Windows.ClientCredential = new System.Net.NetworkCredential("v-saramb", "sdatnov#2014", "REDMOND");
objService.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
var result = String.Empty;
if (RedirectView == "Agent View")
{
ViewData["Flag"] = "AgentView";
#region Agent View
result = objService.SalesDeskAgent_DynamicAsset("REDMOND\\v-susudh", "", "");
#endregion
}
else if (RedirectView == "Manager View")
{
//result = objService.SalesDeskAgent_DynamicAsset("REDMOND\\v-susudh", "", "");
ViewData["Flag"] = "Manager View";
userHUbdata.Clear();
foreach (string Hub in UtilizationHubs)
{
ServiceReference.MYSDRFields obj2 = new ServiceReference.MYSDRFields();
obj2.Hub = Hub;//cmbHubs.SelectedItem.ToString();
if (obj2.Hub != "All")
userHUbdata.Add(obj2);
}
result = objService.SalesDeskManagerView_ConditionbasedwithFilters("", "", userHUbdata, true);
}
//else if (RedirectView == "BulkAssignment View")
// {
// result = objService.SalesDeskManagerView("REDMOND\\v-susudh", "");
// }
XDocument xmldoc = null;
try
{
xmldoc = XDocument.Parse(result.ToString());
Execute = true;
}
catch
{
Execute = false;
}
if (Execute)
{
#region
MysdrListCollection.Clear();
var data = (from info in xmldoc.Elements("NewDataSet").Elements("Table1")
where Convert.ToString(info.Element("Status").Value) != "" && Convert.ToString(info.Element("Status").Value) != "New" && Convert.ToString(info.Element("Status").Value) != "Projected"
select new MYSDR
{
SRNO = Convert.ToString(info.Element("SRNO").Value),
CustomerName = Convert.ToString(info.Element("CustomerName0").Value),
ServiceLevel = Convert.ToString(info.Element("TypeofRequest").Value.Replace("Unsolicited", "Proactive").Replace("Partner Proactive", "Proactive")),
CRMID = Convert.ToString(info.Element("CRMID").Value),
//DueDate_Date = Convert.ToDateTime(info.Element("DueDate").Value),
RequestType = ((Convert.ToString(info.Element("TypeofRequest").Value) == "Managed Proposal") || (Convert.ToString(info.Element("TypeofRequest").Value) == "Standard Proposal") || (Convert.ToString(info.Element("TypeofRequest").Value) == "Unsolicited Proposal") || (Convert.ToString(info.Element("TypeofRequest").Value) == "Unsolicited Proposal Lite")) ? "Proposal" : ((Convert.ToString(info.Element("TypeofRequest").Value) == "AIO") || (Convert.ToString(info.Element("TypeofRequest").Value) == "AIO Prep")) ? "AIO" : ((Convert.ToString(info.Element("TypeofRequest").Value) == "M&A Full") || (Convert.ToString(info.Element("TypeofRequest").Value) == "M&A Light")) ? "M&A" : Convert.ToString(info.Element("TypeofRequest").Value),
Region = Convert.ToString(info.Element("Region").Value),
Segment = Convert.ToString(info.Element("Segment").Value),
Assigned = ((Convert.ToString(info.Element("Status").Value) == "Projected") || ((Convert.ToString(info.Element("Status").Value) == "New"))) ? "Assign" : Convert.ToString(info.Element("AssignedToName").Value),
Language = Convert.ToString(info.Element("Language").Value),
ID = Convert.ToString(info.Element("ID").Value),
Status = Convert.ToString(info.Element("Status").Value),
AM = Convert.ToString(info.Element("AM").Value),
Hub = Convert.ToString(info.Element("Hub").Value),
DueDate = Convert.ToDateTime(info.Element("DueDate").Value).Date,
RequestDate = Convert.ToDateTime(info.Element("Requestdate").Value).Date,
PrimaryContact = Convert.ToString(info.Element("PrimaryContact").Value),
Country = Convert.ToString(info.Element("Country").Value),
SolutionForProposal = Convert.ToString(info.Element("SolutionForProposal").Value),
Reactive = ((Convert.ToString(info.Element("TypeofRequest").Value).Contains("Research")) && (Convert.ToString(info.Element("RequestOrigin").Value) == "Reactive")) ? "R" : "",
CoOwner = ((Convert.ToString(info.Element("Status").Value) == "New") || (Convert.ToString(info.Element("Status").Value) == "Projected") || (Convert.ToString(info.Element("TypeofRequest").Value).StartsWith("QA"))) ? "" : (((Convert.ToString(info.Element("Status").Value) != "New") || (Convert.ToString(info.Element("Status").Value) != "Projected")) && (Convert.ToString(info.Element("Coowner").Value) == "")) ? "Add Co-Owner" : (Convert.ToString(info.Element("Coowner").Value)),
}).AsEnumerable();
MysdrListCollection = data.ToList<MYSDR>();
// Session["MYSDRGridAgentView"] = MysdrListCollection.OrderBy(a => a.DueDate);
// return View(data);
#endregion
}
var serializer = new JavaScriptSerializer();
var resultContent = new ContentResult();
serializer.MaxJsonLength = Int32.MaxValue; // Whatever max length you want here
resultContent.Content = serializer.Serialize(MysdrListCollection.OrderBy(a => a.DueDate));
resultContent.ContentType = "application/json";
return resultContent;
// return Json(MysdrListCollection.OrderBy(a => a.DueDate),JsonRequestBehavior.AllowGet);
// return View("Mysdrviews",MysdrListCollection.OrderBy(a => a.DueDate));
//return MysdrListCollection;
}
catch (Exception ex)
{
return Json("");
}
}
I am using my Ajax call from jQuery like below.
$.ajax({
url: '#Url.Action("GetMYSDRViews", "MYSDR")',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
// url: '/MYSDR/PostbtnSubmit',
data: JSON.stringify({ AssetNames: itemsListAssets, UtilizationHubs: itemUtilizationHub, RedirectView: 'Manager View' }),
success: function (result) {
debugger;
var grid = $('#MYSDRGridAgentView').getKendoGrid();
grid.dataSource.data(result);
grid.refresh();
$('#Loader').oLoader('hide');
// $('#result').html('"PassThings()" successfully called.');
},
failure: function (response) {
debugger;
// $('#result').html(response);
}
});
Up to here everything is fine. But when I try to return my JSON result in my return view method like below, I am not getting any error, but I am not able to successfully return result, and my debugger pint also is not hitting at the Success or Error functions in my jQuery.
Please let me know where to change my Ajax function. I am stuck here like anything.
Make the function a JsonResult and return Json(something).
public JsonResult GetMYSDRViews(List<string> AssetNames, List<string> UtilizationHubs, string RedirectView)
{
...
return Json(MysdrListCollection.OrderBy(a => a.DueDate));
}
You put failure instead of error.
error: function (response) {
debugger;
// $('#result').html(response);
}

Parse JSON array with AJAX from PHP

I am having trouble making an PHP API to get data from MYSQL and parse JSON. I have a demo app (hiApp) and comes with some JSON files inside a folder.
The demo JSON file is like this:
{ "err_code": 0, "err_msg": "success", "data": [{"nickname":"Joao","location":"I.13"},{"nickname":"Victor","location":"2811"}]}
This what my contacts.php is returning:
[{"nickname":"Joao","location":"I.13"},{"nickname":"Victor","location":"2811"}]
My contacts.php api looks like this:
…
…
$result = mysql_query("select * from sellers", $db);
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['nickname'] = $row['first_name'];
$row_array['location'] = $row['territory'];
array_push($json_response,$row_array);
}
echo json_encode($json_response);
?>
The js file to parse JSON, looks like this:
define(['utils/appFunc',
'i18n!nls/lang',
'components/networkStatus'],function(appFunc,i18n,networkStatus) {
//var apiServerHost = window.location.href;
var xhr = {
search: function(code, array){
for (var i=0;i< array.length; i++){
if (array[i].code === code) {
return array[i];
}
}
return false;
},
getRequestURL: function(options){
//var host = apiServerHost || window.location.host;
//var port = options.port || window.location.port;
var query = options.query || {};
var func = options.func || '';
var apiServer = 'api/' + func + '.php' +
(appFunc.isEmpty(query) ? '' : '?');
var name;
for (name in query) {
apiServer += name + '=' + query[name] + '&';
}
return apiServer.replace(/&$/gi, '');
},
simpleCall: function(options,callback){
options = options || {};
options.data = options.data ? options.data : '';
//If you access your server api ,please user `post` method.
//options.method = options.method || 'GET';
options.method = options.method || 'POST';
if(appFunc.isPhonegap()){
//Check network connection
var network = networkStatus.checkConnection();
if(network === 'NoNetwork'){
hiApp.alert(i18n.error.no_network,function(){
hiApp.hideIndicator();
hiApp.hidePreloader();
});
return false;
}
}
$$.ajax({
url: xhr.getRequestURL(options) ,
method: options.method,
data: options.data,
success:function(data){
data = data ? JSON.parse(data) : '';
var codes = [
{code:10000, message:'Your session is invalid, please login again',path:'/'},
{code:10001, message:'Unknown error,please login again',path:'tpl/login.html'},
{code:20001, message:'User name or password does not match',path:'/'}
];
var codeLevel = xhr.search(data.err_code,codes);
if(!codeLevel){
(typeof(callback) === 'function') ? callback(data) : '';
}else{
hiApp.alert(codeLevel.message,function(){
if(codeLevel.path !== '/')
mainView.loadPage(codeLevel.path);
hiApp.hideIndicator();
hiApp.hidePreloader();
});
}
}
});
}
};
return xhr;
});
I know the error is in the way contacts.php is displaying the JSON results or I need to change something in the js file.
Thanks for the help.
Based on your comments above I've tried to rewrite a solution keeping the same structure, but removing the unnecessary things; this is what the code may look like. Note that there are no references to err_code and err_msg peoperties, and the callback is called directly on data variable.
define(['utils/appFunc',
'i18n!nls/lang',
'components/networkStatus'],function(appFunc,i18n,networkStatus) {
//var apiServerHost = window.location.href;
var xhr = {
getRequestURL: function(options){
//var host = apiServerHost || window.location.host;
//var port = options.port || window.location.port;
var query = options.query || {};
var func = options.func || '';
var apiServer = 'api/' + func + '.php' +
(appFunc.isEmpty(query) ? '' : '?');
var name;
for (name in query) {
apiServer += name + '=' + query[name] + '&';
}
return apiServer.replace(/&$/gi, '');
},
simpleCall: function(options,callback){
options = options || {};
options.data = options.data ? options.data : '';
//If you access your server api ,please user `post` method.
//options.method = options.method || 'GET';
options.method = options.method || 'POST';
if(appFunc.isPhonegap()){
//Check network connection
var network = networkStatus.checkConnection();
if(network === 'NoNetwork'){
hiApp.alert(i18n.error.no_network,function(){
hiApp.hideIndicator();
hiApp.hidePreloader();
});
return false;
}
}
$$.ajax({
url: xhr.getRequestURL(options) ,
method: options.method,
data: options.data,
success:function(data){
data = data.length > 0 ? JSON.parse(data) : [];
if (typeof(callback) === 'function' && data !== undefined)
callback(data);
}
});
}
};
return xhr;
});
Then you may call it this way, using directly response var, which now contains the parsed data array:
loadContacts: function() {
if(VM.module('contactView').beforeLoadContacts()) {
xhr.simpleCall({
query: { callback: '?' },
func: 'contacts'
}, function (response) {
if (response !== undefined) {
VM.module('contactView').render({
contacts: response
});
}
});
}
}
Also, you would have to add
header('Content-Type: application/json');
before your PHP echo line in order to be able to parse it in JS.
Ok, many thanks Andrea, looks like there is something else that I'm missing because the results from the contacts.php and the initial contacts.php file is the same in my browser:
[{"nickname":"Joao","location":"I.13"},{"nickname":"Victor","location":"2811"}]
It works just fine if I use the initial contacts.php that only has pure json data like above, but if I switch to my api it stops working.
Also it stops working if I use this in the initial contacts.php:
<?php
$myString = '[{"nickname":"Joao","location":"I.13"},{"nickname":"Victor","location":"2811"}]';
echo $myString;
?>
I'll keep looking, but thanks to you I'm one step ahead.

Categories

Resources