This question already has answers here:
How to put php inside JavaScript?
(7 answers)
Closed 3 years ago.
Here I have an < a ... onclick='show(); / a >. I want to add my php code to to js function, I mean to get action after click.
include($_SERVER['DOCUMENT_ROOT'] . '/model/action.php');
?>
I'm going to put php code in this script
<script>
document.getElementById("show").onclick = function() {show()};
function show() {
document.getElementById("numb").style.display="block";
<<<HERE>>>
}
</script>
With the addition of jQuery you can use ajax function to call a php script
<script>
$.ajax(
'request_ajax_data.php',
{
success: function(data) {
alert('AJAX call was successful!');
alert('Data from the server' + data);
},
error: function() {
alert('There was some error performing the AJAX call!');
}
}
);
</script>
Related
This question already has answers here:
PHP code is not being executed, but the code shows in the browser source code
(35 answers)
Ajax call returns entire page rather than just the echo value
(1 answer)
Closed 2 years ago.
I have been trying to return an alert of a value in a php function using AJAX. However, the alert returns the entire php script, instead of looking for where 'echo' is used. Here is my ajax call in JS:
function sendEncryptionToServer(thisData) {
$.ajax({
url: 'http://myurl.com/encrypt.php',
type: 'POST',
data: { method : "encryptData", dataInQuestion : "Hello" },
success: function(response){
alert(response);
console.log("SUCCESS");
},
error: function(response) {
alert(response);
console.log("ERROR");
}
});
}
And here is my php file
<?php
//Encrypt
if(isset($_POST['dataInQuestion']) && $_POST['method'] == 'encryptData')
{
$data = json_encode($_POST['dataInQuestion']);
$ciphertext = "fakecipher";
$api_key = "fakekey";
$encryptedData = openssl_encrypt($data, "AES-128-CBC", $ciphertext + $api_key, OPENSSL_RAW_DATA, $ciphertext);
$returnedEncryptedData = base64_encode($encryptedData);
echo json_encode($returnedEncryptedData); //This shows the encrypted string
}
//Decrypt
if(isset($_POST['dataInQuestion']) && $_POST['method'] == 'decryptData')
{
$data = json_encode($_POST['dataInQuestion']);
$ciphertext = "fakecipher";
$api_key = "fakekey";
$decryptedData = openssl_decrypt($encryptedData, "AES-128-CBC", $ciphertext + $api_key, OPENSSL_RAW_DATA, $ciphertext);
echo $decryptedData;
}
?>
What ends up happening is my alert displays my entire php file, from start to finish. I thought it would look into the isset and echo out the response based on the data object? If it means anything, I am running a local server via node.JS, but the http:/myurl.com/encrypt.php exists on a real server.
When I click a button:
I need the JavaScript to perform some function.
Also run PHP code as well.
How can we achieve this?
PHP is only run by the server and responds to requests like clicking on a link/button (GET) or submitting a form (POST).
HTML & JavaScript is only run in someone's browser.
<html>
<?php
function PhpFunction() {
echo 'A php function';
}
if (isset($_GET['JsFunction'])) {
PhpFunction();
}
?>
Hello there!
<a href='index.php?JsFunction=true'>Run PHP Function On Click Of This Link</a>
</html>
Alternatively ,
You can create a ajax request to run a php code in your server..
Ajax can help you to send an asynchronous request to the server that php (or other) can catch, in this way you can implement and play with some callback functions
$.ajax({
url : "yourScript.php", // the resource where youre request will go throw
type : "POST", // HTTP verb
data : { action: 'myActionToGetHits', param2 : myVar2 },
dataType: "json",
success : function (response) {
//in your case, you should return from the php method some fomated data that you //need throw the data var object in param
data = toJson(response) // optional
//heres your code
},
error : //some code,
complete : //...
});
in your php script, you'll receive the request posted throw the superglobal vars like POST (for this example)
<?php
$action = (string)$_POST['action']; //this is unsecure, its just for the example
if("myActionToGetHits" == $action) {
//here you have to call your php function and so on..
$data = hitsMonth();
echo $data;
exit;
}
here is html
<a href="#" onclick="javascript:functionName(arg1, arg2);">
This is a basic example to do it, there are lots of ways to do.
Have javascript do the submit:
function button1() {
// js code here
var formelt = document.getElementById("form1");
formelt.submit(); // this will submit the form to server
}
Example =>
<button class="btn-test">Btn Test</button>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
jQuery('.btn-test').click(function() {
js_do_something();
php_do_something();
});
function js_do_something() {
console.log('something done from js');
}
function php_do_something() {
console.log('something done from php');
jQuery.ajax({
type: "POST",
url: 'you_php_file.php',
data: {param: 'btn-test-click'},
success: function () {
console.log('success');
}
});
}
</script>
There you have how to execute a php function with on Onclick.
Execute PHP function with onClick
You can execute a Javascript function assuming you´re using jQuery like this:
jQuery('#id-button').on('click', function(){
// your function body
});
This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 5 years ago.
I inserted an onclick to my button but don't know where I'm going wrong here but it seems like the function is fired each time the page is loaded.
How can I call the function ONLY when clicking on the button itself
<button type="submit" class="btn btn-primary" onclick="<? $query = DB::update('ads')->set(array('sale_agreed' => '999'))->where('id_ad', '=', $msg_thread->ad->id_ad)->execute(); ?>"><?=_e('ACCEPT This Offer')?></button>
Any take on this? Thanks ;-)
You can make use of jQuery Ajax to perform this operation.
Add a button with some id.
<button id="click-button"></button>
Inside your script tag.
$(document).read(function(){
$("#click-button").click(function(){
$.ajax({
url: "remote-file.php",
method:"POST",
data:"token=buttonclick",
success: function(result){
if(result != "fail"){
//Perform actions with the results...
}
}});
});
});
In you PHP remote-file.php
<?php
if(isSet($_POST['token']) && $_POST['token'] == 'buttonclick'){
$result = myFunction();
echo $result;
}else{
echo "fail";
}
function myFunction(){
// Perform your DB actions...
return true; //Return your data
}
?>
You can't use php functions from client side. The attribute "onclick" fires a javascript funciont, not a php one.
In order to execute a php function with onclick, you have to make an Ajax request to the server.
$('.button').click(function() {
$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
.success(function( msg ) {
alert( "Data Saved: " + msg );
});
});
In the "url" variable you have to put the url to your php script, and the data object contains all the PHP $_REQUEST parameter to be send to the script. The success function executes once the script is complete.
Button click is client side whereas PHP is server side, but you can achieve this by using AJAX.
$('.button').click(function() {
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
In your PHP file:
<?php
function abc($name){
//your code here
}
?>
You cant add php functions to client side button clicks.
You should get your PHP to check if the page has been submitted and then run your function
This question already has answers here:
using jquery $.ajax to call a PHP function
(6 answers)
Closed 7 years ago.
This seems straightforward, but I can't get it to work. I have a button, when it's clicked I'd like to execute a php function which is defined in the same file as the button. My code is below, I get the "clicked" alert when the button is clicked, but no alert on response from the function.
//this is in myfile.php
<?php
echo '<button type="button" name="save_button" onclick="save()">Save</button>';
?>
<script type="text/javascript">
function save()
{
alert("clicked");
$.ajax({
url: 'myfile.php',
type: 'post',
data: { "set_description": ""},
success: function(response) { alert(response); }
});
}
</script>
<?php
function set_description() {
return "a string";
}
?>
Change the type of the jquery Ajax code from post to get since you want to use the response, else I can't see something wrong there
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 8 years ago.
My code doesn't show errors, but also doesn't work as it should. The output from the ajax call is working fine but I just can't get anything out of the onClick, no errors message, nothing.
The HTML
<div id="serials"></div>
<div id="accounts_info_key" style="text-align:left"></div>
The Ajax call
$(document).ready(function() {
$('.tab2').click(function(){
var account_id = $('#account_id').val();
$.ajax({
url: 'ajax/account_info_serials_ajax.php',
type:'POST',
dataType: 'json',
data: 'account_id='+account_id,
success: function(response){
$('#serials').html(response.table),
$('#accounts_info_key').html(response.key),
$('.drop_down').hide();
},
error:function (xhr, ajaxOptions, thrownError){
alert(thrownError);
} // End of success function of ajax form
}); //end of ajax
});//close trigger
});//close whole function
The PHP
$response = '';
$response .='<div class="question">';
$response .='plop';
$response .='</div>';
$response .='<div class="drop_down">';
$response .='bob';
$response .='</div>';
$output_array = array(
'table' => $response,
'key' => $key,
'count' => $count
);
echo json_encode($output_array);
The jquery onclick
$(document).ready(function() {
$('#serials').on("click", ".question", function(e){
alert('smeg');
});
});
Please note, I am not asking how to do it, I am asking why my version is not working, it is NOT a duplicate question
I have created a fiddle that shows how it should be done in my opinion http://jsfiddle.net/6VtA8/.
$(document).ready(function () {
$('.tab2').click(function () {
var account_id = $('#account_id').val();
$.ajax({
url: '/echo/json/',
type: 'POST',
dataType: 'json',
data: {'something':'else'}
}).done( function (response) { $('#serials').html('<div class="question ">abcd</div>'); });
});
}); //close whole function
$(document).ready(function () {
$('#serials').on("click", ".question", function (e) {
alert('smeg');
});
});
There are multiple reasons that could cause your code to not work. It could even be the fact that your div (from some css rule) would end up having a height of 0 and therefore the event wouldn't trigger. So instead of debugging I chose to do a little rewriting.
You have to subscribe to the event click on #serials once it's in the dom. So when your ajax callback is over and that .question is in the dom, you subscribe to the click on #serials.