how to use AJAX? - javascript

I'm trying to use AJAX so that you don't see the reload refresh.
i want if i change the select button from 1 to 5 that you can see 5 live change and that i can use the 5 in a php variable.
i got this:
<script>
$(document).on('change', '#hoeveelheid', function(e) {
var j_Hoeveelheid = this.options[e.target.selectedIndex].text;
$.ajax({
type: 'POST',
url: 'do.php',
data: {aantal : j_Hoeveelheid},
success: function (data) {
$('.test').html(data);
}
});
}
</script>
Now is my question what i need to set in the do.php file?
so that my script works without any refresh visible.

what i need to set in the do.php file?
At php file you are sending this object:
data: {aantal : j_Hoeveelheid},
so you need to get the key aantal at php end.
You can do this in your php file:
<?php
$aantal = $_POST['aantal'];
echo $aantal . " is the posted value of dropdown.";
?>

Related

Trying to post a javascript variable to a php file using the ajax method : POST but getting an undefined index in $POST array within php file

I have a php file with the directory "JqueryPHP/HighestBid.php". All I want to do is be able to post javascript variables from one file "views/AuctionPage.php" to another file "JqueryPHP/HighestBid.php".
I then want to echo a value from "JqueryPHP/HighestBid.php" into the span tags with the id "price" into "views/AuctionPage.php".
The problem is that when I load the page "views/AuctionPage.php" it shows me the alert with the returned value "hi" but where the text is supposed to be outputted between the span tags, it is telling me that the index within my $POST array is undefined.
//JS views/AuctionPage.php
<script>
$(document).ready(function() {
var auc = "hi";
$.ajax({
url: "JqueryPHP/HighestBid.php",
method: "POST",
data: {'auctionid': auc },
success: function (result) {
alert("result: " + result);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function () {
$('#price').load('JqueryPHP/HighestBid.php')
}, 333);
});
</script>
//HTML views/AuctionPage.php
<h4 class="price">Highest bid : <span id="price"></span></h4>
//PHP FILE "JqueryPHP/HighestBid.php"
<?php
$auctionid = $_POST['auctionid'];
echo $auctionid;
?>
When I get rid of the $POST array in "JqueryPHP/HighestBid.php" and just assign auctionid with a normal string.
<?php
$auctionid = "hi";
echo $auctionid;
?>
the text gets outputted between the span tags like it's supposed too so I am having a problem posting the variables to another page and I have no idea why. I have tried many ways to get this to work following examples on stack overflow but to no success.
This line:
$('#price').load('JqueryPHP/HighestBid.php')
loads the JqueryPHP/HighestBid.php script using GET, and that's another, completely independent request from your AJAX one, that's why the $_POST superglobal is empty. What you need to do is to change the span inside the success function of your AJAX call:
$.ajax({
url: "JqueryPHP/HighestBid.php",
method: "POST",
data: {'auctionid': auc },
success: function (result) {
// alert("result: " + result);
$('#price').html(result);
}
});
That gives the result you need. Delete the whole setInterval code, you don't need it at all.

Passing data with POST with AJAX

I'm trying to POST some data to another page with AJAX but no info is going, i'm trying to pass the values of two SELECT (Dropdown menus).
My AJAX code is the following:
$('#CreateHTMLReport').click(function()
{
var DeLista = document.getElementById('ClienteDeLista').value;
var AteLista = document.getElementById('ClienteParaLista').value;
$.ajax(
{
url: "main.php",
type: "POST",
data:{ DeLista : DeLista , AteLista : AteLista },
success: function(data)
{
window.location = 'phppage.php';
}
});
});
Once I click the button with ID CreateHTMLReport it runs the code above, but it's not sending the variables to my phppage.php
I'm getting the variables like this:
$t1 = $_POST['DeLista'];
$t2 = $_POST['ParaLista'];
echo $t1;
echo $t2;
And got this error: Notice: Undefined index: DeLista in...
Can someone help me passing the values, I really need to be made like this because I have two buttons, they are not inside one form, and when I click one of them it should redirect to one page and the other one to another page, that's why I can't use the same form to both, I think. I would be great if someone can help me with this, on how to POST those two values DeLista and ParaLista.
EDIT
This is my main.php
$('#CreateHTMLReport').on('click',function() {
$.ajax({
// MAKE SURE YOU HAVE THIS PAGE CREATED!!
url: "main.php",
type: "POST",
data:{
// You may as well use jQuery method for fetching values
DeLista : $('#ClienteDeLista').val(),
AteLista : $('#ClienteParaLista').val()
},
success: function(data) {
// Use this to redirect on success, this won't get your post
// because you are sending the post to "main.php"
window.location = 'phppage.php';
// This should write whatever you have sent to "main.php"
//alert(data);
}
});
});
And my phppage.php
if(!empty($_POST['DeLista'])) {
$t1 = $_POST['DeLista'];
# You should be retrieving "AteLista" not "ParaLista"
$t2 = $_POST['AteLista'];
echo $t1.$t2;
# Stop so you don't write the default text.
exit;
}
echo "Nothing sent!";
And I'm still getting "Nothing Sent".
I think you have a destination confusion and you are not retrieving what you are sending in terms of keys. You have two different destinations in your script. You have main.php which is where the Ajax is sending the post/data to, then you have phppage.php where your success is redirecting to but this is where you are seemingly trying to get the post values from.
/main.php
// I would use the .on() instead of .click()
$('#CreateHTMLReport').on('click',function() {
$.ajax({
// MAKE SURE YOU HAVE THIS PAGE CREATED!!
url: "phppage.php",
type: "POST",
data:{
// You may as well use jQuery method for fetching values
DeLista : $('#ClienteDeLista').val(),
AteLista : $('#ClienteParaLista').val()
},
success: function(data) {
// This should write whatever you have sent to "main.php"
alert(data);
}
});
});
/phppage.php
<?php
# It is prudent to at least check here
if(!empty($_POST['DeLista'])) {
$t1 = $_POST['DeLista'];
# You should be retrieving "AteLista" not "ParaLista"
$t2 = $_POST['AteLista'];
echo $t1.$t2;
# Stop so you don't write the default text.
exit;
}
# Write a default message for testing
echo "Nothing sent!";
You have to urlencode the data and send it as application/x-www-form-urlencoded.

Pass JS var to PHP var

I need to have a "global" variable because I need to use it in different page and I want to modify it too: I think that I need to use $_SESSION
I need to change this variable, when the user click on dropdown or list.
I have this:
SOLUTION 1
PageA:
$('#list.test li').on('click',function(){
choice=$(this).attr('id');
$.ajax({
url: "PageB.php",
data: {word : choice},
dataType: "html",
success: function (data) {
$('#content_table').html(data);
}
});
});
PageB
session_start();
$_SESSION['b']=$_GET['word'];
echo $_SESSION['b']; // It works
PageC for verify the result
session_start();
echo $_SESSION['b']; // Error !!
In my PageC, I have an error ( Notice: Undefined index: b )
Is it possible to update session variable with ajax ?
SOLUTION 2
PageA: I want to passe the id JS var to PHP var
$('#list.test li').on('click',function(){
choice=$(this).attr('id');
<?php $_SESSION['b'] ?> = choice; //<--- it is possible ?
$.ajax({
url: "PageB.php",
data: {word : choice},
dataType: "html",
success: function (data) {
$('#content_table').html(data);
}
});
});
This solution doesn't work because AJAX and PHP are note in the same side (client/server).
Thank you
You can push data to cookies via JavaScript, smth like document.cookie = "key=value";
And receive it on back-end like $_COOKIE["key"];.
$_SESSION['b']=$_GET['projet']; should be $_SESSION['b']=$_GET['word'];

Calling a php function from Javascript and using a javascript var in the php code

JavaScript
function calcPrimesLoop() {
var primes = document.getElementById('primes');
primes.appendChild(document.createTextNode('\n'+this.prime.nextPrime()));
$.ajax({
url: "/test.php",
type: "post",
data: {prime: this.prime.nextPrime()},
success: function(data) {
}
});
calcPrimesDelay = setTimeout('calcPrimesLoop()', this.delay);
}
Php
<?php
$content = $_POST['prime'];
$fn = "content.txt";
$content = stripslashes('prime'"\n");
$fp = fopen($fn,"a+") or die ("Error opening file in write mode!");
fputs($fp,$content);
fclose($fp) or die ("Error closing file!");
?>
So this is all the relevant scripting I think. I have a script that can get prime numbers and it works perfectly. But now I want to record these numbers on a text file. This is how I am trying to do it but I am having no success at all. Thank you. The issue is the numbers aren't being recorded.
I added an alert the Ajax is working. But when I add a form to the php script and submit it that works. So the ajax and php scripts are not working together as such.
You should read up about AJAX and see how you can pass information to a serverside page using Javascript and retrieve the return value.
http://www.w3schools.com/ajax/default.asp
https://www.youtube.com/watch?v=qqRiDlm-SnY
With ajax and jQuery it is actually simple.
function calcPrimesLoop() {
var primes = document.getElementById('primes');
primes.appendChild(document.createTextNode('\n'+this.prime.nextPrime()));
$.ajax({
url: "myScript.php", // URL of your php script
type: "post",
data: {prime: this.prime.nextPrime()},
success: function(data) {
alert("success");
}
});
calcPrimesDelay = setTimeout('calcPrimesLoop()', this.delay);
}
myScript.php :
<?php
$content = $_POST['prime'];
...
You should definately look for Asynchronous JavaScript and XML.
You can choose between using AJAX with a Javascript function, or simplify your life with jQuery
Here is a sample:
//STEP ONE: INCLUDE THE LAST VERSION OF JQUERY
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
//STEP TWO, GET YOUR FUNCTION TO WORK:
function sendVariableTo(variable,url) {
$.ajax({
url:url, //Or whatever.php
type: "GET", //OR POST
data: { myVar: variable}, //On php page, get it like $_REQUEST['myVar'];
success:function(result){
//If the request was ok, then...
alert(result) //Result variable is the php page
//output (If you echo "hello" this alert would give you hello..)
},
});
}
Hope this helped, bye !

How to send a JQuery Variable to another PHP page via dblclick()?

So guys, I made a listbox and if I dblclick to an item the value of it gets saved into "val", but I can't send it to the next PHP File. I also alerted "val" - the value is really saved in it. I also get the function succes displayed in the browser console. what to do?
thanks
My Function:
$(document).ready(function () {
$("option").dblclick(function () {
var lb = document.getElementById("liste");
var val = lb[lb.selectedIndex].value;
$.ajax({
type: 'POST',
url: 'about.php',
dataType: 'HTML',
data: {
aufid: val
},
success: function (data) {}
});
});
});
PHP Code in about.php:
$id = $_POST['aufid'];
Can you try to see what variables are in the $_POST superglobal?
print_r($_POST);
try to set the url your full adrees
url: 'http://myadress.com/about.php',
java script is running on your local computer so it might send the request to you own pc where no about.php exist

Categories

Resources