jquery validation onSubmit ajax post JSON response - json

I have a very complicated post using jquery validation and an AJAX post that gets a JSON response back from the server and puts it in a jqGrid... But it seems as though my onsuccess is never being called at any point...
$(document).ready(function () {
$("#formSearchByMRN").validate({
rules: {
MRN: { required: true, minLength: 6 }
},
messages: {
MRN: 'Please Enter a Valid MRN'
},
submmitHandler: function (form) {
e.preventDefault();
animateLoad();
debugger;
var theURL = form.action;
var type = form.methd;
var data = $(this).serialize();
$.ajax({
url: theURL,
type: type,
data: data,
dataType: "json",
success: function (result) {
debugger;
var data = result;
if (data.split(':')[0] == "Empty record") {
$("#list").unblock();
$('#resultDiv').html('<b><p style="color: #ff00ff">' + data + '</p></b>');
setTimeout(function () {
$('#resultDiv').html("");
}, 10000);
}
else {
binddata(data);
}
}
});
return false;
}
});
});
It would seem I never get into the submmitHandler. Event though I manage to get to my server side function and it does return, it prompts my UI to save a file which contains the JSON results...
No good.
Am I going about validating my form before my AJAX post the wrong way? Does anybody have any advice about best practices in validating AJAX posts?
UPDATE... MARK R. This is what I attempted. It seems as though I never get in to the success function... My suspicion is that I am not really posting via ajax, but instead doing a full post. I don't understand why.
$('#submitMRN').click(function () {
$("#formSearchByMRN").validate({
rules: {
MRN: { required: true, minLength: 6 }
},
messages: {
MRN: 'Please Enter a Valid MRN'
}
});
if ($('#submitMRN').valid()) {
$("#list").block({ message: '<img src="../../Images/ajax-loader.gif" />' });
$.ajax({
url: $('#submitMRN').action,
type: $('#submitMRN').method,
data: $('#submitMRN').serialize(),
dataType: "json",
success: function (result) {
debugger;
var data = result;
if (data.split(':')[0] == "Empty record") {
$("#list").unblock();
$('#resultDiv').html('<b><p style="color: #ff00ff">' + data + '</p></b>');
setTimeout(function () {
$('#resultDiv').html("");
}, 10000);
}
else {
binddata(data);
}
}
});
}
});

$('#SubmitButton').click(function (){
//Check that the form is valid
$('#FormName').validate();
//If the Form is valid
if ($('#FormName').valid()) {
$.post(...........
}
else {
//let the user fix their probems
return false;
}
});//$('#SubmitButton').click(function (){

Related

ajax json parsing to return related values

I am trying to only parse the information related to a certain "market_name" however I cannot seem to figure out how. The api is located at https://stocks.exchange/api2/ticker which displays information related to the entire exchange. I simply need all of the information returned relating to the "market_name" I am searching for such as ETH_BTC
Ajax:
$.ajax({
url: "https://stocks.exchange/api2/ticker",
dataType: 'json',
success: function(data) {
last = data.last;
console.log(last);
$("#btcprice").text(last);
},
error: function() {
//alert("Was unable to get info!");
}
});
That's because data is an array of objects, not a single object.
Try:
$.ajax({
url: "https://stocks.exchange/api2/ticker",
dataType: 'json',
success: function (data) {
// find object
var market = data.find(function (obj) {
return obj.market_name == 'ETH_BTC';
});
$("#btcprice").text(market.last);
},
error: function() {
//alert("Was unable to get info!");
}
});
Use array filter() method to filter out the record having market_name as ETH_BTC.
array.filter(obj => {
return obj.market_name == 'ETH_BTC'
});
DEMO
var jsonObj = [{"min_order_amount":"0.00000010","ask":"0.00000017","bid":"0.0000001","last":"0.00000010","lastDayAgo":"0.00000009","vol":"154955.9586604","spread":"0","buy_fee_percent":"0","sell_fee_percent":"0","market_name":"ATR_BTC","market_id":338,"updated_time":1527789301,"server_time":1527789301},{"min_order_amount":"0.00000010","ask":"0.000032","bid":"0.000012","last":"0.00003200","lastDayAgo":"0.000065","vol":"372.5011152","spread":"0","buy_fee_percent":"0","sell_fee_percent":"0","market_name":"ETH_BTC","market_id":35,"updated_time":1527789301,"server_time":1527789301},{"min_order_amount":"0.00000010","ask":"0.00003595","bid":"0.00003","last":"0.00003000","lastDayAgo":"0.00003001","vol":"26.44435669","spread":"0","buy_fee_percent":"0","sell_fee_percent":"0","market_name":"ARDOR_BTC","market_id":262,"updated_time":1527789301,"server_time":1527789301}];
var res = jsonObj.filter(obj => {
return obj.market_name == 'ETH_BTC'
});
console.log(res);
$.ajax({
url: "https://stocks.exchange/api2/ticker",
dataType: 'json',
success: function(data) {
var results = [];
var searchField = "market_name";
var searchVal = "ETH_BTC";
for (var i=0 ; i < data.length ; i++)
{
if (data[i][searchField] == searchVal) {
results.push(data[i]);
}
}
$("#btcprice").text(results[0].last);
},
error: function() {
//alert("Was unable to get info!");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here is a simple code in which you find what you want simply just change searchVal statically or dynamically according to your need......

Nested AJAX call in React redux

So I'm working on some demoware and I have two AJAX calls, the first is just a last modified date, to let me know whether to fetch data from the second. This works, but I feel like there's a smarter way to do this for real applications, and I'm just a UI monkey trying to come up in the world, any advice is much appreciated.
componentDidMount() {
this.getJson();
setInterval(this.getJson.bind(this), 1000);
}
getJson() {
const el = this;
const isModified = (date) => {
let mod = false;
if (this.state.lastModified == date) {
console.log('no change');
} else {
mod = true;
console.log({
'previously modified': this.state.lastModified,
'newly modified': date
});
el.setState({lastModified: date});
}
return mod;
}
this.serverRequest = $.ajax({
url: 'URL_LAST_MODIFIED',
success: function(result) {
const lastModified = $.parseJSON(result).LastModifiedDateTime;
if (isModified(lastModified)) {
$.ajax({
url: 'URL_DATA',
success: function(result2) {
const result2Obj = $.parseJSON(result2);
el.setState({data: result2Obj});
},
error: function(xhr, status, err) {
alert(err.toString());
}
})
}
},
error: function(xhr, status, err) {
}
});
}
I think it is realted to this:
https://github.com/reactjs/redux/issues/1676
The idea is create a action for the first ajax call... and on success dispatch another action to execute the second call.

jqPlot and JSON formatted Data

I'm returning a JSON string with an Ajax call in jQuery, I'd like to pump that data into a bar chart using jqPlot.
I got the JSON conversion code from another Stack-Overflow post, but can't understand why this isn't working. My code:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(DTO), //JSON.stringify(AnDParms), combined,
url: "GetAdmitsDischarges.asmx/GetAandD",
dataType: "json",
success: function (data) {
//do chart stuff here.
var line1 = [];
for (var prop_name in data.d) {
line1.push([prop_name, data[prop_name]])
}
var ticks = ['Admits', 'Discharges'];
var plot1 = $.jqplot('chartdiv', [line1], {
title: 'Admits & Discharges',
series: [{ renderer: $.jqplot.BarRenderer}],
axesDefaults: {
tickRenderer: $.jqplot.CanvasAxisTickRenderer
},
axes: {
xaxis: {
renderer: $.jqplot.CategoryAxisRenderer
}
}
});
//to prove the flow is working...
//alert("Data: " + data.d);
}, //end of success
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus + ' ' + errorThrown + ' ' + XMLHttpRequest);
} //end of error
}); //end of ajax call
In Firebug, the value of line1 is (going from 0 to 32):
[["0", undefined],["1", undefined],...["31", undefined],["32",
undefined]]
While the value of data is:
Object { d="{"Admits":"35","Discharges":"36"}" }
Thanks for any help you can offer...
The problem is your JSON structure:
{
"Admits": "35",
"Discharges": "36"
}
You are providing a JSON object, but jqplot needs array instead:
[
["Admits", 35],
["Discharges", 36]
]
I finally figured it out with the help of Dave Ward of Encosia.com...if you've not checked out his blog, head straight there right now...it's great for all your .Net/jQuery needs.
Here is my javascript:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(DTO),
url: "GetAdmitsDischarges.asmx/GetAandD",
dataType: "json",
success: function (data) {
var jqPlotData = $.map(data.d, function (value, key) {
if (key != "__type") {
return [value]; //was key, value
}
});
var ticks = ['Admits', 'Discharges'];
var plot1 = $.jqplot('chartdiv', [jqPlotData], {
title: 'Admits & Discharges',
seriesDefaults: {
renderer: $.jqplot.BarRenderer,
rendererOptions: { varyBarColor: true },
pointLabels: { show: true }
},
axes: {
xaxis: {
renderer: $.jqplot.CategoryAxisRenderer,
ticks: ticks
}
},
highlighter: { show: false }
});
Also, I removed the JSON serialization from my web service, and just returned the object. Hopefully this will help others.

jQuery UI - Autocomplete with extra params - returned data

All,
I've moved on to using the ui autocomplete rather than the plugin, took me a while to figure out extra params based on an example I found here, but that part works.
I'm having problems with dealing with the return data. In the code below I can alert out the title being returned, but I get a drop down of 'UNDEFINED' in the browser.
Thanks in advance.
$('#DocTitle').autocomplete({
source: function(request, response) {
$.ajax({
url: "index.pl",
dataType: "json",
data: {
Title: request.term,
maxRows: 10
},
success: function(data) {
response($.map(data, function(item) {
alert(item.TITLE);
return {
TITLE: item.TITLE
}
}))
}
})
}
});
I am using jquery UI autocomplete as follows and it is working quite fine for me. You may try on the similar lines.
$('input[type=text][name=City]').autocomplete({
source: function(request, response) {
$.getJSON($('input#CitySuggestionsLink').val(), {
term: request.term,
stateId: $('select#StateName option:selected').attr('value')
}, response);
},
search: function() {
// custom minLength
var term = this.value;
if (term.length < 1) {
return false;
}
},
delay: 200,
focus: function() {
// prevent value inserted on focus
return false;
},
select: function(event, ui) {
return false;
}
});

$jQuery Tree from json data ---> .live is killing me

I'm trying to build a tree from json data, this data are loaded on demand from php files. My problem is that i can't find a way to get to lvl 3 ;). Here is my code:
$(document).ready(function()
{
//Get the screen height and width
var Height = $(document).height()/2;
var Width = $(window).width()/2;
$("#div1").hide();
$("#div2").hide('slow');
$.ajax(
{
type: 'post',
async: true,
url: "getparents.php",
data: {'id' : 12200},
dataType: "json",
cache: false,
beforeSend: function ()
{
//Show the Loading GIF at centered position
$('#loading').css({'top': Height, 'left': Width}).show();
},
success: function(json_data)
{
$("#div1").empty().show();
$('<ul class="parentContainer"></ul>').appendTo("#div1");
$.each(json_data, function(key, object)
{
$('<li id="node">'+object.name+'</li>').data('id', object.id).appendTo(".parentContainer");
if (object.childbool == true)
{
$('li:last').addClass('childfull')
}
});
},
error: function ()
{
$('#loading').hide();
alert('Something Went Wrong with the Loading please hit back in a minute');
},
complete: function ()
{
$('#loading').hide();
}
});
function getChild(id, node)
{
$.ajax(
{
type: 'post',
async: true,
url: "getchilds.php",
data: {'id' : id},
dataType: "json",
cache: false,
beforeSend: function ()
{
$('#loading').show();
},
success: function(json_data)
{
$('<ul class="childContainer"></ul>').appendTo(node);
$.each(json_data, function(key, object)
{
$('<li id="node">'+object.name+'</li>').data('id', object.id).appendTo(".childContainer");
if (object.childbool == true)
{
$('li:last').addClass('childfull')
}
});
},
error: function ()
{
$('#loading').hide();
alert('Something Went Wrong with the Loading please hit back in a minute');
},
complete: function()
{
$('#loading').hide();
}
});
}
$("li.childfull, li.openchildfull").live('click',function()
{
if ($('li.childfull'))
{
var node = $(this);
var id= $(this).data('id');
$(node).html(getChild(id, node));
$(node).removeClass().addClass('openchildfull');
}
else
{
$(node).removeClass().addClass('childfull');
$(node).children().remove();
}
});
});
I think .live is killing me. I get my parents on load; when I click on one I get its children ALL pretty and well, but when I click on a child to get its children I get a very funny behavior. I get its children correctly indented but with no class="childfull" and I get an other copy of them not properly indented but with correct class.. I don't know what is going wrong... Any ideas/corrections are welcome.
P.S: You don't want me to describe to you what happens when I click on the messed up 3rd lvl childfull :P.
Instead of going through the headache of building your own tree, have a look at the jstree plugin. You can pass different formats to it, including json. It allows for complete customization and allows infinite(possible :p) child levels.