Update data through Ajax - javascript

I have the below code on href click I'm calling a javascript code in which an ajax is being called which returns the value of array $ss in json format . Now I want to know how can I update the value of $ss via ajax.
<div class="white" id="white" style="display:none">
<?php
foreach ($ss as $key => $value){
?>
<a href='javascript:void(0);' onclick='callAjax('<?php echo $key; ?>')'>
<?php
echo $value;
?>
</a>
<?php
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
var res;
function on(id){
//alert('hi '+id);
$.ajax({
url: 'ajax.php', //This is the current doc
type: "GET",
data: ({a: id }),
success: function(data){
res = data;
//alert(res);
document.write(res);
}
});
}
</script>
And ajax.php files return array values for $ss.
I understood how to update data of normal div through ajax but encountering problem to pass the data returned by ajax call to update array value.

1- Lets be clear javascript will not replace the content of a php variable. 2- Even if so you will not be able to regenerate the html you need this way.3- after you receive your variable you need to update the html instead.
PS: Surely you can update the variable on the server side when you receive that ajax call,that also needs some requirements(the variable is global and accessible inside the php file...),but from what I have understood you want to change it with javascript which is not possible.

Your ajax must like this...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
var res;
function on(id){
//alert('hi '+id);
$.ajax({
url: 'ajax.php', //This is the current doc
type: "GET",
data: {a: id },
success: function(data){
res = data;
//alert(res);
document.write(res);
}
});
}
</script>

I think you can't.
PHP code is run server-side, and jQuery runs on the client. The way to update a PHP variable from jQuery is to have a jQuery call which submits to the PHP page, and have the PHP look for it.
$ss = 'ss value';
if exists($_POST['ss']) {
$ss = $_POST['ss'];
}

Related

How to pass variable from php for() to ajax when clicking a button?

when clicking (.refresh)button、how would you pass $data_name to ajax which you'll get by for() in body field of php script?
I would like to pass the variable for selecting data from database.
2Scripts:
(1) html formated .php file>
ajax written in header field,
php for() written in body field
(2) SQL select script in php, added
$dataname= $_POST['dataname'];
In for() I'm getting data from DB and showing data tables, DATA A~C.
When clicking the button for each data, I would want to get the new data from data base.
I was able to get it, just writting "A" for Ajax, but I would want to pass variable for many tables.
[enter image description here][1]
[1]: https://i.stack.imgur.com/zpJ7B.png
<head>
<script>
$(document).ready(function(){
$('.refresh').click(function(){
$.ajax({
// 通信先ファイル名
url: "select.php",
type: "POST",
data: ({"data_name": $data_name}),
success: function(data) {
//more code
},
error: function(data) {
//more code
}
});
</script>
</head>
<body>
<?php
//more code for(){  getting $data_name(A、B、C)here >
echo <<<EOD
<button class='refresh'>REFRESH DATA</button>
<table class='show'></table>
EOD;
?>
</body>
You can use a different PHP to return the JSON or the same.
So if you want to use the same script you basically want to send a JSON with the data when your PHP script gets a POST.
So you have to check:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// The request comes from Javascript doing POST
// Query Database and return a JSON with the field "data_name"
} else {
// Render your form like now you're doing now, the request com from the browser loading the page
}
//select.php
<?php
$data= $_POST["data_name"];
echo json_encode( $data);
?>
<script>
$(document).ready(function(){
$('.refresh').click(function(){
$.ajax({
// 通信先ファイル名
url: "select.php",
type: "POST",
data: ({"data_name": $data_name}),
success: function(data) {
// getting $data_name(A、B、C)here
},
error: function(data) {
//more code
}
});
</script>

post in ajax with php get me undefined index

i want to send/pass data from the client to server by (ajax to php) but when i try this code
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
$.ajax({
type: 'post',
url: 'loo.php',
data: { data: 'some data' },
success: function(response,w) {
console.log(w);
}
});
</script>
<?php
echo $_POST['data'];
?>
in my browser i got success print out which mean that the javascript code is working fine i guess , by in php i got Undefined index
p.s my file name is loo.php all the code is in the same file
edit: i have tried to separate my files like this:
my loo.php file:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
$.ajax({
type: 'post',
url: 'test.php',
data: {data: 'some data'},
success: function (response, w) {
console.log(w);
}
});
</script>
my test.php file:
<?php
echo $_POST['data'];
?>
still got undefined index
p.s. i navigate Manual to test.php file after i run loo.php file
You get this error because when loading the page the POST request has not yet been sent. So show the submitted data only if it exists, otherwise, show the JavaScript code.
<?php
if (isset($_POST['data'])) {
die($_POST['data']);
}
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
$.ajax({
type: 'post',
url: 'loo.php',
data: {data: 'some data'},
success: function (response, w) {
console.log(w);
}
});
</script>
Try this.
<?php
$data = json_decode(file_get_contents('php://input'), true);
echo $data['data'];
?>
Try this
Html file
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="data_value"></div>
<script type="text/javascript">
$( document ).ready(function() {
$.ajax({
type: 'post',
url: 'loo.php',
data: { data: 'some data' },
success: function(response,w) {
$("#data_value").html(response);
}
});
});
PHP file (loo.php)
<?php
print_r($_POST);
?>
try to change the handler this way:
if(isset($_POST['data'])){
function return_data() {
die(json_encode($_POST['data'])));
}
return_data();
}
Answer after you edit the question:
$_POST is the array sent by the HTTP Post request. so if the request to the page named test.php or whatever is not HTTP POST Request the $_POST array will be empty. but the $_GET array may have some data if you sent them.
and navigation to a page is a get request to that page unless you used a form with method="post".
so what you are doing with ajax call is correct. but navigating to test.php manually without a form with post method is not gonna fill the $_POST array.
because when you make the Ajax call, it is done, it just makes the post-call correctly and everything is ok but when you navigate to that page it is a get request and it won't fill the $_POST array.
to do so, you don't need ajax at all. you can have this form
<form method="POST" action="test.php">
<input type="text" name="data" value="some data" />
<input type="submit" value="submit" />
</form>
so either you use ajax and handle whatever you want to handle in the ajax success method. or use form and send the request to the page and handle it there.
the answer to the question before the edit
If they are in the same file it won't work like that, because when the file loads the $_POST['data'] is not exists at all, and after you run the ajax call, it exists within that call, not in your browser window.
so you can check if $_POST['data'] exists so you are sending it from ajax call so you can return it and use it inside your ajax success function.
conclusion:
you cannot put them in the same file and expect ajax will load before the actual php.
it will first load the whole file then it will run the ajax.
the undefined index is from the server before you even see the HTML page.
A solution could be:
File with your html and ajax functions index.html
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
$.ajax({
type: 'post',
url: 'loo.php',
data: { data: 'some data' },
success: function(response,w) {
// use the response here
console.log(w);
}
});
</script>
and another with your logic loo.php
<?php
header("Content-Type: text/plain"); // if you want to return a plain text
// if you want to return json it could be header('Content-type: application/json');
echo isset($_POST['data'])? $_POST['data']: ''
?>

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.

Ajax call to insert to database not working

I'm trying to do an Ajax call on button click to insert to a database through a PHP file. I want to use AJAX to achieve this, but it does not show the alert dialog on success nor does it insert the data to the database. Here is the code I have:
AjaxTest.html:
<button type="button" onclick="create()">Click me</button>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js">
function create () {
$.ajax({
url: "AjaxTestRegistration.php",
type: "POST",
data: {
'bid': 10,
'kid': 20
},
success: function (msg) {
alert("!");
}
});
}
</script>
AjaxTestRegistration.php:
<?php
include "connection.php";
include "Coupon.php";
$bid = $_GET['bid'];
$kid = $_GET['kid'];
Coupon::insertCoupon($bid, $kid);
?>
If I try to enter AjaxTestRegistration.php manually in the browser like this: ajaxtestregistration.php?kid=10&bid=5, the row gets inserted into the database.
wWhat could be the problem with this code? How to rectify that?
Your PHP handles GET requests.
$bid = $_GET['bid'];
But your ajax function tries to POST
type: "POST",
The easiest here is to get your data by $_POST in php.
I think you should try $__REQUEST method of php and also use $_POST method if you use post from ajax
$bid = $__REQUEST['bid'];
$kid = $__REQUEST['kid'];

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 !

Categories

Resources