I'm relatively new to javascript, and I have a restful api I'm connecting to that returns me a json string, which I can parse properly like so:
$.ajax({ url: './php/bandwidth.php',
data: { prop_id : "1" },
type: 'post',
success: function(output) {
var json = $.parseJSON(output);
for( var i = 0 ; i < json.response.length; i++ ){
times.push (json.response[i].time);
}
}
});
Inside of the success callback the variables in the array exist. I also have times array instantiated outside the ajax call function. But outside of the ajax call the array is empty. I'm sure it's a scoping issue. Can anyone give me a way to get the data from inside the array? Does the construct $.ajax({url:... , data:... , success: function(){}}); returns callback return value?
$.ajax({ url: './php/bandwidth.php',
data: { prop_id : "1" },
type: 'post',
dataType: 'json',
success: function(output) {
times = [];
for( var i = 0 ; i < output.response.length; i++ ){
times.push (output.response[i].time);
}
},
complete: function(){
if(times.length > 0){ console.log(times); } else { console.log("times empty"); }
}
});
Related
I'm trying to make a notification system that gets data every 5 secs but I don't know why it doesn't work properly. It outputs the notification endlessly but it should get the data and compare it to the last data it stored and if the data is not the same it should append the notification(s) and when it's the same it should alert "same".
var appliedData;
setInterval(getNotifications, 5000);
function getNotifications(){
$.ajax({
type: 'GET',
url: 'includes/socialplatform/friendsys/notifications.inc.php',
dataType: "json",
async: false,
success: function(data) {
if ( appliedData != data ) {
appliedData = data;
for(i=0; i < data.length; i++){
$( ".notification-container" ).append('<div class="notification"><p>' + data[i].user + '</p></div>');
}
}else{
alert("sammee");
}
}
});
}
Objects (any non-primitive: an array is an object) will never be equal to each other unless they reference the same place in memory. When comparing, your appliedData will always be different from your data, so that condition will always fail. If the response strings can be guaranteed to be the same when they represent the same object, you can simply compare the strings, as shown below. If not, you'll have to carry out a deep comparison instead.
let lastDataStr;
setInterval(getNotifications, 5000);
function getNotifications() {
$.ajax({
type: 'GET',
url: 'includes/socialplatform/friendsys/notifications.inc.php',
dataType: "text", // change here, then parse into an object in success function
async: false,
success: function(newDataStr) {
if (newDataStr === lastDataStr) {
alert('same');
return;
}
lastDataStr = newDataStr;
const newData = JSON.parse(newDataStr);
newData.forEach(({ user }) => {
$(".notification-container").append('<div class="notification"><p>' + user + '</p></div>');
})
}
});
}
some of the resign i cant take value from ajax, where json data is comming like that
request
i wan to take value from ReviewPoint and after that manupulate some other jquery in ajax success block.
but problem is i cant take value when i trying to print value using alert box it showing "undefine"
my jquery code is
var productid = $("#productid").text();
$.ajax({
url: '/ProductService/CheckUserExistFirst.asmx/rating',
method: 'GET',
// dataType: 'json',
data: { productid: productid },
//contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data.d.ReviewPoint);
if (data.ReviewPoint < 1) {
$("#rat-1").removeClass("fa fa-star-o");
$("#rat-1").addClass("fa fa-star");
}
if (data.ReviewPoint < 2) {
$("#rat-1,#rat-2").removeClass("fa fa-star-o");
$("#rat-1,#rat-2").addClass("fa fa-star");
}
if (data.ReviewPoint < 3) {
$("#rat-1,#rat-2,#rat-3").removeClass("fa fa-star-o");
$("#rat-1,#rat-2,#rat-3").addClass("fa fa-star");
}
if (data.ReviewPoint < 4) {
$("#rat-1,#rat-2,#rat-3,#rat-4").removeClass("fa fa-star-o");
$("#rat-1,#rat-2,#rat-3,#rat-4").addClass("fa fa-star");
}
if (data.ReviewPoint < 5) {
$("#rat-1,#rat-2,#rat-3,#rat-4,#rat-5").removeClass("fa fa-star-o");
$("#rat-1,#rat-2,#rat-3,#rat-4,#rat-5").addClass("fa fa-star");
}
},
error:function(err){
alert(err);
}
})
The response is an array so you need to access it by index using array notation. There is also no d property in the response. Try this:
var reviewPoint = data[0].reviewPoint;
Also note that you can DRY up your code by giving all the #rat-N elements a common class. You can then use eq() and prevAll() to set the classes on the required elements. Try this:
success: function (data) {
var reviewPoint = data[0].reviewPoint;
$('.rat').eq(reviewPoint).prevAll('.rat').addBack().removeClass('fa-star-o').addClass('fa-star');
});
hi actually i read many topic about array and jquery and they all show example using jquery inside the hmtl script tag but what i try to learn is how to read an array sent by php throught ajax inside a js file
here is my php example
$record = array('jazz','rock', 'punk', 'soft', 'metal');
echo json_encode($record);
then here is my ajax
$.ajax({
url: "system/music_list.php",
dataType: 'json',
cache: false,
success: function(response){
// here i want to read the array and make a loop for each element
},
});
thanks if you can help me
try basic for loop with count using length This .. this should help surely.
function ajax_test()
{
$.ajax({
url: "system/music_list.php",
dataType: 'json',
cache: false,
success: function(response)
{
for (var i = 0; i < response.length; i++)
{
alert(response[i]);
}
}
});
}
Try a for loop to loop the records
$.ajax({
url: "system/music_list.php",
dataType: 'json',
cache: false,
success: function(response){
var record;
for(record in response)
{
console.log(response[record]);
});
},
});
Please use below code :
$(response).each(function(key,value){
console.log(value);
});
Here each loop of response array and value get ('jazz',rock,...etc).
try see this, clear solution for your question
https://stackoverflow.com/questions/20772417/how-to-loop-through-json-array-in-jquery
$.each : A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties. Reference documentation
$.ajax({
url: "system/music_list.php",
dataType: 'json',
cache: false,
success: function(response){
//Check if the response is in expected JSON format.
var flag = isJSON(response);
if(flag === true)
{ response = JSON.parse(response); }
//Iterate the Array using for each loop of jquery
$.each(response, function( index, value ) {
console.log( "Index : " + index + "Value : " + value );
});
} // End of success function
}); //End of Ajax
//JSON format check
function isJSON(data) {
var ret = true;
try {
JSON.parse(data);
}catch(e) {
ret = false;
}
return ret;
}
You can get array indexes and values by using .each in jQuery as:
$.ajax({
url: "system/music_list.php",
dataType: 'json',
cache: false,
success: function(response){
$.each(response, function(index,value)
{
console.log(index); // print all indexes
console.log(value); // print all values
});
},
});
<div id="dat" name="dat"></div>
<script type="text/javascript">
$.ajax({ url: "music_list.php",
dataType: 'json',
cache: false,
success:function(response) {
for( res in response) {
document.getElementById('dat').innerHTML+=response[res]+"<br/>";
}
}
});
</script>
I am fairly new to JS and AJAX, and for some reason I can not send my dynamically generated and read data via AJAX. How do I properly send an array via AJAX to PHP script?
I have tried following the instructions but I can not get the AJAX to send the data. The first try was a complete bust, the second gets error:
Uncaught TypeError: Illegal invocation
but it seems to originate from the JS-library instead of my code (though the code is most probably the reason for it!) and I do not know what to do with it.
//first thing I tried
var i = 1, j = 0, cu = [], cu2 = [];
while (i <= tilit ) {
cu[j] = document.getElementById("til_nro_"+i);
console.log(cu[j].value);
i++;
}
var dynamic_account_value = JSON.stringify(cu);
jQuery.ajax({
type: "POST",
url: 'http:mysite.php',
dataType: 'json',
data: { dynamic_account_count:tilit, db:cu , id:id, result:dynamic_account_value
}
});
//2nd thing I tried
var i = 1, j = 0, cu = [], cu2 = [];
while (i <= tilit ) {
cu[j] = document.getElementById("til_nro_"+i);
cu2.push(JSON.parse(cu[j].value));
i++;
}
var tilinrot_lisa = JSON.stringify(cu2);
jQuery.ajax({
type: "POST",
url: 'http:mysite.php',
dataType: 'json',
data: { dynamic_account_count:tilit, db:cu , id:id, result:tilinrot_lisa
}
});
First, give them something that makes selection easier, like a common class. Second, use jquery serialize
$.ajax({
url : "foo",
data : $(".bar").serialize(),
success : function(response) {}
})
Try this code snippet, Try to send just one variable then go for another & use content type.
u can use //console.log(JSON.stringify(cu)); to view what's inside.
jQuery.ajax({
type: 'post',
dataType: 'json',
data: {your_var:JSON.stringify(cu)},
contentType: "application/json"
});
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I have a question about $.ajax in javascript:
If I have a function like this:
var jQueryFunction = function()
{
var array = new Array();
...
$.ajax ({
type: "GET",
async: false,
url: TPS_URL_1,
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "tpsHandler",
success: function(json)
{
array[0] = 1;
array[1] = 2;
}
});
}
After that when I check array value, it isn't set by anything and still null.
However I do like this:
var jQueryFunction = function()
{
var array = new Array();
array[0] = 1;
array[1] = 2;
...
$.ajax ({
...
});
}
It works fine.
So why I cannot set value for array inside $.ajax?
The line $.ajax({...}) is the equivalent of
var obj = {...};
$.ajax(obj);
The statement array[0] = 1 is not something that can be placed inside a object declaration like that (ie the code var obj = {array[0]=1} is not valid), thus the code you've posted is invalid (it throws a SyntaxError)
If you want to set these array elements AFTER the ajax returns, you should use the success callback:
$.ajax({url: ...,
success: function(returnData) {
array[0] = 1;
}
});
Try with:
Simple:
var setup = {
url : 'index.php',
dataType : "json",
type : "post",
data : {
time : "now"
},
success : function(response)
{
console.log( response ) ;
}
};
$.ajax( setup );
API( ajaxSetup ):
$.ajaxSetup({
url : 'index.php',
dataType : "json",
type : "post",
success : function(response)
{
console.log( response ) ;
}
});
$.ajax({
data:{
time : "now"
}
});