In effect, I want to say this:
$('#results1').html($.post("videoloaderurl.php", { id: byName } ));
Obviously, the code above doesn't work.
where results1 is a div and videoloaderurl.php returns html.
You should provide success callback function for post function, which could add retrived data to the div.
$.post("videoloaderurl.php", { id: byName }, function(data) {
$('#results1').html(data);
});
$.post() is an AJAX method - meaning it is Asynchronous. You have to wait for the data to be returned and do something in the callback rather than the function returning the value.
$.post("videoloaderurl.php", { id: byName }, function(d){
$('#results1').html(d)
});
Related
I have a problem. I am learning React js and I have a template which i must edit. I need to add some ajax methods for getting and sending info. I manage to do some of those actions but now I have a problem.
I have php scripts which is getting me json_encode.
getCategories: function() {
$.ajax({
url: '#########my_url#########',
dataType: 'json',
success: function(data) {
this.setState({datas: data});
}.bind(this)
});
},
and I have this
getInitialState: function() {
return {datas: []};
},
The problem is I always get firstly the empty array and then the result. And when I try to work with it, it gets me error because it tries to map the empty array. This is the console.log before I try to play with the object.
[HMR] Waiting for update signal from WDS...
[]
[WDS] Hot Module Replacement enabled
[Object, Object, Object, Object]
How can I make it to work after the object is full?
First option: render your view on ajax call success
Second option: anticipate the case your state.datas is still empty
for example if you're working in your render function try:
{ this.state.datas ? <div> Loading </div> : <....
Above is JSX syntax
Hope it helps
EDIT:
if(this.state.datas.length == 0) {
var mycomponent =<div> Loading ... </div>;
} else {
var mycomponent = this.state.datas;
}
Basically this should work.
var data = {
'ids': $("input[name='ids\\[\\]']").map(function(){return $(this).val();}),
'price': $("input[name='price\\[\\]']").map(function(){return $(this).val();})
};
alert(data);
$.post("api/update_prices.php", {'data[]': data}, function (responseText) {
alert(responseText);
});
or...
$.post("api/update_prices.php", data, function (responseText) {
alert(responseText);
});
The alert data is outputting a Object (object). I was looking a Stackoverflow and it's still not working. alert(responseText) is never called.
Did you try specifying the content type as "application/json" in the jQuery Ajax API and then calling
JSON.stringify(data);
also, open the web developer console in Google Chrome browser and navigate to the Network tab to see what is happening during the Ajax call. i.e. what data is sent and what data is received in the Ajax Call.
Have you tried serialize? It sums up all the form data. It seems to be what you're trying to do with the data object.
$.post("api/update_prices.php", $(':input').serialize(), function (responseText) {
alert(responseText);
});
http://api.jquery.com/serialize/
Your $.post function should be like this:
$.post("api/update_prices.php", {'data[]': JSON.stringify(data)}, function (responseText) {
alert(responseText);
});
Pay attention to JSON.stringify.
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
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();
}
}
var tds = ["0", "1", "2", "3", "4", "5", "6"];
for (var i = 0; i < tds.length; i++) {
jQuery("#notification-bar").html('I am doing ' + tds[i]);
jQuery.ajax({
url: "/ajax_json_echo/",
type: "POST",
timeout: 10000,
data: tds[i],
success: function(response) {
},
error: function(x, t, m) {
}
});
} //end for
jQuery("#notification-bar").html("Done!");
/ajax_json_echo/ might take 10 seconds or even more to deal with tds.
The expected result of notification bar is
I am doing 0
I am doing 1
I am doing 2
...
Done!
The actual result I get is:
Done!
I guess it is caused by the async variable of jquery ajax is being set to true.
If it is set to false, the browser will be frozen. When it recovers, I get "Done!" only.
The browser runs JavaScript and does page rendering all on the same thread, so while JS is running no repaints will occur. This means that your entire for loop will complete and the status message will be set to "Done!" before the page gets updated.
In the case of async being true all of the Ajax requests are queued up initially and the message set to "Done!" and then the responses are processed later asynchronously. In the case of async set to false the Ajax requests are done one at a time with no further action until the response comes in. Either way the browser never gets a chance to display the "I am doing..." messages.
Rather than using a loop you can trigger each subsequent call from within the Ajax complete (or success) callback:
var tds = ["0", "1", "2", "3", "4", "5", "6"];
function doNextAjax(i) {
if (i < tds.length) {
jQuery("#notification-bar").html('I am doing ' + tds[i]);
jQuery.ajax({
url: "/ajax_json_echo/",
type: "POST",
timeout: 10000,
data: tds[i],
success: function(response) {
},
error: function(x, t, m) {
},
complete: function() {
doNextAjax(i + 1);
}
});
} else {
jQuery("#notification-bar").html("Done!");
}
}
doNextAjax(0);
Each time doNextAjax() is called it updates the status message and makes a single Ajax request and that's all. When the function exits the browser then has a chance to re-render and actually show that message. Then when the complete callback is fired it calls the function again for the next item. When there are no items left it sets the "Done!" message.
Note that using the complete callback to trigger the next Ajax call means that it will keep going even if a particular request fails. If you wanted to stop on error you could get rid of the complete handler and move the doNextAjax(i+1) into the success callback.
Generally this is what you use the success callback parameter to ajax() for - to run a function when the AJAX request completes.
http://api.jquery.com/jQuery.ajax/
If you can use HTML5 elements, use the <progress> element, this is why he's there.
Increase the progress-bar value in the success callback of each ajax request.
var progress = document.getElementById('progress');
progress.max = tds.length;
...
success: function(){
progress.value++;
}
LIVE DEMO
Here's the solution, you should take a look at jQuery deffered object
$.when($.ajax("/page1.php"), $.ajax("/page2.php")).done(function(a1, a2){
/* a1 and a2 are arguments resolved for the
page1 and page2 ajax requests, respectively */
var jqXHR = a1[2]; /* arguments are [ "success", statusText, jqXHR ] */
if ( /Whip It/.test(jqXHR.responseText) ) {
alert("First page has 'Whip It' somewhere.");
}
});
http://api.jquery.com/jQuery.when/
The response you wrote will happen. Change
jQuery("#notification-bar").html('I am doing ' + tds[i]);
jQuery("#notification-bar").html("Done!");
to
jQuery("#notification-bar").append('I am doing ' + tds[i]);
jQuery("#notification-bar").append("Done!");
and you will see result. But, behavior is not what you expect. For loop will fire up all AJAX calls, one after another. If you want to fire up next AJAX call only when the last one is finished you should use jQuery Deferred objects to manage this.
I have wrapped up an example here http://jsfiddle.net/DXYZw/2/
var tds = ["0", "1", "2", "3", "4", "5", "6"];
var sendRequest = function(ary, data) {
if (!ary.length) {
// no more calls to be made
jQuery("#notification-bar").append("Done!");
return;
}
jQuery("#notification-bar").append('I am doing ' + tds.length);
dfAJAX(ary)
.done(sendRequest)
.fail(function() {
alert("error");
});
}
var dfAJAX = function(ary) {
var dfd = new jQuery.Deferred();
var dataToSend = ary.pop();
jQuery.ajax({
url: "/ajax_json_echo/",
type: "POST",
timeout: 10000,
data: dataToSend
})
.done(function(data) {
dfd.resolve(ary, data);
})
.fail(function() {
dfd.reject();
})
return dfd.promise();
}
sendRequest(tds);