Parse json and replace html - json

After submitting a form I'm directed to a blank page that shows some json data such as:
some error
{"status":0,"message":"some error message here"}
or success
{"status":1,"message":"You have been signed up!"}
I would like the contents of a span element to be replaced with the message from the json data.
span element:
<span class="ladda-label" id="notice">Get notified!</span>
My script is located after my jquery and is as follows
<script>
$(document).ready(function() {
$.ajax({
dataType: 'json',
success: function( data ) {
var prices = data.message;
$('#notice').html(data.message);
}
});
});
</script>
I'm pretty confident I'm not doing a single thing correctly here.

...be more carefull )
<script>
$.ajax('/my-data-url',{
dataType: 'json',
success: function( data ) {
var prices = data.message;
//$('#notice').text -> html( message.data !!! -> data.message);
$('#notice').html(data.message);
},
error: function() {
console.log('connection error')
}
});
</script>

Related

ASP.NET jQuery reload element on submit (Ajax POST/GET)

Using ASP.NET I'm trying to reload only a part of my webpage using jQuery instead of using "location.reload();". It's a single page application. As the user submits a form the user credits change and the new value should be updated without a full page reload. The value for credits is retrieved through an Ajax Get Call and should be updated after an Ajax Post Call. I tried using "$("#userCredits").load(?);" within the Ajax Post but can't get it right. Do I need to make a partial view to achieve this? Thanks for helping.
HTML _Layout.cshtml
<ul class="nav masthead-nav">
<li id="userCredits">
//Paragraph retrived from Ajax Get Call: "#reloadUserCredits".
</li>
<li>
<p class="user">#User.Identity.GetUserName()</p>
</li>
</ul>
JS
//Ajax POST user pack (buy pack)
$("#postform").submit(function (e) {
e.preventDefault();
var data = {
applicationUserId: $("#userId").val().trim(),
packId: $("input.activeImg").val().trim(),
}
$.ajax({
url: '/api/buypack',
type: 'POST',
dataType: 'json',
data: data,
success: function () {
document.getElementById("postform").reset();
location.reload();
},
error: function () {
}
});
});
// Ajax GET user credits (navbar userCredits)
var $credits = $('#userCredits')
$.ajax({
type: 'GET',
url: '/api/user',
success: function (credits) {
$.each(credits, function (i, user) {
$credits.append('<p id="reloadUserCredits" class="credits">Credits: ' + user.credits + '</p>');
});
}
});
As I understand... You already are getting the user credits via Ajax on page load. So you only need to do it again after he bought some more.
Have the Ajax request to /api/user in a named function. Below, I called it get_credits(). Run it on page load AND on success of the Ajax request to /api/buypack.
//Ajax POST user pack (buy pack)
$("#postform").submit(function (e) {
e.preventDefault();
var data = {
applicationUserId: $("#userId").val().trim(),
packId: $("input.activeImg").val().trim(),
}
$.ajax({
url: '/api/buypack',
type: 'POST',
dataType: 'json',
data: data,
success: function () {
document.getElementById("postform").reset();
//location.reload();
// Refresh the credits displayed on the page
get_credits();
},
error: function () {
}
});
});
// Ajax GET user credits (navbar userCredits)
var $credits = $('#userCredits')
function get_credits(){
$.ajax({
type: 'GET',
url: '/api/user',
success: function (credits) {
$.each(credits, function (i, user) {
$credits.html('<p id="reloadUserCredits" class="credits">Credits: ' + user.credits + '</p>');
});
}
});
}
// Run on page load
get_credits();

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......

autocomplete to populate all values on input focus

I have autocomplete textbox whose values are populated using ajax call which returns json data. This works fine with following code lines.
$("#searchTitle").autocomplete({
source: function (request, response) {
$.ajax({
url: "/umbraco/Surface/MyApp/StartSearch",
type: "POST", dataType: "json",
data: { term: request.term },
success: function (data) {
debugger
response($.map(data, function (item) {
debugger
return { label: item.Cat_Name };
}));
}
});
},
messages: { noResults: "", results: "" },
minLength: 0
});
But this function gets called when user type something. Now, I want that when input is focused, all the values from response should be shown in autocomplete. How can I trigger the same?
You can achieve by using search event of autocomplete on focus of input.
For example
$( "#searchTitle" ).focus(function() {
// make sure you put space between double quote
$( "#searchTitle" ).autocomplete("search", " " );
});

jquery validation onSubmit ajax post JSON response

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 (){

Jquery Autocomplete with json and using parameters

I am trying to do an autocomplete input field. Everytime a user type a letter in that field, the value of the field is sent to the server and the server answer with words that match.
var acOptions = {
source:function (request, response) {
$.ajax({
url: "index.php?option=com_fmw&view=keywords_api&controller=keywords_api&format=raw",
type: "GET", dataType: "json",
data: { expr: request.term},
success: function (data) {
response($.map(data, function (item) {
return item.value;
}))
}
})
},
minChars: 1,
dataType: 'json'
};
$( "#search_box_input" ).autocomplete(acOptions);
This is an example of data from the server:
[{"value":"Greater"},{"value":"great"},{"value":"greatly"},{"value":"Greater-Axe"}]
The previous code do the right request to the server (and the server answer right) but it does not display anything in the text field.
I tried to do the autocomplete without an explicit ajax object but then I couldn't send the current value of the field (parameter "expr" of the request) to the server:
var acOptions = {
source: "index.php?option=com_fmw&view=keywords_api&controller=keywords_api&format=raw&expr=",
minChars: 1,
dataType: 'json'
};
$( "#search_box_input" ).autocomplete(acOptions);
Thank you for your help!
You can use jQuery to pull the value of your field to add it to URL parameter string.
var acOptions = {
source: "index.php?option=com_fmw&view=keywords_api&controller=keywords_api&format=raw&expr=" + $('#ID_OF_YOUR_TEXTBOX').val(),
minChars: 1,
dataType: 'json'
};
$( "#search_box_input" ).autocomplete(acOptions);