Why isn't my variable getting passed in php? - javascript

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

Related

Javascript - why is this undefined?

The alert at the start shows "undefined", why?
The alerts come in this order:
"success!"
"Data" (what it should be)
"undefined"
I read through multiple threads, the problem was always that ajax was asynchronous, so the data was not defined when it was accessed, but in my case the data is there, the alert in my function shows the data BEFORE the other alert where it is undefined!
Very grateful for any help!
I got this code
var data = getData("");
alert(data); <<<<<<< UNDEFINED
function getData(fileName) {
$.ajax({
async:false,
type: "GET",
url: "breastCancer.csv",
dataType: "text",
success: function (data) {
var arrData = processData(data);
alert("success!");
alert(arrData); <<<<< WORKS GREAT
return arrData;
},
});
}
function processData(data) {
var arrData = CSVToArray(data);
dimensions = arrData[0];
var objects = [];
objects[0] = dimensions;
for (var i = 1; i < arrData.length; i++){
objects[i] = new Object();
for (var j = 0; j < dimensions.length; j++){
objects[i][dimensions[j]] = arrData[i][j];
}
}
return objects;
}
To clarify, I know asynchronous is the way to go for user experience, but this page just has to show data from this call, so its okay for me to wait for it.
Your getData function doesn't return anything.
You need to return it from the function itself.
function getData(fileName) {
$.ajax({
async:false,
type: "GET",
url: "breastCancer.csv",
dataType: "text",
success: function (data) {
var arrData = processData(data);
alert("success!");
alert(arrData); <<<<< WORKS GREAT
return arrData;
},
});
}
^ This returns the data within getData. But getData doesn't do anything with it: such as returning it.
function getData(fileName) {
var ourData = "";
$.ajax({
async:false,
type: "GET",
url: "breastCancer.csv",
dataType: "text",
success: function (data) {
var arrData = processData(data);
ourData = arrData;
},
});
return ourData;
}
This returns the data from getData to whatever calls that function.
edit: also, don't use async:false. Your browser won't capture any events happening until that AJAX completes. The benefit of asynchronous JS is that...we can! And in this case should.
Preface: Don't use async: false. But answering the question:
getData doesn't return anything. You're doing a return from the success callback, but that returns something from the success callback, not getData.
To change it so getData returns something, you'd do this:
function getData(fileName) {
var arrData;
$.ajax({
async:false,
type: "GET",
url: "breastCancer.csv",
dataType: "text",
success: function (data) {
arrData = processData(data);
},
});
return arrData; // <=== Now `getData` returns something
}
But don't do that. Instead, embrace asynchronous programming and remove async: false. For instance, a callback:
function getData(fileName) {
$.ajax({
async:false,
type: "GET",
url: "breastCancer.csv",
dataType: "text",
success: function (data) {
callback(processData(data));
},
});
}
...called like this:
getData(function(data) {
alert(data);
});
...or a promise ($.ajax returns one, of sorts):
function getData(fileName) {
return $.ajax({
async:false,
type: "GET",
url: "breastCancer.csv",
dataType: "text",
success: function (data) {
callback(processData(data));
},
}).then(data) {
return processData(data); // <== Becomes the resolution value of `getData`'s promise
});
}
and then
getData().then(function(data) {
alert(data);
});
data is undefined because the function getData doesn't return anything. You should have a look at promises.

Nested Ajax Want to Running in Sequence

My code is as follows
$.ajax({
type: 'post',
dataType: 'json',
url: '123.123.0.1',
success: function (result) {
for (var i = 0; i < 2; i++) {
console.log('OUTSIDE');
$.ajax({
type: 'post',
dataType: 'json',
url: '123.123.0.1',
success: function (result) {
console.log('INSIDE');
}
});
}
}
});
Result of that code is :
OUTSIDE
OUTSIDE
INSIDE
INSIDE
My Objective here is I want to outside AJAX wait inside AJAX until inside AJAX done then inside AJAX continue. So I wanna the result look
like :
OUTSIDE
INSIDE
OUTSIDE
INSIDE
My question :
How to do that? How to fix my code?
You have to wait the ajax request to be finished before you go to the next step.
Below an recursive example.
// Code goes here
$.ajax({
type: 'post',
dataType: 'json',
url: '123.123.0.1',
success: function(result) {
function processResult() {
if (i >= 2) return;
console.log('OUTSIDE');
$.ajax({
type: 'post',
dataType: 'json',
url: '123.123.0.1',
success: function(result) {
console.log('INSIDE');
}
}).then(function() {
processResult(++i);
});
}
processResult(0);
}
});

jquery: function parameter is undefined in success callback

I am trying to access graphList within success callback, but graphList is undefined. I referred this StackOverflow post. However, I am not able to access elem. Any help would be appreciated.
getGraphData = function (graphList) {
$.ajax({
type: "GET",
url: 'someURL',
beforeSend: function(xhr){},
success: function(result) {
console.log(result);
console.log(graphList);//undefined
}
});
}
Added creating getGraphList function as below, I can access getGraphList inside success callback
var graphList;
var promise = graphInit(response);
promise.done(function(data){
getGraphData(data.graphs)
}
graphInit = function(response,graphList){
getGraphList = function(){return response.graphs;}
}
getGraphData = function (graphList) {
$.ajax({
type: "GET",
url: 'someURL',
beforeSend: function(xhr){},
success: function(result) {
console.log(result);
console.log(graphList);//undefined
graphList = getGraphList();//available
}
});
}

Variable is not being recognized outside function even after making it global JavaScript

I can't get my head around why this is not working I have also tried window.variable and that doesn't work from my understanding anything without the var keyword is at global level.
I would expect the window.alert to work but it is saying it is undefined I also thought it was perhaps because i was using the this keyword so I tried making another variable it did the same thing and before you ask I am pressing a key and still undefined.
$(document).ready(function() {
flag = false;
var x = $('.inpbox');
x.keyup(function() {
logVal = this.value + 'helloooo';
console.log(logVal);
});
window.alert(logVal);
$.ajax({
type: "POST",
url: 'searchbar.php',
data: {
val: 'logVal'
},
dataType: 'json',
});
$('#abcd').click(function() {
setInterval(function() {
via_ajax();
}, 1000);
function via_ajax() {
flag = true;
if (flag == true) {};
$.ajax({
type: "POST",
url: 'searchbar.php',
data: {
val: 'logVal'
},
dataType: 'json',
});
};
});
});
You change it to something like this.
<script>
$(document).ready(function(){
$("input").keyup(function(){
logVal = this.value + 'helloooo';
ajax_Val();
});
});
function ajax_Val()
{
$.ajax({
type: "POST",
url: 'searchbar.php',
data: {
val: logVal
},
dataType: 'json',
});
}
</script>

How can I call my function multiple times using setInterval?

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);

Categories