i'm new to this so i hope you could help me.
i'm try to build one page has the ability to add and remove from sqldb.
from some reason i have to send value from js to php and i try this basic code and it doesn't work .
<html>
<head>
<script src="resources/js/jquery-2.2.3.js"> </script>
</head>
<body>
<form method="get">
<input type="button" value="submit" name="submit" class="test">
</form>
<div id="state"></div>
</body>
<script type="text/javascript">
$('.test').click(passValue);
function passValue(e){
document.getElementById('state').innerHTML="button is clicked";
var js_var = "xml recevid";
var xhr = new XMLHttpRequest();
var url = 'test.php?js_var=' + js_var;
xhr.open('GET', url, false);
xhr.onreadystatechange = function () {
if (xhr.readyState===4 && xhr.status===200) {
document.getElementById('state')xhr.responseText;
}
}
xhr.send();
}
</script>
<?php
if (isset($_GET['js_var'])) $php_var = $_GET['js_var'];
else $php_var = "<br />js_var is not set!";
echo $php_var;
?>
USE $php_var ="<script type='text/javascript'>document.write('js_var');</script>";
NOTE THAT js_var shoul be a global variable, not local one.
Related
I have an html form displaying a series of checkboxes. The checkboxes (an array called "checkbox" is ) are created using a loop in php. I want to use this array for some background processing.
Trying to use AJAX as below, but I am not able to get it working.
Please help!
Here is test.php: containing html form:
<!DOCTYPE html>
<script language="javascript">
function activate(checkbox){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
document.getElementById("ajaxState").innerHTML =xhttp.readyState;
document.getElementById("ajaxStatus").innerHTML =xhttp.status;
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("ajaxResponse").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", "process.php", true);
xhttp.setRequestHeader( "Content-Type", "application/json" );
xhttp.send(JSON.stringify(checkbox));
}
</script>
<html>
<body>
<form>
<?php
for ($i=0; $i<10; $i++){
echo "$i: ";
echo "<input type='checkbox' name='checkbox[".$i."]'></input><br>";
}
?>
<button type="button" name="button" onclick="activate(checkbox)" >Test</button>
</form>
<p>ajaxState: <span id="ajaxState"></span></p>
<p>ajaxStatus: <span id="ajaxStatus"></span></p>
<p>ajaxResponse: <span id="ajaxResponse"></span></p>
</body>
</html>
Output: Don't get any response.
process.php: decode json data and display the array
<?php
$data = file_get_contents( "php://input" );
$checkbox = json_decode( $data, true );
echo "Hello!<br>";
var_dump($checkbox);
?>
NOTE: If, in the button element, I use this.checkbox, var_dump returns NULL.
<button type="button" name="button" onclick="activate(this.checkbox)" >Test</button>
Response:
ajaxState: 4
ajaxStatus: 200
ajaxResponse: Hello!
NULL
Check the below code...
<!DOCTYPE html>
<script language="javascript">
function activate(){
/*getting all inputs*/
var inputs = document.getElementsByTagName("input");
var cbs = []; //will contain all checkboxes
var checked = []; //will contain all checked checkboxes
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == "checkbox") {
cbs.push(inputs[i]);
if (inputs[i].checked) {
checked.push(inputs[i]);
}
}
}
//then making a request
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
document.getElementById("ajaxState").innerHTML =xhttp.readyState;
document.getElementById("ajaxStatus").innerHTML =xhttp.status;
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("ajaxResponse").innerHTML = xhttp.responseText;
}
};
console.log(xhttp);
xhttp.open("POST", "process.php", true);
xhttp.setRequestHeader( "Content-Type", "application/json" );
xhttp.send(JSON.stringify(checked));//sending checked instead of checkbox
}
</script>
<html>
<body>
<form>
<?php
for ($i=0; $i<10; $i++){
echo "$i: ";
echo "<input type='checkbox' name='checkbox[".$i."]'></input><br>";
}
?>
<button type="button" name="button" onclick="activate()" >Test</button>
</form>
<p>ajaxState: <span id="ajaxState"></span></p>
<p>ajaxStatus: <span id="ajaxStatus"></span></p>
<p>ajaxResponse: <span id="ajaxResponse"></span></p>
</body>
</html>
used this to get all checkboxes
Better use Query see jQuery - AJAX
Here realization "Click on button and show id current button in ajax, for use in second needed tasks". If I right anderstand you.
{{--include jQuery CDN Library--}}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<button type="button" name="1" id="test" >Test</button>
<button type="button" name="2" id="test" >Test</button>
<button type="button" name="3" id="test" >Test</button>
...
<style>
$("button#test").change(function(){
var id = $(this).attr('name');
$.ajax({
method: 'POST',
url: 'process.php',
data: {id: id}
})
.done(function(msg){
console.log('button: ' + msg);
});
});
</style>
And php file
<?php
$data = $_POST['id']
$checkbox = json_encode($data);
echo "Hello!<br>";
echo $data; // show id checkbox
?>
It is simpler realization codes, from same javascript codes
i have tried this code:
<script type="text/javascript">
var s = 0;
document.getElementById('text').value = "<?php echo phpVal[s];?>";
</script>
the problem is how can i put the (s) value into (PHP) code.
Here's more context:
<head>
<?php $s = ["a","b","c"]; ?>
<script type="text/javascript">
function doFun(ss){
var data = "<?php echo json_encode($s); ?>";
document.getElementById('t').value = s[ss];
}
</script>
</head>
<body>
<input type="text" id="t" name="t" />
<button type="button" id="b" name="b" onclick="doFun(0)">doFun</button>
</body>
You can't, by the time s has a value (on the client), the PHP code (on the server) has long-since completed.
What you do instead depends a lot on what your end goal is. You have a lot of options. Here are two of them:
Output the entire phpVal array/object to the client, and then index into it with s.
var s = 0;
var data = <?php echo json_encode(phpVal)%>;
document.getElementById('text').value = data[s];
Send s to the server via ajax, have the PHP code that runs in response to that request pick out the correct value from phpVal, and return that as the result of the ajax, putting it in the client-side input's value. For example:
JavaScript:
var s = 0;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById('text').value = xhr.responseText;
}
};
xhr.open("get-value.php?s=" + encodeURIComponent(s));
// You don't really need this ^
// for `0`, but many times when sending variables to the
// server, you do
xhr.send();
PHP for get-value.php (roughly):
<?php
header('Content-Type: text/plain');
$phpVal = /*...get the value however it is you do that...*/
echo $phpVal[$_GET['s']];
?>
But again it depends on what you're actually trying to do.
I'm trying to teach myself how to use AJAX with PHP. However, I am unable to get my (likely broken) AJAX code to change the value of my $things variable. Instead, what happens is the index.php page gets reloaded and a brand new button gets added. Here is my code:
<?php
$things = 0;
?>
<!DOCTYPE html>
<html>
<head>
<title>testing</title>
<script>
function changeMe()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("changetest").innerHTML=xmlhttp.responseText;
}
}
var things = "<?php echo $things; ?>";
things++;
xmlhttp.open("GET","index.php?things="+things,true);
xmlhttp.send();
}
</script>
</head>
<body>
<?php
echo "<p>Things = <span id=\"changetest\"" . $things . "</span></p>";
?>
<button type="button" onclick="changeMe()">Change Content</button>
</body>
</html>
Any clue as to where I'm messing up?
There are at least two problems I can see:
You are not using the variable you are sending back to the server $_GET['things'] anywhere. Instead you are always setting it to 0 so you will never see anything else;
You are posting to the original php file. That means that the response will be the complete html page, including the head, etc. You probably want a separate file to only send back what you really need.
An example of a separate php file would just be to echo out what was sent in:
<?php
echo 'I sent the number: ' . intval($_GET['things']);
And now you should make an ajax request to this file and not index.php.
You should remove the quotes around "<?php echo $things; ?>"; and make it var things = <?php echo "'".$things."'"; ?> instead.
i have a problem with my simple program in php that include an alert javascript.
This is the code:
<?php
function iva(){
$country='IT';
$vatnum=$_POST['n'];
$a="Work";
$b="NotWork";
$url='http://isvat.appspot.com/'.$country.'/'.$vatnum.'/';
$response = file_get_contents($url);
//global $a, $b;
if( $response == 'true' ){
echo $a;
}
if ($response != 'true'){
echo $b;
}
}
?>
<script>
function ivaz(){
alert("<?php iva() ?>");
}
</script>
<form method="post">
<input name="n" type="textarea" >
<input onclick="ivaz();" value="Validate" type="submit"> </input> </form>
My program take a value from input text box and pass the value to php script that return true or false in a javascript alert. The program work, but return previous value passed in input box.
Can someone help me to solve it?
Thanks guys.
No, it doesn't work that way. If you want to call a PHP function from Javascript without the page refreshing, you need an XMLHttpRequest.
Example:
<?php
// your php process when called by XMLHttpRequest
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$vatnum = $_POST['n'];
$country='IT';
$a = "Work";
$b = "NotWork";
$url = 'http://isvat.appspot.com/'.$country.'/'.$vatnum.'/';
$response = file_get_contents($url);
//global $a, $b;
if( $response == 'true' ){
echo $a;
} else {
echo $b;
}
exit;
}
?>
<form method="post" id="form1">
<input name="n" type="text" id="n" />
<input value="Validate" type="submit">
</form>
<script type="text/javascript">
// when the form is submitted
document.getElementById('form1').addEventListener('submit', function(e){
e.preventDefault();
var n = document.getElementById('n').value; // get the textbox value
var xmlhttp = new XMLHttpRequest();
var params = 'n=' + n;
var php_url = document.URL;
xmlhttp.open('POST', php_url, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var response = xmlhttp.responseText;
alert(response); // alert the server response
}
}
xmlhttp.send(params);
});
</script>
Remove onclick="ivaz();" from input tag
You cannot run the php script without reloading the page as php is generated serverside and javascript runs clientside.
I need to retrieve an attribute from an image. This attribute then needs to be send to the original page. I use a .load to load the page where you click on an image, which then retrieves the attribute, on the "internal" page.
So what I basically want:
You get on the "internal page"
You click on an image from the ajax-loaded "external page".
The attribute "src" is then loaded into a variable
This variable gets send back to the "internal page"
I can use the sent variable.
This is what I got so far:
External page:
<script type="text/javascript">
$(document).ready(function() {
$(".imgid").click(function() {
var imgname = $(this).attr('src');
var xhr;
if (window.XMLHttpRequest) xhr = new XMLHttpRequest(); // all browsers
else xhr = new ActiveXObject("Microsoft.XMLHTTP"); // for IE
var url = 'internalpage.php?js_var=' + imgname;
xhr.open('GET', url, false);
xhr.onreadystatechange = function () {
if (xhr.readyState===4 && xhr.status===200) {
var div = document.getElementById('update');
div.innerHTML = xhr.responseText;
}
}
xhr.send();
// ajax stop
});
});
</script>
<fieldset>
<label for="portal_id">Afbeelding Portal</label>
<?php $photos = Beeldbank::find_all(); ?>
<?php $rows=3; $cols=4;$i=1; $row_counter=0; echo '<table>'; foreach($photos as $photo): if($row_counter<$rows){
if($i==1) { echo '<tr>'; }
echo '<td>'.'<img src="../'.$photo->image_path().'" width="125" class="imgid" />'.'</td>';
echo '<td>'.'<input type="hidden" id="filename" name="filename" value="'.$photo->naam.'" />'.'</td>';
if(($i%$cols)==0){ echo '</tr><tr>'; $row_counter++; }
}
$i++;
endforeach;
echo '</table>'; ?>
</fieldset>
Internal page:
<script type="text/javascript" src="../javascripts/SelectImage.js"></script>
Afbeelding Portal<br />
<button id="select_portal" type="button">Selecteer Afbeelding</button>
<div id="dialog-form" style="display:none; position:absolute; width:auto; height:auto;"></div>
The js file:
$(document).ready(function(){
$( "#select_portal" )
.button()
.click(function() {
$("#dialog-form").css("display", "block");
$("#dialog-form").css("top", "50%");
$("#dialog-form").css("left", "50%");
$("#dialog-form").css("backgroundColor","white");
$("#dialog-form").load("externalpage.php");
});
});
If I understood your question right you need to post the result back to a php page. So you can use jQuery POST to send a value you have read using jQuery.