I have recently posted another question which straight away users pointed me in the right direction.
$.ajax({
type: 'POST',
url: './',
data: 'token=' + token + '&re=8',
cache: false,
timeout: 5000,
success: function(html) {
auth(html);
var JSON_array = eval(html);
alert(JSON_array[0].username);
}
});
this returns the data correctly but I want to perform a kind of 'foreach'. the array contains data about multiple incoming and outgoing Instant Messages. So if a user is talking to more than one person at a time i need to loop through. the array's structure is as follows.
Array(
[0] => Array
(
[username] => Emmalene
[contents] =>
<ul><li class="name">ACTwebDesigns</li><li class="speech">helllllllo</li></ul>
<ul><li class="name">ACTwebDesigns</li><li class="speech">sds</li></ul>
<ul><li class="name">ACTwebDesigns</li><li class="speech">Sponge</li><li class="speech">dick</li></ul>
<ul><li class="name">ACTwebDesigns</li><li class="speech">arghh</li></ul>
)
)
Any help very much appreciated.
Well since you are using jQuery already you could use the each function:
$.ajax({
type: 'POST', url: './', data: 'token=' + token + '&re=8', cache: false, timeout: 5000,
success: function(html){
auth(html);
var JSON_array = eval(html);
$.each(JSON_array, function(index, data) {
$('someelement').append(data.contents);
});
}
});
Instead of evaluating the HTML, you can even specify JSON as return type...
Iteration is easy when using $.each:
$.ajax({
type: "POST",
data: ...,
url: url,
dataType: "json",
success: function(data) {
$.each(data, function(i, item){
// do something with every item in data
// you can reference items in data via
// data.fieldName
});
}
});
But a for ... in loop isn't much harder:
$.ajax({
...,
dataType: "json",
success: function(data) {
var fields = data.fieldName;
var value;
for (value in fields) {
// do something with value
}
}
});
Just to clarify, As I've read many helpful hints and answers and only this one worked for me:
$.ajax({
type: 'POST', url: './', data: 'token=' + token + '&re=8', cache: false, timeout: 5000, datatype: 'json',
success: function(html){
auth(html);
var JSON_array = eval(html);
$.each(JSON_array, function(index, data) {
var talk_to = JSON_array.username;
var contents_to_update = JSON_array.contents;
});
}
});
this which made work:
1) use of eval.
2) datatype: 'json'
3) use of jquery's $.each function
Related
New to Web development and multiple scripting languages and how they mesh together...
I'm looking to return the entire SQL table (or a subset of it) from PHP and iterate through the values in JS and can't quite get it to work any help is appreciated.
In PHP encoding the array like this.
//get SQL data
$return_arr[] = array("id" => $id, "otherinfo" => $otherinfo);
echo json_encode($return_arr);
The ajax code I have looks like this but is where I'm getting tripped up...
jQuery.ajax({
type: "POST",
url: 'example.php',
type: 'POST',
data: { i: i },
dataType: "json",
success: function(response)
{
for(var i=0; i<response.length; i++)
{
var info = response[i].otherinfo;
var title = document.createElement("div");
var titletext = document.createTextNode(titledb);
title.appendChild(info);
}
}
)}
Thanks
I think its a syntax mistake.
jQuery.ajax({
url: 'example.php',
type: 'POST',
data: { i: '' },
dataType: "json",
success: function(response)
{
// code here
}
}) // <--- here
I have an API I'm trying to query which requires an initial request to generate the report, it returns a report ID and then in 5 seconds you can pull it from that report ID.
This is what I have which works perfectly and returns the reportID:
$(document).ready(function(){
$("#r2").click(function(){
$.ajax({
url: "report.php",
dataType: 'json',
data: {
type: 'queue',
ref: 2
},
success: function(result){
console.log(result.reportID);
}});
});
});
It returns this:
{"reportID":1876222901}
I'm trying to make it call another ajax call on the back of the first one to collect the report using the reportID as the data varaible "ref". So for example, the second ajax query should have ref: 1876222901
$(document).ready(function(){
$("#r2").click(function(){
$('#loading').show();
$.ajax({
url: "report.php",
dataType: 'json',
data: {
type: 'queue',
ref: 2
},
success: function(result){
console.log(result);
$.ajax({
url: "report.php",
dataType: 'json',
data: {
type: 'get',
ref: result.reportID
},
success: function(result){
console.log(result);
}
});
}});
});
});
What I am stuck with is the way I am passing the variable from the result of the first ajax call to the second. It doesn't seem to make it there. How should I send my report ID 1876222901 into my second ajax call please?
You can do this without jQuery just using browser built-in DOM APIs and the fetch API
const r2 = document.getElementById('r2')
const loading = document.getElementById('loading')
const handleAsJson = response => response.json()
const fetchRef = ({reportId}) =>
fetch(`report.php?type=get&ref=${reportId}`)
document.onready = () => {
r2.addEventListener('click', () => {
loading.show();
// you don't have to interpolate here, but in case these
// values are variable...
fetch(`report.php?type=${'queue'}&ref=${2}`)
.then(handleAsJson)
.then(fetchRef)
.then(handleAsJson)
.then(console.log)
})
}
The solution is instead of writing
ref: result.reportID
You have to write it like this
ref: result.reportID.reportID
Because as your said, the first time you use console.log(result.reportID) the result is {"reportID":1876222901}. Which means you have to chaining dot notation twice to be able to reach the value 1876222901 in the next ajax call.
To be clear:
$(document).ready(function(){
$("#r2").click(function(){
$('#loading').show();
$.ajax({
url: "report.php",
dataType: 'json',
data: {
type: 'queue',
ref: 2
},
success: function(result){
console.log(result); // as you said, console.log(result.reportID) return {"reportID":1876222901}
$.ajax({
url: "report.php",
dataType: 'json',
data: {
type: 'get',
ref: result.reportID //which means, this line would be => ref: {"reportID":1876222901}
// we will correct it like this => ref: result.reportID.reportID
// then we properly get => ref:1876222901
},
success: function(result){
console.log(result);
}
});
}});
});
});
Hopefully it fixes your error.
I think you can try to make another function for calling after your first ajax like
$(document).ready(function(){
$("#r2").click(function(){
$.ajax({
url: "report.php",
dataType: 'json',
data: {
type: 'queue',
ref: 2
},
success: function(result){
console.log(result.reportID);
callSecondAjax(result.reportID)
}});
});
});
now make that function like
function callSecondAjax(reportId){
// do some stuff
}
The way I'm trying to perform this action is like this:
var postPlaylistAjax = $.ajax({
type: 'delete',
url: 'http://api.deezer.com/user/me/playlists?request_method=delete&
access_token='+
encodeURIComponent(deezerAccessToken)+'&playlist_id=' +
encodeURIComponent(playlistId) + '&output=jsonp',
dataType: 'jsonp',
success: function() {
alert('Deleted');
},
error: ajaxError,
});
(When I try it in web the result is true but it doesn't delete the playlist).
Since the API description for deleting a playlist is the following
request_method = delete
https://api.deezer.com/playlist/{playlist_id}
I'm getting trouble to execute it in javascript
solved it:
function deleteDeezerPlaylist(playlistId) {
var postPlaylistAjax = $.ajax({
type: 'post',
url: 'http://api.deezer.com/playlist/'+encodeURIComponent(playlistId)+'?request_method=DELETE&access_token='+encodeURIComponent(deezerAccessToken)+'&output=jsonp',
dataType: 'jsonp',
error: ajaxError,
});
return postPlaylistAjax.then(function (response) {
return response.id;
});
}
The code looks like:
var jsonUrl = url +"&callback=?";
// $("#getJSON").click(function(){
$.getJSON(
jsonUrl,
{
dataType: "JSONP"
},
function(json){ var items = [];
var items = JSON.parse(json);
alert(items);
$("#result").html("<h3>" + result + "</h3>");
}
);
also tried
$.ajax({
type: 'GET',
url: url,
key: $('#access_token'),
dataType: 'jsonp',
success: function(data){ $('.result').html(data);
processData: false,
alert(jQuery.data( document.access_token ));
alert(data[0].text);},
error: function() {
console.log('Uh Oh!'); },
jsonp:'onJSONPLoad'
});
Essentially if I'm in Firebug and look at the net objects I see the status 200
If I click on the JSON tab I can see my access_token, but how do I extract it from there so I can use for API calls?
var jsonUrl = url +"&callback=?";
var access_token;
$("#getJSON").click(function() {
$.getJSON(jsonUrl, { dataType: "JSONP" }, function(json){
...
access_token = json.access_token;
...
});
});
// do something with your access_token ?
Did i understand your question right? You can assign the the access_token to a variable and then do what you want with it in your code, can't you?
$.ajax({
dataType: 'jsonp',
jsonp: 'callback',
url: url,
success: function (json) {
console.log(json.access_token);
}
});
i am currenty using jquery plugin to read a data file (data.html)
data.html has below format
[10,20,30,40,50]
my jquery data request and the javascript to return values is below
function test(){
var result=$.ajax({
url:'data.html',
type:'get',
dataType:'text',
async:false,
cache:false
}).responseText
return result;};
var my=test();
alert(my[0])
i want to get these values in the array format i.e i want my[0] to be value 10, but instead i get "[".
If i use eval function
my=eval(test());
i can get 10, but is there any other better way to store the returned ajax calls into an array instead of string?
Thanks
i tried the below answer and i am bit puzzled, the follow code results in myArray is null (in firebug), but i put async:false then it works. why do i need async:false to store the values into array ? (http://stackoverflow.com/questions/133310/how-can-i-get-jquery-to-perform-a-synchronous-rather-than-asynchronous-ajax-req)
jQuery.extend({getValues: function(url) {
var result = null;
$.ajax({
url: url,
type: 'get',
dataType: 'json',
cache: false,
success: function(data) {result = data;}
});
return result;}});
myArray=$.getValues("data.html");
alert(myArray[1]);
You don't need eval. Just indicate the proper dataType: 'json':
function test() {
return $.ajax({
url: 'data.html',
type: 'get',
dataType: 'json',
async: false,
cache: false
}).responseText;
}
var my = test();
alert(my[0]);
or even better do it asynchronously:
function test() {
$.ajax({
url: 'data.html',
type: 'get',
dataType: 'json',
cache: false,
success: function(result) {
alert(result[0]);
}
});
}
test();
I think jquery $.getScript('data.html',function(){alert("success"+$(this).text())} might be simpler. I have not had time to try it so if I'm on right track, improve this answer, if not I'm happy to learn now...