If I have a function like this, i pass in a variable of movieid.
function getFilmDetails(movieid) {
var filmDetails = 0;
$.ajax({
dataType: "json",
type: 'get',
mimeType: "textPlain",
url: 'http://api.themoviedb.org/3/movie/' + movieid,
async: false,
success: function(result){
if(result.popularity > 10000) {
result.popularity = 10000;
}
if(result.popularity < 0.1) {
result.popularity = 0.1;
}
filmDetails = result;
}
});
return filmDetails;
}
I'm calling over 100 films details through this function and as you can imagine, it takes forever to load the page by doing it this way. I need to easily access the values in the JSON for each film. For example:
alert(getFilmDetails(12345).description);
alert(getFilmDetails(65432).popularity);
alert(getFilmDetails(12345).tagline);
Is there a better way to do this?
// receive a callback------------v
function getFilmDetails(movieid, callback) {
var filmDetails = 0;
$.ajax({
dataType: "json",
type: 'get',
mimeType: "textPlain",
url: 'http://api.themoviedb.org/3/movie/' + movieid,
// async: false, // YUCK! Commented out
success: function(result){
if(result.popularity > 10000) {
result.popularity = 10000;
}
if(result.popularity < 0.1) {
result.popularity = 0.1;
}
callback(result) // invoke your callback
});
return filmDetails;
}
// make a callback
function workWithData(data) {
alert(data.description);
}
// pass the callback
getFilmDetails(12345, workWithData);
Related
what am I missing? I want to get a variable which is incremented in JavaScript and pass it to PHP via AJAX. Maybe you can help me with my code?
function increase()
{
var k=1;
k++;
$.ajax({
type: "POST",
url: 'inc/functions.php',
data: ({page:k}),
success: function(response) {
content.html(response);
}
});
}
function decrease()
{
var k=1;
k--;
$.ajax({
type: "POST",
url: 'inc/functions.php',
data: ({page:k}),
success: function(response) {
content.html(response);
}
});
}
This function should be triggered when I am pressing the button on an "onclick" event.
This variable which is "k" should be passed to inc/functions.php
$page = $_POST['page'];
echo $temp;
What am I doing wrong?
I need the variable because for use in the following MySQL statement.
$sql_tbl_questions = "SELECT * FROM `questions` where istAktiv='1' && dimension=$page";
The idea is : the user presses "next" then the JS is incrementing the variable by 1 passing it to my function where the "table" is getting to the next "site".
your increment variable should be outside the function, otherwise k is always 2
var ki = kd = 1;
function increase()
{
ki++;
$.ajax({
type: "POST",
url: 'inc/functions.php',
data: {'page':ki},
success: function(response) {
content.html(response);
}
});
}
function decrease()
{
kd--;
$.ajax({
type: "POST",
url: 'inc/functions.php',
data: {'page':kd},
success: function(response) {
content.html(response);
}
});
}
Try the below snippet for increment
var k = 1
function increase() {
var dataForAjaxCall = { page: k++ };
$.ajax({
type: "POST",
url: 'inc/functions.php',
data: dataForAjaxCall,
success: function(response) {
content.html(response);
}
});
}
Similarly you can write for decrement also.
NB: Make sure you initialize the decrement counter variable outside of the function like given above
I have multiple values, I am trying pass all values in url to controller class at one time.
But last value passed in url.
function submitFormData(formData) {
var x = [];
for(var i = 0;i < formData.length ;i++ ){
alert(i);
x = [];
x.push(formData[i].name);
x.push(formData[i].email);
x.push(formData[i].message);
}
var url= '/userrecords?x='+x;
alert(url);
$.ajax({
type: 'POST',
data: formData,
cache: false,
processData: false,
contentType: false,
beforeSend: beforeSendHandler,
url: url,
success: function(result){
if(result.success == true) {
$('.alert-success').show();
$('.alert-danger').hide();
$("#successmsg").html(result.msg);
setTimeout(function() {
$(".alert-success").alert('close');
}, 10000);
} else {
$('.alert-danger').show();
$('.alert-success').hide();
$("#error").html(result.msg);
setTimeout(function() {
$(".alert-danger").alert('close');
}, 10000);
}
}
});
}
controller class
#RequestMapping(value = "/userrecords")
public #ResponseBody StatusResponse saveList(#RequestParam(required = false) String x,Model model)
throws ParseException, SQLIntegrityConstraintViolationException {
//read all values here
}
What is wrong in my code. And how to read all values in controller.
Convert your array output in JSON and send it to using AJAX and also you have to define content type is JSON.
you can also use jquery ajax it is very simple for request response.
$.ajax({
type: "POST",
dataType: 'json',
url:"URL here",
success: function(data) // response
{}
});
I think you should post your formdata as ajax data as below.
Pass your x veriable as a ajax data.
function submitFormData(formData) {
var x = [];
for(var i = 0;i < formData.length ;i++ ){
alert(i);
x.push(formData[i].name);
x.push(formData[i].email);
x.push(formData[i].message);
}
var url= '/userrecords';
alert(url);
$.ajax({
type: 'POST',
data: x,
cache: false,
processData: false,
contentType: false,
beforeSend: beforeSendHandler,
url: url,
success: function(result){
if(result.success == true) {
$('.alert-success').show();
$('.alert-danger').hide();
$("#successmsg").html(result.msg);
setTimeout(function() {
$(".alert-success").alert('close');
}, 10000);
} else {
$('.alert-danger').show();
$('.alert-success').hide();
$("#error").html(result.msg);
setTimeout(function() {
$(".alert-danger").alert('close');
}, 10000);
}
}
});
}
I am loading 2 XML documents that both run functions on success, although the function for the 2nd XML document is dependant on the 1st being complete.
If I have async:true:
1st XML
function XmlDataTypes() {
var result = null;
var scriptUrl = "http://domain.com/xml/test.XmlDataTypes?AccountId=" + AccountId;
$.ajax(
{
url: scriptUrl,
type: 'get',
dataType: 'xml',
async: true,
success: function (data) {
//create array to be used in second XML
for (var i = 0; i < xmlRows.length; i++) {
var dataType = xmlRows[i];
var dataTypeId = nodeValue(dataType.getElementsByTagName("DataTypeId")[0]);
var dataTypeName = nodeValue(dataType.getElementsByTagName("DataTypeName")[0]);
dataTypeArray.push({ dataTypeId: dataTypeId, dataTypeName: dataTypeName, position: i, markerArray: [] });
}
},
error: function onXmlError() {
alert("An Error has occurred.");
}
});
return result;
}
2nd XML
function XmlAmenityData() {
var result = null;
var scriptUrl = "http://domain.com/xml/test.XmlAmenityData?AccountId=" + AccountId;
$.ajax(
{
url: scriptUrl,
type: 'get',
dataType: 'xml',
async: true,
success: function (data) {
//store this info in markerArray in dataTypeArray
},
error: function onXmlError() {
alert("An Error has occurred.");
}
});
return result;
}
The XML data can loaded in a random order so the function for the second document will error if the 1st hasn't completed.
If I set:
async: false
It works correctly but I get a warning:
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience.
Is there a way around this without using:
async: false
Since the 2nd xml is dependent on the 1st, you can define a callback on success.
Also since ajax is async, you must assign the result when the callback is called. You can define a variable ourside of your function (in this case an array) and put the data there.
var result = [];
function XmlDataTypes(url, accountId, callback) {
var scriptUrl = url + accountId;
$.ajax({
url: scriptUrl,
type: 'get',
dataType: 'xml',
async: true,
success: function (data) {
// do something
result.push(data);
if(typeof callback == 'function') {
callback();
}
},
error: function onXmlError() {
alert("An Error has occurred.");
}
});
}
function doSomething() {
// Do something to store this info in markerArray in dataTypeArray
// XmlAmenityData is in results var.
}
And you can use it like so
var _callback = XmlDataTypes("http://domain.com/xml/test.XmlAmenityData?AccountId=", "1234", doSomething);
XmlDataTypes("http://domain.com/xml/test.XmlDataTypes?AccountId=", "1234", _callback);
EDIT: Updated script based on given scenario.
You could try to return the $.ajax as a promise:
function XmlDataTypes() {
// note domain.com was changes to example.com - this should be changed back
var scriptUrl = "http://example.com/xml/test.XmlDataTypes?AccountId=" + AccountId;
return $.ajax(
{
url: scriptUrl,
type: 'get',
dataType: 'xml',
async: true,
success: function (data) {
//create array to be used in second XML
for (var i = 0; i < xmlRows.length; i++) {
var dataType = xmlRows[i];
var dataTypeId = nodeValue(dataType.getElementsByTagName("DataTypeId")[0]);
var dataTypeName = nodeValue(dataType.getElementsByTagName("DataTypeName")[0]);
dataTypeArray.push({ dataTypeId: dataTypeId, dataTypeName: dataTypeName, position: i, markerArray: [] });
}
},
error: function onXmlError() {
alert("An Error has occurred.");
}
});
}
Then calling them in sequence :
XmlDataTypes.done(XmlAmenityData);
Here is some more documentation :
http://www.htmlgoodies.com/beyond/javascript/making-promises-with-jquery-deferred.html
basically I want a Jquery function to call a PHP script multiple times, and every single time, load the response into a div, this is the code I have now:
images = 10;
while(images > 0)
{
$.ajax({
type: "POST",
url: "processimage.php",
data: { image : 1 },
async: false,
success: function(data) {
$( "#logger" ).append(data+ '<br />');
}
});
images--;
}
What this code is doing is processing all the images and then appending the full response, but I want it to append the response for every single image. Somehow the while block is entirely being processed before updating the #logger div. Am I missing something?
you must remove the async: false. which in turn allows the requests to complete and be appended as they finish. However, you'll then realize that they are being appended out of order! to fix that, we can use promise objects and .then.
images = 10;
var req = $.ajax({
type: "POST",
url: "processimage.php",
data: {
image: images
},
success: function (data) {
$("#logger").append(data + '<br />');
}
});
images--;
while (images > 0) {
req.then(function(){
return $.ajax({
type: "POST",
url: "processimage.php",
data: {
image: 1
},
success: function (data) {
$("#logger").append(data + '<br />');
}
});
});
images--;
}
Now, there's still one more possible issue. if you needed to pass the current value of images with each request, the previous code will send all requests after the first with the last value of images. To fix that, we can use an iffe.
images = 10;
var req = $.ajax({
type: "POST",
url: "processimage.php",
data: {
image: 1
},
success: function (data) {
$("#logger").append(data + '<br />');
}
});
images--;
while (images > 0) {
(function(i){
req.then(function(){
return $.ajax({
type: "POST",
url: "processimage.php",
data: {
image: i
},
success: function (data) {
$("#logger").append(data + '<br />');
}
});
});
})(images);
images--;
}
And then you can make it DRYer as suggested below by storing the options in a separate variable:
images = 10;
var ajaxOpts = {
type: "POST",
url: "processimage.php",
data: {
image: 1
},
success: function (data) {
$("#logger").append(data + '<br />');
}
};
var req = $.ajax(ajaxOpts);
images--;
while (images > 0) {
(function(i){
req.then(function(){
ajaxOpts.data.image = i;
return $.ajax(ajaxOpts);
});
})(images);
images--;
}
I'm trying to do a for loop 10 times and i wrote setInterval to call my function again but it does not work. My for loop turns only ten. So how can i do?
function randomThumbNews() {
for(var i=0;i<10;i++){
$.ajax({
type: "get", url: "Home/Oku", data: {},
success: function (data) {
$("#thumbNews_" + i).html(data);
}
});
}
}
setInterval(randomThumbNews, 3000);
Try something like:
$.ajax({
type: "get", url: "Home/Oku", data: {},
context: i, /* NEW - this value comes to your success callback as 'this' */
success: function (data) {
$("#thumbNews_" + this).html(data);
}
});
The problem is this -- when
function (data) {
$("#thumbNews_" + i).html(data);
}
Is called the loop has already finshed so i will always be 10.
You will only see results posted to one of your <div>s
This will fix it since function parameters don't have closure:
function ajaxAndSet(counter)
{
$.ajax({
type: "get",
url: "Home/Oku",
data: {},
success: function (data)
{
$("#thumbNews_" + counter).html(data);
}
});
)
function randomThumbNews()
{
for(var i=0;i<10;i++)
{
ajaxAndSet(i);
}
}
setInterval(randomThumbNews, 3000);