Reputation: 902
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.
Upvotes: 0
Views: 1538
Reputation: 1096
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'];
}
Upvotes: 0
Reputation: 1501
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.
Upvotes: 1
Reputation: 6969
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>
Upvotes: 0