How do i make my php variable accessible? - javascript

I am trying to implement a timer. I learned this idea from a SO post.
<?php
if(($_SERVER['REQUEST_METHOD'] === 'POST') && !empty($_POST['username']))
{
//secondsDiff is declared here
$remainingDay = floor($secondsDiff/60/60/24);
}
?>
This is my php code. My php,html and JS codes are in the same page. I have a button in my html. When a user clicks on the html page, It will call a Ajax function
//url:"onlinetest.php",
//dataType: 'json',
beforeSend: function()
{
$(".startMyTest").off('click');
setCountDown();
}
It will call setCountDown() method, which contains a line at the very beginning
var days = <?php echo $remainingDay; ?>;
When i run the page, it says[even before clicking the button] "expected expression, got '<'" in the above line. My doubt is
Why this php variable get replaced before i am triggering the button. Please let me know hoe to solve this or how to change my idea.

The problem is, since initial load, $_POST values aren't populated (empty on first load),
That variable you set is undefined, just make sure you initialize that variable fist.
<?php
// initialize
$remainingDay = 1;
if(($_SERVER['REQUEST_METHOD'] === 'POST') && !empty($_POST['username']))
{
//secondsDiff is declared here
$remainingDay = floor($secondsDiff/60/60/24);
echo json_encode(array('remaining_day' => $remainingDay);
exit;
}
?>
<script>
var days = <?php echo $remainingDay; ?>;
$('.your_button').on('click', function(){
$.ajax({
url: 'something.php',
dataType: 'JSON',
type: 'POST',
beforeSend: function() {
// whatever processes you need
},
success: function(response) {
alert(response.remaining_day);
}
});
});
</script>
That is just the basic idea, I just added other codes for that particular example, just add/change the rest of your logic thats needed on your side.

You can pass a php variable into JS code like
var jsvariable ="<?php echo $phpvariable ?>";
NOTE:
If you ever wanted to pass a php's json_encoded value to JS, you can do
var jsonVariable = <?php echo $json_encoded_value ?>; //Note that there is no need for quotes here

Try this,
var days = "<?php echo $remainingDay; ?>";

Related

Incrementing variable by 1 changes variable value to 1 in php

As the title states, I seem to be having an issue with incrementing a variable in my .php file code, it modifies the value in the database, acc_points, to 1 after I increment acc_points by one in the variable above. What the code does is send an ajax request to the php which then updates the data in the mysql database and then returns the data to the js and the js will then alert the data.
The incrementation somehow changes the value of acc_points from 5 to 1. I also considered if the problem had something to do with sessions. I've looked around for relevant information but couldn't find a solution. Would like to find out the real cause of this issue. Thanks!
Here are the codes:
.php file
<?php
require 'dbcon.php';
session_start();
$acc_points = $_SESSION["acc_points"];
$acc_id = $_SESSION["acc_id"];
if(isset($acc_points))
{
$acc_points++;
}
$result = $con->prepare(" UPDATE `points` SET `acc_points` = ? WHERE `acc_id` = ? ");
$result->bind_param("ii", $acc_points, $acc_id);
$result->execute();
if($acc_points != null)
{
$response = $acc_points;
echo $_GET['callback'] . '(' . json_encode($response) . ')';
}
else
{
$response = "'Failed. Please try again.'";
echo $_GET['callback'] . '(' . json_encode($response) . ')';
}
//connection closed
mysqli_close ($con);
?>
js file
$(document).ready(function() {
$("#qrtest").click(function() {
{
$.ajax({
type: "GET",
url: "http://127.0.0.1/MP/appqrcode.php?callback=?",
dataType: 'JSONP',
async: false,
jsonp : "callback",
jsonpCallback: "jsonpcallback",
success: function jsonpcallback(response)
{
alert(response.acc_points);
}
})
}
});
});
The first problem is that you are checking the value of $acc_points in the code below, but you are executing the query regardless of whether it's null or not null
if(isset($acc_points))
{
$acc_points++;
} // if condition ends here. Insert command will always be executed.
Then after the comand has been executed you check the value again
if($acc_points != null) /// insert has already happend.
{
}
So you should restructure your code, but better still, you don't need this approach at all. Why not just?
$result = $con->prepare(" UPDATE `points` SET `acc_points` = acc_points+1 WHERE `acc_id` = ? ");
This increments the value already in the database.

Undefined index in php when getting value passed from AJAX

I'm trying to get the value that I passed in AJAX to PHP. It shows an alert that says, "Success!" however it when I try to display the value in PHP, it says undefined index. Also I am passing it in the same page.
Whenever I click a button, it opens a modal and I also passing values from that button to the modal. This is evident in my JS code.
<script>
$(document).ready(function(){
$('#editModal').on('show.bs.modal', function (e) {
var id = $(e.relatedTarget).data('id'); //im trying to pass this value to php, e.g. 5
var time = $(e.relatedTarget).data('time');
var name = $(e.relatedTarget).data('name');
var stat = $(e.relatedTarget).data('stat');
var desc = $(e.relatedTarget).data('desc');
alert(id);
$("#task_id_edit").val(id);
$("#new-taskID").val(id);
$("#allotted_time_edit").val(time);
$("#task_name_edit").val(name);
$("#task_status_edit").val(stat);
$("#task_desc_edit").val(desc);
$("#task_id_ref2").val(id);
//AJAX CODE HERE
$(function() {
$.ajax({
type: "POST",
url: 'tasks.php?id='<?php $id = isset($_GET['id']) ? $_GET['id'] : ""; echo $id; ?>,
data: { "userID" : id },
success: function(data)
{
alert("success!"); //this display
}
});
});
}); // line 1131
});
</script>
PHP CODE:
<?php
$uid = $_POST['userID'];
echo $uid." is the value";
?>
It keeps getting an error that says, undefined index: userID. I am confused. Please help me how to fix this. Your help will be much appreciated! Thank you!
Echo the number in the javascript string.
Currently you will get:
url:'tasks.php?id='1,
The 1 should be concatenated or inside the quote. Try:
url: 'tasks.php?id=<?php $id = isset($_GET['id']) ? $_GET['id'] : ""; echo $id; ?>',
or take that parameter out since it doesn't appear to be being used.
Just put the $_POST['userID'] in a if statement
Undefined index: UserID is not a error it is a warning
<?php
if(isset($_POST['userID'])
{
$uid = $_POST['userID'];
echo $uid." is the value";
}
else
{
echo "Sorry Value cant be printed";
}
?>

AJAX - Javascript array to php

I know that there are so many to find on the internet, however, I have been trying this for hours now, and still not working, Maybe the community could help me out:)
http://jsfiddle.net/dkk2nqyg/14/
I've got a little explanation in the jsfiddle, else, you can take a look in my previous question, JavaScript array splice
Basicly, I want the values from selected ( 3 picked up cards )
in php, because I want to mail those values;)
$.ajax({
url: 'data.php', //I actually want it to be on same page, trying this for debugging
type: 'post',
data: {data : selected},
success: function(data) {
alert("worked");
}
});
in the data.php :
<?php
$data = json_decode(stripslashes($_POST['data']));
foreach($data as $d){
echo $d;
}
?>
I would like that I don't even need that data.php but just 1 page, so in the index.php, is that even possible?
Edit: Please, link a JsFiddle, would really help!
First the ajax request should be within the click handler
$('#mail').click(function () {
console.log($('#dvDest .flipper').get())
var selected = $('#dvDest .flipper').map(function () {
return $(this).data('src')
}).get();
alert(selected)
$.ajax({
url: 'data.php', //I actually want it to be on same page, trying this for debugging
type: 'post',
data: {
data: selected
},
success: function (data) {
alert("worked");
}
});
})
then in server side loop through the array like(Not sure about the PHP syntax)
<?php
foreach($_POST['data'] as $d){
echo $d;
}
?>
you can write a condition as if request object have post values then
$data = json_decode(stripslashes($_POST['data']));
foreach($data as $d){
echo $d;
}
else your homepage display code
So,index.php is enough
For using a single page, eg: index.php
at the top of index.php you do:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Your code goes here
exit();
}

AJAX PHP function onchange select box

I have a problem about which I am very confused. I have a select box with s dynamically generated using a mysqli query:
$result = mysqli_query($db, "SELECT * FROM `users` WHERE `user_id` > 0");
echo '<html><form name="contacts" method="post"><select name="contacts"><option value="Contact list" onchange="func()">Contact List</option>';
while($row = $result->fetch_assoc()){
echo '<option value = '.$row['user_name'].'>'.$row['user_name'] . '</option>';
}
echo '</select></form>';
I am completely new to AJAX, but I need to use jquery and ajax to pass the this.value variable to a php variable for use in a later query.
Here is my script (most of which was found online):
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
$("#contacts").change(function() {
//get the selected value
var selectedValue = this.value;
//make the ajax call
$.ajax({
url: 'function.php',
type: 'POST',
data: {option : selectedValue},
success: function() {
console.log("Data sent!");
}
});
});
</script>
Now, when I click a value in the select box, nothing happens. There are no warnings or errors, etc.
Please help me.
p.s. function.php does exist. It is just a simple echo for now (for testing purposes)
UPDATE: HERE IS FUNCION.PHP:
<?php
/*$val = $_REQUEST['selectedValue'];
echo $val;*/
function function(){
$val = $_REQUEST['selectedValue'];
echo $val;
}
?>
UPDATE: Thank you everyone for all your help. I have now got it to work in that the network section of chrome inspect shows the function.php being requested however I still don't get the echo (I used external .js files to get it to work). My J query function is also successful (the success function echoes into the console)
Your select box has no ID and you are watching the change event of $("#contacts").
Change:
echo '<html><form name="contacts" method="post"><select name="contacts"><option value="Contact list" onchange="func()">Contact List</option>';
to:
echo '<html><form name="contacts" method="post"><select name="contacts" id="contacts"><option value="Contact list">Contact List</option>';
^^^^^^^^^^^^^ here
You also only need one event handler, so I have removed the inline one which doesn't seem to do anything anyway.
Edit: If the select is created using ajax as well, you need event delegation:
$("body").on('change', '#contacts', function() {
^^^^ for example
Edit 2: Your variable is called $_REQUEST['option'] and not $_REQUEST['selectedValue']. You are also not calling your -badly named - function so you will not get any output from php except from an error like Parse error: syntax error, unexpected 'function' ....
Call onchange function in select tag as below
echo '<form name="contacts" method="post"><select name="contacts" onchange="func(this.value)"><option value="Contact list">Contact List</option></form>';
Javascript src should be in head of the html page.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
Add the above one in head of html. Update javacript as below
As onchange function is called in the select tag itself, following is enough
<script>
function func(selectedValue)
{
//make the ajax call
$.ajax({
url: 'function.php',
type: 'POST',
data: {option : selectedValue},
success: function() {
console.log("Data sent!");
}
});
}
</script>
Updated php: If you must want to get value from function, you must call it. Otherwise, simply, you can make as below
<?php
if($_REQUEST['option'])
{
$val=$_REQUEST['option'];
echo $val;
}
?>
In .php file, receive it first-
$val = $_REQUEST['selectedValue'];
echo $val;
set an id attribute in your php code for the select tag and
please don't use the same value for the name attribute in form and select tags !!
just change your function to a 'body'.on, and give your elements an id of 'contacts'
$("body").on('change', '#contacts', function() {
//get the selected value
var selectedValue = $(this).val();
//make the ajax call
$.ajax({
url: 'function.php',
type: 'POST',
data: {option : selectedValue},
success: function() {
console.log("Data sent!");
}
});
});

ajax not able to pass variable to php

I have a slider which uses javascript. I am trying to update the display of my web page based on the slider values. I tried to use ajax function to send the data to another PHP page to update the display. But I am not getting anything in my page. Here is my code so far.
<?php
$i = 1;
while (++$i <= $_SESSION['totalcolumns']) {
$range = $_SESSION["min-column-$i"] . ',' . $_SESSION["max-column-$i"];?>
<br><?php echo "Keyword" ?>
<?php echo $i -1 ?>
<br><input type="text" data-slider="true" data-slider-range="<?php echo $range ?>" data-slider-step="1">
<?php } ?>
<button type="button" onclick="loadXMLDoc()">Update</button>
<script>
$("[data-slider]")
.each(function () {
var range;
var input = $(this);
$("<span>").addClass("output")
.insertAfter(input);
range = input.data("slider-range").split(",");
$("<span>").addClass("range")
.html(range[0])
.insertBefore(input);
$("<span>").addClass("range")
.html(range[1])
.insertAfter(input);
})
.bind("slider:ready slider:changed", function (event, data) {
$(this).nextAll(".output:first")
.html(data.value.toFixed(2));
});
</script>
<script>
function loadXMLDoc()
{
alert "Am I coming here";
$.ajax({
type: "POST",
url: 'update.php',
data: { value : data.value },
success: function(data)
{
alert("success!");
}
});
}
</script>
I read in another post that javascript variables are available across functions and so I am trying to use the variable data.value inside my another javascript function loadXMLDoc(). But I do not see the value getting displayed in my update.php page. My update.php file is as below.
<?php
if(isset($_POST['value']))
{
$uid = $_POST['value'];
echo "Am I getting printed";
echo $uid;
}
?>
Can someone please help me on this?
In the loadXMLDoc function I don't see data defined anywhere. I think that could be one of the problems. Also, when you're doing jquery ajax requests be sure to have a fail callback. The fail callback will tell you if the request fails which can be very informative.
var jqxhr = $.ajax( "example.php" )
.done(function() {
alert( "success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "complete" );
});
To make the data variable accessible in the XMLLoadDoc function you could try putting it in the global scope (kind of a 'no-no', but its OK for a use case like this). So, at the top, declare var masterData, then when you have data in the .bind callback set masterData = data; and then in loadXMLDoc refer to masterData

Categories