I'm retrieving a json string as below with jquery ajax and displaying it on a xhtml page
{"pID":"T1","avBal":147765035.20,"accBalance":147713417.00}
I have the jquery written like this,
$.ajax({
type : "GET",
url : '../accData.xhtml',
dataType : "json",
async : true,
cache : false,
success: function(data) {
if(data!=null){
$("#accBalance").text(data.accBalance);
$("#avBal").text(data.avBal);
}
},
error : function() {
}
});
The issue here is it displays the "avBal" as 147765035.2 and "accBalance" as 147713417 without the zero's all the zero's at the end of the values are truncated automatically. Is it a limitation in jQuery or json or something else is wrong here?
please replace your script as below:
$.ajax({
type : "GET",
url : '../accData.xhtml',
dataType : "json",
async : true,
cache : false,
success: function(data) {
if(data!=null){
//chage is here...
$("#accBalance").text(parseFloat(data.accBalance).toFixed(2));
$("#avBal").text(parseFloat(data.avBal).toFixed(2));
}
},
error : function() {
}
});
Not jQuery's or JSON's fault, but JavaScript. JavaScript is loosely typed, and 123 & 1.23 are both of the type Number. If the precision is important, treat those values as strings.
Here is a nifty function that will format the values as required:
function toFixed(value, precision) {
var power = Math.pow(10, precision || 0);
return String(Math.round(value * power) / power);
}
Related
I have a serious problem, I can't receive data sent by ajax in php. I've read many tutorial about that but it still not resolved. So if you guys have the magic solution, it'll make my day.
Here is the code, note that it is in the same file problem.php.
assocStored is an array or object, and it have the right data if I check it on jvascript
window.onload = function(e){
var assocStored = JSON.parse(localStorage.getItem("associes"));
$.ajax({
type : "POST",
data : {"problem" : assocStored},
success : function(res){
console.log("action performed successfully");
}
})
}
<div>
<h3>php</h3>
<?php
var_dump ($_POST);
if( isset($_POST['problem']) ){
foreach ($_POST['problem'] as $associe) {
echo($associe["sex"]." ".$associe["firstname"]." ".$associe["lastname"]);
}
exit;
}
?>
</div>
As my comment above, I guess your request send a GET method.
In your code, you are using type is POST but type is an alias for method. You should use type if you are using versions of jQuery prior to 1.9.0.
So you can modify your ajax to here:
$.ajax({
method: "POST",
data : { "problem" : JSON.stringify(assocStored) }, // convert to json
dataType: "json", // add type
success : function(res){
console.log("action performed successfully");
}
})
If it continues not working, add this code to ajax:
$.ajax({
method: "POST",
data : { "problem" : JSON.stringify(assocStored) }, // convert to json
dataType: "json", // add type
beforeSend: function(req) {
if (req && req.overrideMimeType) {
req.overrideMimeType("application/j-son;charset=UTF-8");
}
},
success : function(res){
console.log("action performed successfully");
}
})
I hope it works.
The MVC controller method is not being called with the following code and the issue isn't clear. $("#screeners").val() returns a list of strings:
<script>
$(document).ready(function () {
$("#submitScreeners").click(function () {
var selected = $("#screeners").val();
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/Applicant/PassScreeners',
data: "selected=" + JSON.stringify(selected),
success: function () {
$('#result').html('"PassScreeners()" successfully called.');
},
failure: function (response) {
$('#result').html(response);
}
});
});
});
</script>
Method in controller:
public void PassScreeners(List<string> selected)
{
Session["SelectedApplicants"] = selected.Select(e => Int32.Parse(e.ToString())).ToList();
}
If I understand you correctly, the "selected" parameter is being passed in as a null value. I believe this is because you are using an incorrect data format. You tell the server to expect JSON formatted data, but then pass it something more akin to a form value with '='.
Try removing the "selected=" bit from your data line and just pass the stringified list.
If that doesn't work, check the trace and post it. If the string you are posting is just comma separated or something it needs to be an array in order for the POST to work correctly.
Apologies if I've misunderstood.
I have first and last name text boxes, last name on blur triggers an ajax call to get additional data to fill in other textboxes. The call is made and I can see in the Chrome dev tool (network tab) that a json string is coming back with all the data, but I can't figure out how to populate the text fields.
ajax function:
$(function() {
$("#LastName").on('blur', function () {
var first = $("#FirstName").val();
var last = $("#LastName").val();
$.ajax({
url: '#Url.Action("SearchEmployee", "Employee")',
type: "GET",
datatype: 'json',
data: { 'firstName': first, 'lastName': last },
success: function (data) {
alert(data.ManagerFirst);
$("#ManagerFirst").val(data.ManagerFirst);
$("#ManagerLast").val(data.ManagerLast);
},
error: function () { alert("Huh? What? What did you need?.") }
});
})
})
returns something like this:
{"EmployeeId":0,"FirstName":"Bob","LastName":"Smith","EmailAddress":null,"ManagerEmail":"Boss.Man#work.org","ManagerId":null,"ManagerFirst":"Boss","ManagerLast":"Man"}
The 'alert' shows "undefined".
You may just have a typo. Try changing "datatype" to "dataType"
You are trying to alert a data member of the response string, which does not exist. Instead, you should try to convert the string to object, like this:
$(function() {
$("#LastName").on('blur', function () {
var first = $("#FirstName").val();
var last = $("#LastName").val();
$.ajax({
url: '#Url.Action("SearchEmployee", "Employee")',
type: "GET",
datatype: 'json',
data: { 'firstName': first, 'lastName': last },
success: function (data) {
//converting it to object, since further rows expect this
data = $.parseJSON(data);
alert(data.ManagerFirst);
$("#ManagerFirst").val(data.ManagerFirst);
$("#ManagerLast").val(data.ManagerLast);
},
error: function () { alert("Huh? What? What did you need?.") }
});
})
})
EDIT:
As Bryan Lewis pointed out, it was a typo. This has led to the behavior about which I have written my answer.
Turns out the problem was the server was returning an array of employee objects, so had to access it like:
data[0].ManagerFirst ... etc.
There was no way to tell that from the data I posted, so my apologies.
fyi, once I added that fix, I changed the the dataType param back to 'datatype' and it still worked fine.
I'm setting up a select2 with the following JavaScript
$j("#" + name).select2({
placeholder: "",
width:"300px",
minimumInputLength: 3,
ajax: {
url: "/MyService.asmx/ServiceMethod",
dataType: 'json',
data: function (term) {
return {
q: term // search term
};
},
results: function (data) {
alert('results');
return {results: data};
},
success: function() {
alert('success');
},
error: function () {
alert('error');
},
},
});
The method I'm calling is the following:
<WebMethod(enableSession:=True)>
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)>
Public Function ServiceMethod(q as String) As String
Dim temp As String = "[{'id':'35','text':'Drew'}]"
Return temp
End Function
I also have <ScriptService()> around the class. The enableSession is there because eventually I'm going to be running a lot of logic in the service that requires it, but for now I'm just trying to return a simple string with JSON.
I've put a breakpoint in the webservice, and I know it is being called. I know it is returning the JSON. I also know that the select2 expects "id" and "text" in the JSON return
My problem is the following: after I input 3 characters, the data function calls (I put an alert in it), the webservice breakpoint is hit, but none of the results, success, or error events fire afterwards. The select2 just spins and nothing ever happens. No javascript errors are entered in the console, and I'm at a loss about even where to look for information as to why the ajax isn't handling the returned value from the service.
Can anyone point me in the direction of at least where to look to see why this isn't working?
So I fixed this myself after getting a hint to look at the network log. The service was returning correctly, but it was returning XML, not JSON. I had to make 2 modifications and everything worked.
My working ajax:
ajax: {
url: "/MyService.asmx/ServiceMethod",
type: 'POST',
params: {
contentType: 'application/json; charset=utf-8'
},
dataType: 'json',
data: function (term, page) {
return JSON.stringify({ q: term, page_limit: 10 });
},
results: function (data) {
return {results: data};
},
},
The important changes were the type, putting the contentType in the params wrapper, and JSON.stringify-ing the data. I'm going to change what's passed and how its passed, but things are at least communicating now. Hope this helps anyone else who was looking for a similar solution.
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);