In the code below after user click in cancel button It will call the function botao_excluir(). Inside of this function I want to run the cancela_cielo() php function. But I know that is impossible to run PHP inside JavaScript. So Could someone please tell me a way to do this?
PHP
<?php
$id=$row['id_temp_transaction'];
if($row['status']!=9)
{
echo "<input type = \"button\" name=\"cancel\" value = \"Cancel\" onclick= \"botao_excluir()\" >";
}
?>
JavaScript
<script>
function botao_excluir()
{
var r=confirm("Press OK to confirm the cancel")
if (r==true)
{
<?php cancela_cielo($row['tid'], $row['numero_afiliacao'], $row['chave_utilizada']); ?>
alert("Transaction Canceled")
}
else
{
alert("Cancel aborted")
}
}
You can do this using ajax
this will send the request to page.php as example the request will be executed in php and the data will be returned.
function botao_excluir()
{
var r=confirm("Press OK to confirm the cancel")
if (r==true)
{
xhr = new XMLHttpRequest()
xhr.open("POST","page.php",false);
xhr.send();
// response will be assigned to data variable
data = xhr.responseText
alert("Transaction Canceled")
}
else
{
alert("Cancel aborted")
}
}
you can read more about ajax and php here
http://www.w3schools.com/php/php_ajax_php.asp
Related
i am try to load B.php from A.php after execution in the function and pass some data using a post array from A.php to B.php within same time.
code list as follows
A.php
<script type="text/javascript">
alert_for_the_fucntion();
window.location.href = "B.php";
function alert_for_the_fucntion() {
$.post("B.php", {action: 'test'});
}
</script>
B.php
<?php
if (array_key_exists("action", $_POST)) {
if ($_POST['action'] == 'test') {
echo 'ok';
}
}
?>
for testing purpose i tried to echo something in the B.php. but currently this is not working. have i done any mistakes? or is there any possible method to do this.
Your code does this:
Tells the browser to navigate to B.php (using a GET request)
Triggers a POST request using XMLHttpRequest
The POST request probably gets canceled because the browser immediately leaves the page (and the XHR request is asynchronous). If it doesn't, then the response is ignored. Either way, it has no effect.
You then see the result of the GET request (which, obviously, doesn't include $_POST['action']) displayed in the browser window.
If you want to programmatically generate a POST request and display the result as a new page then you need to submit a form.
Don't use location. Don't use XMLHttpRequest (or anything that wraps around it, like $.ajax).
var f = document.createElement("form");
f.method = "POST";
f.action = "B.php";
var i = document.createElement("input");
i.type = "hidden";
i.name = "action";
i.value = "test";
f.appendChild(i);
document.body.appendChild(f);
f.submit();
If you want to process the results in JavaScript then:
Don't navigate to a different page (remove the line using `location)
Add a done handler to the Ajax code
e.g.
$.post("B.php", {action: 'test'}).done(process_response);
function process_response(data) {
document.body.appendChild(
document.createTextNode(data)
);
}
Try this:
Javascript:
<script type="text/javascript">
window.onload = alert_for_the_fucntion;
function alert_for_the_fucntion() {
$.post("B.php",
{
action: 'test'
},
function(data, status){
if(status=="success"){
alert(data);
}
}
);
}
</script>
PHP
<?php
if(isset($_POST['action'])){
echo $_POST['action'];
}
?>
i have a simple form: when i submit it without javascript/jquery, it works fine, i have only one insertion in my data base, everything works fine.
I wrote some jquery to have result in ajax above the input button, red message if there was an error, green if the insertion was done successfully. I also display a small gif loader.
I don't understand why when i use this jquery, two loaders appear at the same time and two insertions are done in my database.
I reapeat that when i comment the javascript, it works fine, i'm totally sure that my php is ok.
$('#addCtg').submit(function () {
var action = $(this).attr('action');
var name = $('#name').val() ;
$('.messages').slideUp('800', function() {
$('#addCtg input[type="submit"]').hide().after('<img src="spin.gif" class="loader">');
$.post(action, {
name: name
}, function (data) {
$('.messages').html(data);
$('.messages').slideDown('slow');
$('.loader').fadeOut();
$('#addCtg input[type="submit"]').fadeIn();
});
});
return false;
});
I really don't understand why it doesn't work, because i use the 'return false' to change the basic behaviour of the submit button
Basic php just in case:
<?php
require_once('Category.class.php');
if (isset($_POST['name'])) {
$name = $_POST['name'] ;
if ($name == "") {
echo '<div class="error">You have to find a name for your category !</div>' ;
exit();
} else {
Category::addCategory($name) ;
echo '<div class="succes">Succes :) !</div>' ;
exit();
}
} else {
echo '<div class="error">An error has occur: name not set !</div>';
exit();
}
And finnaly my function in php to add in the database, basic stuff
public static function addCategory($name) {
$request = myPDO::getInstance()->prepare(<<<SQL
INSERT INTO category (idCtg, name)
VALUES (NULL, :name)
SQL
);
$r = $request->execute(array(':name' => $name));
if ($r) {
return true ;
} else {
return false ;
}
}
I rarely ask for help, but this time i'm really stuck, Thank you in advance
You're calling: $('.messages') - I bet you have 2 elements with the class messages. Then they will both post to your server.
One possible reason could be because you are using button or submit to post ajax request.
Try this,
$('#addCtg').submit(function (e) {
e.preventDefault();
var action = $(this).attr('action');
var name = $('#name').val() ;
$('.messages').slideUp('800', function() {
$('#addCtg input[type="submit"]').hide().after('<img src="spin.gif" class="loader">');
$.post(action, {
name: name
}, function (data) {
$('.messages').html(data);
$('.messages').slideDown('slow');
$('.loader').fadeOut();
$('#addCtg input[type="submit"]').fadeIn();
});
});
return false;
});
I am trying to make a ajax call and validate a input html field. But, instead of getting simple echo message. I am getting complete source code in responseText.
JavaScript
function checkUsername() {
document.getElementById("username").className = "thinking";
usernameRequest = createRequest();
if (usernameRequest == null)
alert("Unable to create request");
else {
var theName = document.getElementById("username").value;
var username = escape(theName);
var url= "checkName.php?username=" + username;
usernameRequest.onreadystatechange = showUsernameStatus;
usernameRequest.open("GET", url, true);
usernameRequest.send(null);
}
}
function showUsernameStatus() {
alert(usernameRequest.responseText);
if (usernameRequest.readyState == 4)
{
if (usernameRequest.status == 200) {
if (usernameRequest.responseText == "okay") {
document.getElementById("username").className = "approved";
document.getElementById("register").disabled = false;
}
else {
document.getElementById("username").className = "denied";
document.getElementById("username").focus();
document.getElementById("username").select();
document.getElementById("register").disabled = true;
}
}
}
}
checkName.php
<?php
$takenUsernames = array('bill', 'ted');
sleep(2);
if (!in_array($_REQUEST['username'],$takenUsernames )) {
echo 'okay';
} else {
echo 'denied';
?>
Previously, I tried to integrate PHP into tomcat, but I was advice it was not a good practice. TRIAL TO INTEGRATE PHP
What I can make out of this situation is that Tomcat is not parsing PHP file and instead it is returning the source code. I believe there should be a means for me to let tomcat parse php files and send the right response.
I have also tried with simple php code, with one statment <?php echo 'HELLO'; ?> and I still get the source code.
Thanks in advance.
NOTE : I do not know php, I am working an example from HEAD FIRST AJAX
you need to install PHP for Tomcat & set its path to compile it.see the below link for php configuration settings.
http://php-java-bridge.sourceforge.net/doc/tomcat6.php
http://www.studytrails.com/blog/php-on-a-java-app-server-apache-tomcat-using-quercus/
This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 1 year ago.
I have some information from my db that is being loaded onto my page, but I would like to be able to use an if statement regarding the value of this, and then assign a javascript value to be a boolean value. How can I go about this? (at the moment I am just printing the value)
<?php
if ($_SESSION['loggedin'] = true){
print_r($_SESSION['userlevel']); // THIS IS WHAT I WANT TO SPECIFY IN AN IF STATEMENT
}
?>
<script>
var userloggedin = false;
</script>
What I would like to do in pseudocode:
<script>
var userloggedin = false;
function somefunction(){
if (userloggedin == true){
//Do stuff...//
}
}
</script>
Sorry for my lack of knowledge on the subject, I'm only beginning to learn backend web development.
Have you tried searching the forum for any previous posts with regards to parsing PHP variables to javascript?
With a simple search I found a feed relating to parsing PHP variables to JavaScript here:
Get variable from PHP to JavaScript
Anyway, from my understanding of your problem does this serve as a suitable answer?
<?php
if ($_SESSION['loggedin'] == true){
$userLevel = $_SESSION['userlevel'];
$userLoggedIn = true;
}
else {
$userLevel = null;
$userLoggedIn = false;
}
?>
<script type="text/javascript">
var userLoggedIn = "<?php Print($userLoggedIn); ?>";
var userLevel = "<?php Print($userLevel); ?>";
if (userLoggedIn == true) {
if (userLevel == "levelOne") {
//Your code here
}
else if (userLevel == "levelTwo") {
//Your code here
}
else {
//Your code here
}
}
</script>
You can echo bits of Javascript code from PHP, like this:
<script>
var userloggedin = <?php echo ($_SESSION['loggedin'] ? 'true' : 'false'); ?>;
</script>
First change your if statement to use == double equal signs if you want the expression to work as expected. Then you can simply echo a variable into javascript as in example below:
Simple solution would be similar to:
<?php
if ($_SESSION['loggedin'] == true){
$logged_in = "true";
} else {
$logged_in = "false";
}
?>
<script>
var userloggedin = <?php echo $logged_in;?>;
</script>
You can set a javascript variable with a php value by:
<script>
var jsVar='<?php echo $phpVar ?>';
</script>
A simple solution would be just to echo variable value in script tag. But this is unsafe, because variable is global, meaning it can be modified in client-side console.
Better solution would be an ajax request and php script that returns some response, this way the variable is scoped to ajax response function, so it's safe from modifications. Here's an example:
...
echo json_encode($_SESSION['loggedin'] ? 'true' : 'false');
...
In javascript, you can use jquery .get() request:
$.get("userLoggedIn.php", function(data) {
var response = JSON.parse(data);
if(data === true) {
// user is logged in
}
else {
// not logged in
}
});
If it's important that this functionality is handled before anything else, an synchronous ajax request:
$.ajax({
url: "userLoggedIn.php",
async: false, // this makes request synchronous
success: function (data) {
var response = JSON.parse(data);
if (data === true) {
// user is logged in
} else {
// not logged in
}
});
Synchronous request means that client will wait for request to finish before doing anything else. It's not recommended to be used a lot, but sometimes it's the only way to go about.
I need to send the textbox value on anchor tag click to checkID.php and display the response sent from php page in html page. I tried using javascripts. But the page is redirected to checkID.php page. need to display in the very same html page.
<a href="#" onclick="javascript:fillContent('checkID.php'); ">
Check Availability
</a>
In form action I speceified as checkID.php.
Following is the javascript I used
<script language="javascript">
function fillContent(resource)
{
xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", resource, true);
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4) {
el = document.getElementById('availabilityResponse')
el.innerHTML = xmlhttp.responseText;
}
}
xmlhttp.send(null);
}
</script>
below is my php code
<?php
require_once('lib/nusoap.php');
$client=new nusoap_client("http://localhost/server.php?wsdl");
$error = $client->getError();
if ($error) {
return $error;
}
$alias=$_POST['id'];
$response = $client->call("checkAvailability", array("id" => $alias));
if($client->fault)
{
return $client->faultstring;
}
else
{
$error = $client->getError();
if ($error) {
return $error;
}
else {
return $response;
}
}
?>
how to get response and display in html page?
Not sure why its getting redirected, but in your PHP file -
Instead of
return $response;
Use
echo $response;
Always use echo instead of return in ajax cases
That code should not redirect to that page. Cancel the click action and see if that helps.
onclick="fillContent('checkID.php');return false"
I suggest you to use jquery. Its very simple
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$("#myID").on("click",function(){
$.ajax({ url: 'checkID.php',
type: 'post',
success: function(output) {
$("#availabilityResponse").html(output);
}
});
})
</script>
</head>
<body>
Check Availability
</body>
</html>