Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
167
rated 0 times [  174] [ 7]  / answers: 1 / hits: 91609  / 11 Years ago, fri, october 25, 2013, 12:00:00

I am working on a Stock Exchange jQuery fix for a website.



EDIT: It updates a ID/CLASS or input value on the webpage depending on the value returned.



index.php:



<!doctype html>





<script src=http://code.jquery.com/jquery-1.9.1.js></script>

<meta charset=utf-8>
<title>load demo</title>
<script type=text/javascript>
$(document).ready(function() {
$.ajax({
url: '/datacall/demo.json',
dataType: 'json',
success: function( resp ) {
$( '#div' ).val( resp.currency[0].amount );
},
error: function( req, status, err ) {
console.log( 'Something went wrong', status, err );
}
});
var end = parseInt($('#value').val());
var newend = parseInt($('#div').val());
var result = $( end * newend );
$('#clickme').click(function() {
$('#new').val( result );
});
});
</script>





<div>

<input type=hidden value=2500 id=value />

<input type=hidden value= id=div>

<input type=text id=new value= readonly/>

<input type=button value=Change id=clickme />

</div>





Currently it is returning:



[object Object]


I have also tried returning it to a div with .text()



demo.json:



    { currency : [
{
name : South Africa,
code : ZAR,
amount : 0.14
},
{
name : America,
code : USD,
amount : 0.64
},
{
name : Europe,
code : GBP,
amount : 1.29
}
] }


Please can someone tell me what I did wrong.



Thanks in advance!


More From » jquery

 Answers
53

You can do this:



// Create some global variables
var end = parseInt($('#value').val(), 10);
var newend = 0;
var result = 0;

$.ajax({
url: '/datacall/demo.json',
dataType: 'json',
success: function (resp) {

// Check the values in console
console.log(resp.currency[0].amount);
console.log(resp.d.currency[0].amount);

$('#div').val(resp.currency[0].amount);
newend = parseInt(resp.currency[0].amount, 10);
result = end * newend;

// No need to create a new jQuery object using $()
// result = $( end * newend );
},
error: function (req, status, err) {
console.log('Something went wrong', status, err);
}
});

$('#clickme').click(function () {
$('#new').val(result);
});


So the main issues here is:-




  • You need to do all the result logic in the ajax success callback, as ajax is asynchronous and you always get the empty values for the end & newend variables.

  • No need to do this result = $( end * newend ); as it creates a new jQuery object instance and hence you are getting [object Object]


[#74739] Thursday, October 24, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mariselas

Total Points: 711
Total Questions: 117
Total Answers: 110

Location: Burkina Faso
Member since Thu, Dec 23, 2021
2 Years ago
;