Ajax - Issue - Sending JavaScript Var to PHP script - javascript

I have not been able to find a simple example of ajax with single variable, everything on here is made way too complicated for an AJAX beginner. I've watched about 4 different YouTube videos on the topic, but can't seem to get it right.
I have the src of an image in a variable like so with a JavaScript..
<img alt="" src="blah.jpg" style="height: 276px; width: 200px" id="imgClickAndChange1" onclick="changeImage(this)" />
<script language="javascript">
function changeImage(imagePass) {
var num = Math.floor((Math.random() * 48) + 1);
var n = num.toString();
var numImg = n.concat(".jpeg");
var string = "/Images/Folder/"
var final = string.concat(numImg);
imagePass.src = final;
//(this is where I want to pass the variable imagePass.src or "final" to a php script w/ Ajax)
Here is my php script:
<?php>
include_once "code.php"; //connecting to database
$s = (this is where I want the variable to be posted);
$temp = explode('/', $s);
$temp2 = explode('.', $temp[count($temp) - 1]); //this is getting the variable I want from the variable sent(which is actually a number)
$float = (int)$temp2; //changing the number (which is a string) to an int
mysql_query("UPDATE Variable SET `upVote` = `upVote`+1 WHERE id= (variable here)) " //Making a row in my database w/ the id of the variable add 1 to the count
?>
How would I go about posting and sending this w/out a page refresh? AJAX is really confusing me so a working implementation to get me started on this would be great, Thanks a lot.
//Let's just assume the php page where the script is located is called 'hello.php'

To use ajax, try this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
function changeImage(imagePass) {
var num = Math.floor((Math.random() * 48) + 1);
var n = num.toString();
var numImg = n.concat(".jpeg");
var string = "/Images/Folder/"
var final = string.concat(numImg);
imagePass.src = final;
$.ajax({
url : 'hello.php',
type: 'post',
data : {'final':final},
success: function()
{
alert('Success!');
}
});
}
</script>
PHP script (hello.php):
<?php>
include_once "code.php"; //connecting to database
$s = $_POST['final'];
$temp = explode('/', $s);
$temp2 = explode('.', $temp[count($temp) - 1]); //this is getting the variable I want from the variable sent(which is actually a number)
$float = (int)$temp2; //changing the number (which is a string) to an int
mysql_query("UPDATE Variable SET `upVote` = `upVote`+1 WHERE id= (variable here)) " //Making a row in my database w/ the id of the variable add 1 to the count
?>

Related

Refresh <a> that has PHP variable connected to XML URL without reloading

I have two files home.php and calc.php, the file calc.php has variables parsing from XML URL and this url data keep changing automatically but the problem is i need a specific element in this home.php keep refreshing automatically
as you see in my code there is a div has alink inside it and the link has php variable $amount and this var keep updating,
so i tried to use AJAX like this but it did not work and after 1 s the link disapear So what to do please?
THANKS
var auto_refresh = setInterval(
function () {
$('#low2z3').load('calc.php'});
}, 1000);
<div id="linnnez4" class="linnne res1"><a id="low2z3"><?php echo $amount1;?></a> </div>
<!--in calc.php-->
<?php
$url = 'http://magneticexchange.com/export.xml';
$xml = simplexml_load_file($url);
foreach($xml->item as $item) {
if($item->from == "PRUSD" && $item->to == "NTLRUSD") {
$give = $item->in;
$get = $item->out;
$amount = 10;
$give1 = $amount." ".$item->from;
$get1 = $amount * $get / $give;
$get2 = number_format($get1, 2). " ".$item->to;
$amount1 = $item->amount;
break;
}
}
?>

Javascript does not show data obtained from PHP and SQL Server

I'm new to PHP and I have little knowledge of Javascript, I'm trying to create a chronometer that the time limit is obtained from a database (SQL SERVER), so when you get the value in PHP and assign it to a variable of Javascript function, I get a -1.
From what I read it appears to me that the PHP object type is not the same as in Javascript and this can be solved with json_encode (), however it keeps appearing -1.
<?php
require('db.php');
if ($connection)
{
$TimEva = 60;
$rs = odbc_exec($connection,"SELECT time FROM DBO.tablaCrono cr WHERE cr.id = '$EncIdx';");
while(odbc_fetch_row($rs))
{
$TimEva=odbc_result($rs,"TimEva");
}
echo "<div align='center'><h1><label id = 'tiempo'>".$TimEva."</label></h1></div>";
$rs = odbc_close($connection);
}
else
{
echo "<div align='center'>no se pudo conectar</div><br />";
}
?>
And in the Javascript function I have the following
var label = document.getElementById("tiempo"),
minutos = <?php echo json_encode($TimEva,JSON_HEX_TAG);?>,
I expect 60, which is the value in the database, it shows up well in html, but the value of the variable minutes, throws -1
I could be guided, help, use AJAX, I'm really a bit lost.
$rs = odbc_exec($connection,"SELECT `time` FROM DBO.tablaCrono cr WHERE cr.id = '$EncIdx';");
Change your query to this. time is a word used from the language so if you want to use it as a column you need to escape it.
Also modify your JS code to something like :
<script>
var label = document.getElementById("tiempo")
var minutos = <?php echo json_encode($TimEva,JSON_HEX_TAG);?>
console.log(minutes)
</script>
Then open your console window and see what is the value that your variable has.
Lastly ensure that you actually have a value in $EncIdx variable cause we don't see how you assign a value to it. I guess it's in a part of the code you did not share.
<script>
function tiempo()
{
var label = document.getElementById("tiempo"),
minutos = <?php echo json_encode($TimEva,JSON_NUMERIC_CHECK);?>,
segundos = 0,
intervalo = setInterval(function(){
console.log(minutos)
if (--segundos < 0){
segundos = 59;
minutos--;
}
if (!minutos && !segundos)
{
clearInterval(intervalo);
alert("Lo sentimos se termino el tiempo");
//document.evaluacion.submit();
}
label.innerHTML = minutos + ":" + (segundos < 10 ? "0" + segundos : segundos);
}, 1000);
}
</script>

Change Jquery variables to PHP

I need to put a Javascript variable into php variable, I dont know how to do that. Possible answers are appreciatable.
<script type="text/javascript">
$(document).ready(function(){
$('#number_of_inwards,#number_of_outwards').each(function(){
var product_name,total_stock;
$('#product_name').change(function(){
product_id = $('#product_name').val();
});
var hello = "13";
<?php $d = '<script>hello</script>' ?>
total_stock = <?php echo $st[$d]; ?>;
console.log(total_stock);
$(this).focusout(function(){
var inward = parseInt($('#number_of_inwards').val());
var outward = parseInt($('#number_of_outwards').val());
$('#overall_stock').val(parseInt(inward+outward));
console.log("Inside the Loop"+ inward + outward);
})
})
});
</script>
Here from the code.I added dummy variable
hello="13"
And tried to get it into php variable but It won't work, It returns empty value.
Thanks in advance

To find which image out of the two were clicked and report it to Database

I'm not very new to programming nor am I a prodigy or a maestro at it. Now I'm trying to make a website like Facesmash where
two images show up randomly from the respective arrays and
an up-vote is given to the image on which user clicked
the result is stored as a vote in database
Now I've done with the first part and will do with the third as well with php.
Where I'm facing a problem is the 2nd part.
My code in JavaScript looks like this..
var imagesArray1 = ["a.jpg","b.jpg","c.jpg","d.jpg","e.jpg"];
var imagesArray2 = ["f.jpg","g.jpg","h.jpg","i.jpg","j.jpg"];
function displayImage(){
document.getElementById('nextButton').value="NEXT";
var num1 = Math.floor(Math.random() * (imagesArra1.length));
var num2 = Math.floor(Math.random() * (imagesArray2.length));
document.canvas1.src = imagesArray1[num1];
document.canvas2.src = imagesArray2[num2]; }
As you can see.. I've created two arrays and a random Image is generated from both the two. Now to create a polling system, one solution would be to take two variables p and q. p=num1 and q=num2 If image1 is clicked, the php code reports "p" and value of the index num1 to the DB
If image2 is clicked, php code sends "q" and value of the index num2
num1 and num2 are the randomly generated indices of the image arrays. I'll do with the php part, Just wanted help in this. Any other code solution would be appreciated. Thanks a ton for time and help
I tried to write this up :
This is what I suggest you should display your images.
<img src="pathToImage1Array" data-name="p" id="num1_Image1IndexFROMTheArrayVariable">
<img src="pathToImage2Array" data-name="q" id="num2_Image2IndexFROMTheArrayVariable">
Please note.
Id needs to be unique for each image that will come from the array.
so we need to make our ID for the image unique.. with a dynamic data. so we will have a prefix for each image ID that will come up from the array.
in this case we have num1_ then the string after the underscore (_) will be replaced by the variable that stores index of each image so if the index of the image is 8 then num1_8 this changes as the image changes.
Then you will need to send ajax request to some php script when the image is clicked.
then your ajax :
<script type="text/javascript">
$('document').ready(function(){
//getting data of the 1st image.. that have a dyamic ID.
$('[id^="num1_"]').on('click',function(){
var index = $(this).attr('id').split("_")[1]; //get index of the clicked image
var action = "firstimage";
var image = $(this).data('name');
$.ajax({
type : "POST",
data : {imageIndex:index,action:action,:image:image},
url : "pathTophpfile/phpfile.php",
dataType :"json",
encode : true,
success : function(response){
if(response == "ok"){
alert("vote casted");
}else{
alert(response);
}
}
});
});
$('[id^="num2_"]').on('click',function(){
var index = $(this).attr('id').split("_")[1]; //get the index of the clicked image
var action = "secondimage";
var image = $(this).data('name');
$.ajax({
type : "POST",
data : {imageIndex:index,action:action},
url : "pathTophpfile/phpfile.php",
dataType :"json",
encode : true,
success : function(response){
if(response == "ok"){
alert("vote casted");
}else{
alert(response);
}
}
});
});
});
</script>
then your server side :
I'm not sure which API you comfortable with PDO/MYSQLI I did mysqli prepared statements :
<?php
$conn = new mysli("..."); // the staff you should know already
function image1($conn)
{
if ($_SERVER['REQUEST_METHOD'] == "POST"):
$imageIndex = $_POST['imageIndex'];
$image = $_POST['image'];
$sql = $conn->prepare("INSERT into YourTable (`p/q`,index) VALUES(?,?)");
$sql->bind_param("si", $image, $imageIndex);
if ($sql->execute()) {
echo json_decode("ok");
} else {
echo json_decode("Error : " . $conn->error);
}
endif;
}
function image2($conn)
{
if ($_SERVER['REQUEST_METHOD'] == "POST"):
$imageIndex = $_POST['imageIndex'];
$image = $_POST['image'];
$sql = $conn->prepare("INSERT into YourTable (`p/q`,index) VALUES(?,?)");
$sql->bind_param("si", $image, $imageIndex);
if ($sql->execute()) {
echo json_decode("ok");
} else {
echo json_decode("Error : " . $conn->error);
}
endif;
}
if (isset($_POST['action'])) {
$action = $_POST['action'];
switch ($action) {
case 'firstimage':
image1($conn);
break;
case 'secondimage':
image2($conn);
break;
}
}
?>

Ajax response text is always 1

I am sending two variables to my php page for calculation then echoing the end result back. My response text always equals one.
The Javascript:
var xhttp = new XMLHttpRequest();
xhttp.open("GET","calc.php?w1="+ftest+"&w2="+ltest,true);
xhttp.onreadystatechange = function() {
if(xhttp.readyState==4)
{
var dog = xhttp.responseText;
alert(dog);
}
};
xhttp.send(null);
}
The php:
I set the end var to a random number here just to test if my math was causing the problem.
$startdate = $_GET['w1'];
$endDate = $_GET['w2'];
$workingdays = 239;
echo $workingDays;
Set $workingDays directly to 10 ( random number ). If it is not 10, then you are clearly not seeing the result of that echo statement.
1 is often used as the output to native PHP functions such as isset
You're case is wrong.
$workingdays = 239;
echo $workingDays;
Make it workingDays (with capital D) in both places.
Always use isset() for receiving data and you are using variable $workingdays for declaration and for echo $workingDays, take care of these things. I hope this will work for you.
$startdate = '';
$endDate ='';
if(isset($_GET['w1']))
{
$startdate = $_GET['w1'];
}
if(isset($_GET['w2']))
{
$endDate = $_GET['w2'];
}
$workingdays = 239;
echo $workingdays;
die;
Try adding this variable in your ajax code just to make a test if in the server side is receiving the data you sent using get method.
var ftest = 1;
var ltest = 2;
I assumed that your ajax code is inside the a function let say myfunction and you have a link like this link
Here is the full implementation of the code assuming that your filename is index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Ajax</title>
</head>
<body>
link
<script type="text/javascript">
function myfunction () {
var ftest = 1;
var ltest = 2;
var xhttp = new XMLHttpRequest();
xhttp.open("GET","calc.php?w1="+ftest+"&w2="+ltest,true);
xhttp.onreadystatechange = function() {
if(xhttp.readyState==4) {
var dog = xhttp.responseText;
alert(dog);
}
};
xhttp.send(null);
}
</script>
</body>
</html>
and Calc.php
<?php
$startdate = $_GET['w1'];
$endDate = $_GET['w2'];
$workingdays = 239;
$result = $startdate + $endDate;
echo "$result";
?>
In this example you alert will equal to 3 it be same in your code
Hope this will help

Categories

Resources