Why this is variable does not work? Jquery [duplicate] - php

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I am writing the following code below, which basically takes the data from the current date to a PHP file to handle in jQuery. Until here everything well. But I'm not understand why I can not have a new value of the total variable after it picks the value coming PHP file.
day.each(function () {
var $this = $(this);
var the_index = $this.index();
var the_date = $this.find('h3.date').html().substr(0,2);
var the_day = $this.find('h3.day');
/*THIS VARIABLE*/
var total = 0;
$.get('trd/datetime.php', function (date) {
if(that.hasClass('list-'+date.day)) {
weekList.find('.item.list-'+date.day).addClass('active');
}
total = date.firstDate;
}, 'json');
console.log(total);
});
I don't know if my english helps, but, please, tell me what wrong I'm doing!
Thanks.

The .get call is asynchronous -- the stuff inside it runs after your console.log statement.
You probably want to use a callback, which you invoke from inside the .get handler:
$.get('trd/datetime.php', function (date) {
// ...
callback(total);
}, 'json');
function callback(total) {
console.log(total);
}

Related

How to get javascript variable to php [duplicate]

This question already has answers here:
how to convert javascript variable to PHP variable? [closed]
(2 answers)
How to get JavaScript function data into a PHP variable
(5 answers)
Closed 9 years ago.
i am trying to get the javascript variable value to php.
here is my javascript code:
function getResults()
{
var radios = document.getElementsByName("address");
for (var i = 0; i < radios.length; i++)
{
if (radios[i].checked) {
var a = radios[i].value
alert(a);
break;
}
}
}
from this javascript i want to get variable a's value inside php code onclick on submit button.
how can i do this?
i tried this
$var1 = $_GET["a"];
Do this..
$var1 = <?=$_GET["a"]?>;
to communicate a value from JavaScript to PHP do following
$var1 = <?=$_POST["a"]?>;
What you tried is almost correct:
var a = <?=$_GET["a"]?>;
Since javascript code runs on client-side, but PHP is server-side code, you need to send your JS variables to the server. You can do this using AJAX.
Hint: AJAX calls usually use POST instead of GET.
Replace:
$var1 = $_GET["a"];
on:
$var1 = <?=$_POST["a"]?>;

Set Session inside the javascript [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 9 years ago.
I want to set session inside the javascript. But all the time this function return false value. Please tell me the error of this code.
<script>
function myFunction(){
var r=confirm("Would you like to add another item ?");
if (r==true) {
alert('ok');
var varname = '<?php echo $_SESSION["redirect"]=1; ?>';
}
if(r==false) {
alert('bad');
var varname = '<?php echo $_SESSION["redirect"]=2; ?>';
}
}
</script>
You can't evaluate PHP on the client. Do an AJAX request to the server setting the session variable instead.
Javascript runs on the client side, so you'll need to perform an AJAX call to a server side script that will change the sessions value.
Something in the lines of:
function changeSession()
{
$.ajax({
url: /change_session.php?value=1&key=redirect,
dataType:"html"
});
}
And in change_session.php:
<?php $_SESSION[$_REQUEST['key']]=$_REQUEST['value'] ?>

Need to pass a value from PHP to Javascript [duplicate]

This question already has answers here:
how to pass these strings from php to javascript
(5 answers)
Closed 9 years ago.
I need to pass a value from PHP back to my javascript. I have tried so many things but can't get it to work. Here is my code.
<script type="text/javascript">
life = {};
life.anjaxEnter = function(finished) {
$.ajax({
dataType:"json",
type:"POST",
data:mydata,
url:"myurl.php",
async:false,
success:life.receiveResult,
});
setTimeout("location.href='myredirectionurl'", 1000); // Redirect after 1 second
}
life.receiveResult = function(result) {
alert(result);
}
</script>
I need to pass a specific value from the PHP file back to life.receiveResult and then add this to the redirection url.
The biggest problem is probably that at the time when you assign life.receiveResult to success, life.receiveResult is undefined. You need to define it before you assign it to something else.
myurl.php needs to return a JSON result when it's called. Something like this:
<?php
header("Content-Type: text/json");
$mydata = "Hello";
echo json_encode(array('ok' => true, 'mydata' => $mydata));
?>
Have a look at the json_encode docs, the header docs and some of the other answers for more information.

Update an element on parent page from fancybox [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Update a Select Box on Parent Page from FancyBox2
I'm trying to update an element on my site from a fancybox. In the fancybox I do a $.post() and get back html data that aI want to populate in a div on my page. I'm opening the fancybox in ajax. I can see in firebug that my script is returning the html but the select box on the parent page is not updating. Can anyone help me with the proper way to do that? I'm currently trying from the fancybox:
$("#send-message").click(function () {
$(this).closest('form').submit(function () {
return false;
});
var frm = $(this).closest('form');
if ($(frm).valid()) {
$("#ajax-loading").show();
var data = $(frm).serialize();
$(frm).find('textarea,select,input').attr('disabled', 'disabled');
$.post("../forms/company_add.php",
data,
function (data) {
if (data.success) {
$('#companyselect', $(parent.document)).html(data.success);
parent.$.fancybox.close();
} else {
$("#ajax-loading").hide();
$(frm).find('textarea,select,input').removeAttr('disabled');
$("#send_message_frm").append(data.error);
}
}, "json"
);
}
});
I'm using fancybox-2 and php. Thx!
I think you just need to use the id of the element
$('#companyselect').html(data.success);
$.fancybox.close();
Write a javascript function on your parent like
function UpdateElementOfParent(someValue)
{
// your code
}
And from your fancybox, you can the object of parent and call its function like that..
this.parent.UpdateElementOfParent(someValue);

Returning post data [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
$.post("../js.php", {state: state},
function(data) {
return data;
});
Here's my jquery code. Like you can see it sends a post request to js.php.
Here's the code for js.php.
{...}
$query = "SELECT * FROM table WHERE x='" . $y . "'";
$result = $mysqli->query($query);
$num_rows = $result->num_rows;
echo $num_rows ? $num_rows : 0;
Now, when I alert the "data" back in the js file then it displays fine. But when trying to return it or assign it to a variable it does not work. The console tells me that the variable that has been assigned the value of data is undefined.
Any thoughts?
Updated code:
var data = null;
$.post("../js.php", {state: state},
function(response) {
data = response;
});
console.log(data);
Still not working. :(
the function in the post is a callback function, you cannot return anything from it since there is no one to return it to.
You need to use the data retuened inside the callback, for example:
$.post("../js.php", {state: state},
function(data) {
$('.someClass').html(data);
});
The callback you pass to asynchronous methods such as $.post are executed some time in the future, once the async call has returned. The JavaScript execution has moved on and is now somewhere else, so there is nowhere for your callback to return to.
Imagine it like this:
//Some code... executed as you would expect
var data; //Currently undefined
$.post("../js.php", {state: state}, function(response) {
//Callback is executed later, once server responds
data = response; //No good, since we already executed the following code
return response; //Return to where? We have already executed the following code
});
/* More code... we carry on to this point straight away. We don't wait for
the callback to be executed. That happens asynchronously some time in
the future */
console.log(data); //Still undefined, callback hasn't been executed yet
If you need to work with the data returned by the async call, do so in the callback.
var data = null;
$(...).click(function(e) {
$.post("../js.php", {state: state},
function(response) {
data = response;
});
});
After that just access data variable. Keep in mind that its value will be null unless the post request is done.
The example you posted will do nothing EVERY TIME because AJAX calls like this are ASYNCHRONOUS (that's what the A in AJAX stands for).
If you want to be able to use the value of the output, add a hidden element to your page with a unique ID that contains the value. Then you can access that element through javascript.
Thats because, the ajax call is asynchronous. You should never return a value from a callback function. Do the job in the callback or trigger an event.

Categories