Here is my function to get the data requested from a remote server. All is fine but one thing.
function get_users_request()
{
var result = [];
var idx=0;
$.get("getUsers_actions.php",
function(data) {
for (var key in data)
{
result[idx++]=data[key];
console.log(data[key].login);
}
},
"json");
return result;
}
The output is:
hissou
hbadri
user_1
But when i try to get get_users_request() result an empty array is given [].
Since it's an asynchronous call, you need to make use of a callback when you call the function:
function get_users_request(callback)
{
$.get("getUsers_actions.php", callback,"json");
}
get_user_request(function(data){
//var result = [];
//var idx=0;
//for (var key in data)
//{
// result[idx++]=data[key];
// console.log(data[key].login);
//}
$.each(data, function(k, v){
console.log(v.login);
});
});
To understand the code above, you could simulate an ajax call using a timeout:
var myAjaxResult;
setTimeout(function(){
myAjaxResult = 1; // try to update the value
}, 1000 /* simulates a 1 second ajax call */);
console.log(myAjaxResult); //undefined
Since console.log(myAjaxResult); isn't wrapped in a callback, it will be called immediately, and thus still be undefined.
If we would have waited for at least one second, the value would be set. But instead of presuming a time when the call is completed, we can make a callback function and know exactly when its done:
function myFunc(callback){
setTimeout(function(){
callback(1 /* returns the value 1 to the callback */);
}, 1000 /* simulates a 1 second ajax call */);
}
myFunc(function(callbackData){ //call the function using
//the callback we just specified
console.log(callbackData);
});
Hope this helps! Just let me know if anything is unclear.
This is what can give the result.
function get_users_request(s)
{
var s =new Array(), idx=0;
$.ajax({
url: "getUsers_actions.php",
success: function(data){
$.each(data, function(k, v){
s[idx++] = v.login;
console.log(v.login);
})
},
dataType: "json"
});
console.log(s);
}
You should put return result; after the for loop. The return should be done AFTER the $.get call is finished. Where is it now, the return is accessed right after the $.get call STARTS
Related
Initial .ajax call in jquery:
$.ajax({
type: 'post',
url: 'items_data.php',
data: "id="+id,
dataType: 'json',
success: function(data){
if(data){
make_item_rows(data);
}else{
alert("oops nothing happened :(");
}
}
});
Sends a simple string to a php file which looks like:
header('Content-type: application/json');
require_once('db.php');
if( isset($_POST['id'])){
$id = $_POST['id'];
}else{
echo "Danger Will Robinson Danger!";
}
$items_data = $pdo_db->query ("SELECT blah blah blah with $id...");
$result_array = $items_data->fetchAll();
echo json_encode($result_array);
I am catching the $result_array just fine and passing it on to another function. I double checked that there is indeed proper values being returned as I can just echo result to my page and it displays something like the following:
[{"item_id":"230","0":"230","other_id":"700"},{"item_id":"231","0":"231","other_id":"701"},{"item_id":"232","0":"232","other_id":"702"}]
I am having trouble figuring out how to iterate through the results so I can inject values into a table I have in my HTML. Here is what I have for my function:
function make_item_rows(result_array){
var string_buffer = "";
$.each(jQuery.parseJSON(result_array), function(index, value){
string_buffer += value.item_id; //adding many more eventually
$(string_buffer).appendTo('#items_container');
string_buffer = ""; //reset buffer after writing
});
}
I also tried putting an alert in the $.each function to make sure it was firing 3 times, which it was. However no data comes out of my code. Have tried some other methods as well with no luck.
UPDATE: I changed my code to include the parseJSON, no dice. Got an unexpected token error in my jquery file (right when it attempts to use native json parser). Tried adding the json header to no avail, same error. jquery version 1.9.1. Code as it is now should be reflected above.
Set the dataType:"JSON" and callback in your ajax call.
For example:
$.ajax({
url: "yourphp.php?id="+yourid,
dataType: "JSON",
success: function(json){
//here inside json variable you've the json returned by your PHP
for(var i=0;i<json.length;i++){
$('#items_container').append(json[i].item_id)
}
}
})
Please also consider in your PHP set the JSON content-type. header('Content-type: application/json');
function make_item_rows(result_array){
var string_buffer = "";
var parsed_array=JSON.parse(result_array);
$.each(parsed_array, function(){
string_buffer += parsed_array.item_id;
$(string_buffer).appendTo('#items_container');
string_buffer = "";
});
}
You need to parse it with jQuery.parseJSON
function make_item_rows(result_array){
var string_buffer = "";
$.each(jQuery.parseJSON(result_array), function(index, value){
string_buffer = value.item_id;
$(string_buffer).appendTo('#items_container');
});
}
Try this.
function make_item_rows(result_array){
var string_buffer = "";
$.each(result_array, function(index, value){
value = jQuery.parseJSON(value);
string_buffer += value.item_id;
$(string_buffer).appendTo('#items_container');
string_buffer = "";
});
}
Assuming you already parsed the json response and you have the array. I think the problem is you need to pass a callback to $.each that takes and index and an element param
function make_item_rows(result_array){
$.each(result_array, function(index, element){
document.getElementById("a").innerHTML+=element.item_id;
});
}
(Slightly modified) DEMO
for starters within the $.each you need to access the properties of the instance of object contained within result_array, not result_array itself.
var string_buffer = "";
$.each(result_array, function(index, object){
/* instance is "object"*/
alert( object.item_id);
});
Not entirely sure what you are expecting from this line: $(string_buffer).appendTo('#items_container');
$(string_buffer) does not create a valid jQuery selector since nothing within string_buffer has a prefix for class, tagname or ID, and values from json don't either
If just want the string value of the item_id appended :
$('#items_container').append( object.item_id+'<br/>');
If you are receiving this using jQuery AJAX methods you don't need to use $.parseJSON as other answers suggest, it will already be done for you internally provided you are setting correct dataType for AJAX
I am using immediately invoked functions pattern, but this is not passing the id
1.When the user clicks on $user, id is passed and the chat window appears
echo "<div class='boxbottom'><a href='#' onclick=chat_com_one($id);> >$user</a><br></div>";
2.Function chatcom_load_one keep checking, if there is any message from the id passed to chatcom_load_one function.
But the problem is that onclick function do passes the id but immediately invoked function did not pass the id to the post function.
Also sending the message is slow?
Please help or suggest any alternate approach, I think error is in the chat_load_one pattern.
function chat_com_one(id) {
$('#chatcom').show('fast');
(function chatcom_load_one(id) {
$.post('sendchat2.php', {
option: 'chatcom_load_one',
tocom: id
}, function (data) {
$('#chatcom #commid #commidwin').html(data);
setTimeout(chatcom_load_one(id), 1000);
});
}());
$('#chatcom_send').click(function () {
var text = document.getElementById('chatcom_text').value;
$.post('sendchat2.php', {
option: 'chat_com_send_one',
text: text,
tocom: id
}, f
function (data) {
document.getElementById('chatcom_text').value = '';
});
});
}
send function on my server
if($_REQUEST['option']=='chat_com_send_one'){
$session=new $session;
$text=mysqli_real_escape_string($db3->connection,$_POST['text']);
$tocom=mysqli_real_escape_string($db3->connection,$_POST['tocom']);
$sql=mysqli_query($db3->connection,"INSERT INTO chat_com(fro,tocom,mesg,time) VALUES ('$session->userid','$tocom','$text',CURRENT_TIMESTAMP)");
}
First off, I notice two problems:
You have a syntax error in the parameter list to $.post
You probably don't want to do this: setTimeout(chatcom_load_one(id), 1000);
Here's an updated version of your code with these errors fixed:
function chat_com_one(id) {
$('#chatcom').show('fast');
(function chatcom_load_one(id) {
$.post('sendchat2.php', {
option: 'chatcom_load_one',
tocom: id
}, function (data) {
$('#chatcom #commid #commidwin').html(data);
setTimeout(function () {
chatcom_load_one(id);
}, 1000);
});
}());
$('#chatcom_send').click(function () {
var text = document.getElementById('chatcom_text').value;
$.post('sendchat2.php', {
option: 'chat_com_send_one',
text: text,
tocom: id
},
function (data) {
document.getElementById('chatcom_text').value = '';
});
});
}
Also, since you're using jQuery, you can simplify document.getElementById.... Another updated version (with some more changes to make it more readable):
function chat_com_one(id) {
$('#chatcom').show('fast');
(function chatcom_load_one(id) {
$.post('sendchat2.php', {
option: 'chatcom_load_one',
tocom: id
}, function (data) {
$('#commidwin').html(data);
setTimeout(function () {
chatcom_load_one(id);
}, 1000);
});
}(id));
$('#chatcom_send').click(function () {
var text = $('#chatcom_text').val();
$.post('sendchat2.php', {
option: 'chat_com_send_one',
text: text,
tocom: id
},
function (data) {
$('#chatcom_text').val('');
});
});
}
These are just a few cleanups, there may be others.
Edit:
Added devnull69's insight to my final updated code. Hopefully it's useful (accept his answer if this was the problem).
Edit: Other notes
Why are you doing $.post in chatcom_load_one? It would make much more sense as a $.get, and the query parameters would still be sent. It's not really a problem per se, but it's bad style. This should probably be in a file called getchat.php or something instead of doing what I expect is looking for the text parameter.
Also, I don't know the implementation of sendchat2.php, but you should probably reduce the timeout. Try something like 250ms or so. That's not going to overload the server and it'll improve response time.
In addition to the previously mentioned problems you invoke the immediately executed function without any parameter. You will have to add the (id) parameter to the function call in order to hand over the id element to its local copy inside the function.
(function chatcom_load_one(id) {
...
}(id));
Turning off asynchronous requests in jQuery fixed the issue.
I have the following Javascript & AJAX request (using jQuery) in my page:
"use strict";
var hsArea, counter, hotspots, count;
counter = 4;
count = 0;
hotspots = {};
function fetchHotspotList() {
$.getJSON ('/alpha/engine/hotspots/gethotspot.php', {'type' : 'list'}, function(json) {
hotspots = json;
});
}
function displayHotspot(type, id, number) {
$.ajax({
url: '/alpha/engine/hotspots/gethotspot.php',
dataType: 'json',
data: {'type' : type, 'id' : id},
success: function(json) {
console.log(json);
var hotspot, extract;
extract = json.content;
extract = extract.replace(/<(?:.|\n)*?>/gm, '');
extract = extract.substring(0, 97);
extract = extract + "...";
json.content = extract;
hotspot = document.createElement("div");
hsArea.append(hotspot);
hotspot.setAttribute('class','hotspot');
hotspot.setAttribute('id','hotspot' + number);
$(hotspot).css('position', 'absolute');
$(hotspot).css('top', number * 100 + 100);
$(hotspot).css('left', number * 100 + 110);
hotspot.innerHTML = "<h1>"+ json.title + "</h1><p>" + json.content + "</p>";
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus, errorThrown);
}
});
}
function listHotspots() {
for(count = 0; count < counter; count++) {
(function(count) {
displayHotspot('scribble',hotspots[count], count);
count = count + 1;
})(count);
}
}
function loadHotspots() {
fetchHotspotList();
listHotspots();
}
$(document).ready(function() {
hsArea = $("#hotspotArea");
fetchHotspotList();
listHotspots();
});
(Sorry the formatting is a bit off!) - Now, the $(document).ready() function assigns the hsArea variable as it should, however, a combination of fetchHotspotList() and listHotspots() returns:
Uncaught TypeError: Cannot call method 'replace' of null
However, if in the Google Chrome Javascript console, I run:
loadHotspots();
it fetches the data from the AJAX request and displays it properly on the page. At first I thought the problem was that I Wasn't using the $(document).ready() handler, but adding it hasn't fixed it. Neither has using an onload handler inside of the body tag.
Any help would be greatly appreciated.
Regards,
Ben.
It's probably due to the fact that your listHotSpots function is called before fetchHotSpots returns (since it's an async call).
You're better off chaining the execution of listHotSpots to the completion of fetchHotSpots, like so:
function fetchHotspotList() {
$.getJSON ('/alpha/engine/hotspots/gethotspot.php', {'type' : 'list'}, function(json) {
hotspots = json;
listHotSpots();
});
}
You may be better off modifying listHotSpots to take the json data returned from your AJAX call. Hope this helps!
I'm having trouble figuring out how to display some return JSON objects.
My script works like this:
I'm making an ajax call, sending some params to a CodeIgniter Controller where I'm processing it with a model, making some queries towards an database and then returning the json_encoded rows to the ajax callback function. This works great btw.
Here is what I want to do now and here its where I'm stuck. I want the new JSON objects (contains database rows) to "replace" the old rows in a html table. So I want it to update the table depending on the params I'm passing but only in the tbody mind.
I'm new at jquery so I've tried i few things. I've tried iterate trough the json data and use the $.html(string) function but i guess this replace everything and it will eventually just display the last object(Am i right?).
So I wonder how in a general sense I would do this?
$.ajax({
type: 'GET',
url: 'someSite.com/someEndpoint'
data: xyz.
success: function( response ) {
//lets say you have an object like this: object = { data: { ... } }
var html = '';
for(var i = 0; i<response.data.length; i++) {
html += '<tr><td>'+response.data[i].title+'</td></tr>';
}
$('#someTable tbody').html(html);
}
});
You don't have to return JSON objects in an AJAX request. Try setting the data_type config setting for the $.ajax call to "html" (or leave it blank--jQuery is really good about figuring it out from the response data).
I usually factor out the <tbody>...</tbody> portion of a view to its own view partial. Then, the "original" page load can use it, and so can an updating AJAX call.
The only asterisk to this is if you need some sort of object-oriented response along with the HTML. I would usually do something like this:
{
"stat": "ok",
"payload": "<tr><td>row1</td></tr><tr><td>row2</td></tr>"
}
And then in the ajax success function:
$.post('/controller/action', { some: 'data' }, function(response) {
$('#my_table tbody').append(response.payload);
}, 'json');
What are the params your passing in?
for example you might use a select or input field to trigger an ajax call and pass its value as the param.
var tableObj = {
var init : function(){
//check that your selectors id exists, then call it
this.foo();
},
foo : function(){
var requestAjax = function(param){
var data = {param : param}
$.ajax({
data : data,
success : function(callback){
console.log(callback);//debug it
$("tbody").empty();//remove existing data
for(var i =0; i < callback.data.length; i++){}//run a loop on the data an build tbody contents
$("tbody").append(someElements);//append new data
}
});
}
//trigger event for bar
$("#bar").keyup(function(){
requestAjax($(this).val());
});
}
}
$(function(){
tableObj.init();
})
Your php method
public function my_method(){
if($this->input->is_ajax_request())
{
//change the output, no view
$json = array(
'status' => 'ok',
'data' => $object
);
$this->output
->set_content_type('application/json')
->set_output(json_encode($json));
}
else
{
show_404();
}
}
The JS
SWFlocation = "open-flash-chart.swf";
getMyData = function()
{
$.post(
myJsURL,
{
passedval: 1234
},
function (returned_json) {
return returned_json;
},
"json"
);
}
swfobject.embedSWF(SWFlocation, "myChartDiv", "650", "200", "9.0.0", "", {"get-data":"getMyData"} );
Using firebug, if I hardcode the returned JSON, the chart works fine. But when I request the data as above - i.e. after the page has loaded, I get a 2032 error.
The getMyData method actually requests data from a PHP script that in turn requests data from and extrnal API (a big one like flickr) so there can be a few seconds delay if the results are not currently cached by us. Maybe I'm going about this the wrong way?
You have to put the swfobject.embedSWF() into the ajax callback.
like this:
SWFlocation = "open-flash-chart.swf";
init_chart = function()
{
$.post(
myJsURL,
{
passedval: 1234
},
function (returned_json) {
swfobject.embedSWF(SWFlocation, "myChartDiv", "650", "200", "9.0.0", "", {"get-data":returned_json} );
},
"json"
);
}
init_chart();
just use $.ajaxSetup({async : false}); before you call $.post();
example
function ajaxchart() {
$.ajaxSetup({async : false});
var chart = '';
var url = "data.php";
var data = '';
var callback = function(resp) {
chart = resp;
};
$.post(url, data, callback, 'text');
return chart;
}
$(function() {
$("#test").click(function() {
swfobject.embedSWF("open-flash-chart.swf", "my_chart", "350", "200", "9.0.0", "expressInstall.swf", {"get-data":"ajaxchart"});
});
});
Just a guess as I don't use Open Flash Chart but since you're making an async ajax call your getMyData function is not actually returning the json value (the callback function you defined is).
Try preloading (maybe make a synchronous ajax call before the swf embed?) the data and storing it in a var, then have your getMyData function simply return that var.
In Javascript, declair a variable flashvars and a var data like this:
var flashvars = {};
var data;
Also, make sure that you have this function, which is automatically called by swfobject.embedSWF:
function open_flash_chart_data(){
return JSON.stringify(data);
}
Now go to your AJAX-function and change your AJAX-Success-call like this:
success: function(returned_json){
// we need to set both
// data and flashvars.ofc
data=returned_json;
flashvars.ofc = returned_json;
swfobject.embedSWF(SWFlocation, "myChartDiv", "650", "200", "9.0.0", "",flashvars);
I had a similar problem, and it was quite hard to debug that you need both vars data and flashvars in the success callback. If these variables (or function open_flash_chart_data() ) are missing, you'll get Error 2032.