How can we apply both JavaScript and PHP to a button? - javascript

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
});

Related

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 PHP function when clicking <button type="submit"> [duplicate]

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

Call a php from another php using ajax

I'm trying to call a php from ajax, so I wrote this on my first page (index.php):
<script type="text/javascript">
function valid(id) {
var element = document.getElementById(id);
$.ajax({
url: 'valid.php',
type:'POST',
data:
{
url: element.children[0].childNodes[0].nodeValue
},
success: function(msg)
{
console.log('done 1');
}
});
}
</script>
and here is my second one (valid.php):
<script type="text/javascript">
console.log('done 2');
</script>
<?php
if (isset($_GET['url']))
{
try
{
$bdd = new PDO('mysql:host=host;dbname=dbname;charset=utf8', 'id', 'password');
$bdd->exec("INSERT INTO sometable (url)
VALUES (".$_GET['url'].");");
}
catch (Exception $e)
{
die();
}
}
?>
But when I call my function, it doesn't seem to call valid.php even if the console show "done 1", "done 2" doesn't appear anywhere by the way and the database stay unchanged, like valid.php just doesn't run.
How may I fix that? Thank you!
Since you are using POST, you need to retrieve your data using $_POST rather than $_GET.
In valid.php if you are expecting isset($_GET['url']) which is a GET parameter but your AJAX request is sent via POST. You should change that to isset($_POST['url']).
Regarding the console.log('done 2'); on valid.php it won't get executed unless you append that to the body of index.php and evaluate that specific script but it is redundant because console.log('done 1'); refers to the completion of valid.php request.
Edit: On your insertion query you have $_GET['url'] and it should be $_POST['url'].

Passing values from jQuery to PHP in same page instantly

I have written a PHP program to confirm deletion of data through jQuery confirm message (Refer: http://rathur.fr/jQuery/MsgBox/) and record the result back to the same page itself instantly. If the page refreshes, it'll return back its state to previous.
The part of line is below:
print "
<script type='text/javascript'>
$(document).ready(function(){
$.msgbox('<br/>Are you sure you want to delete the selected record from the database?', {
type : 'confirm'
}, function(result){
$('#output').text(result);
var output = result;
});
});
</script>";
I want to get the result of the action button to PHP variable instantly, like below (just a trial):
$x = $_SESSION['output']; OR
$x = $_POST['output']; OR
$x = print "<div id=\"output\"></div>"; OR
$x = some_function(output);
Please help me, or suggest if there is other better options.
Here is a simple Ajax call to a Php File by an event : Click on a button.
Javascript client side :
$("body").on("click", "#mybutton", function() {
var mydata = $("#form").serialize();
$.ajax({
type: "POST",
url: "/api/api.php",
data: {data : mydata},
timeout: 6e3,
error: function(a, b) {
if ("timeout" == b) $("#err-timedout").slideDown("slow"); else {
$("#err-state").slideDown("slow");
$("#err-state").html("An error occurred: " + b);
}
},
success: function(a) {
var e = $.parseJSON(a);
if (true == e["success"]) {
$("#action").html(e['message']);
// here is what you want, callback Php response content in Html DOM
}
}
});
return false;
});
Next in your Php code simply do after any success function :
if ($result) {
echo json_encode(array(
'success' => true,
'msg' => "Nice CallBack by Php sent to client Side by Ajax Call"
));
}
You should use jQuery to POST the data to a PHP script using AJAX if you want to use the second pass.
http://api.jquery.com/category/ajax/ has many functions and tutorials on writing AJAX functions and handling return data. In particular, look at the post() function.

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