Call php function from javascript and send parameter - javascript

I would like to send 'ID' to JS function then send the same ID again from JS function to php function.
Please tell me what is the wrong in my code!
<script type="text/javascript">
function deleteclient(ID){ //I receive the ID correctly until now!
var x = "<?php deleteclient11('ID');?>";
return false;
}
</script>
<?php
function deleteclient11($x)
{
echo "$x";
}
?>

You need to use AJAX, it's easy with jQuery or another library, so I'll demonstrate with jQuery.
javascript
var deleteClient = function(id) {
$.ajax({
url: 'path/to/php/file',
type: 'POST',
data: {id:id},
success: function(data) {
console.log(data); // Inspect this in your console
}
});
};
php file
<?php
if (isset($_POST['id'])) {
deleteClient11($_POST['id']);
function deleteClient11($x) {
// your business logic
}
}
?>
More info: jQuery.ajax()

Related

jQuery ajax not working when trying to call php function

I'm trying to call php function from my JavaScript script. I've read several questions on how to call a php function using jQuery ajax. I simply copied most of the content and adapted it to fit my script, but somehow it's not working.
Here's my code:
var var1 = document.getElementById("tag").value;
var id = tag.id;
var var3 = tag.checked;
var test = $.ajax({
url: '../PHP/phpFunc.php',
type: 'GET',
data: {param1: var1, param2: id, param3: var3},
complete: function() {
if(window.console) {
console.log("success");
}
},
error: function() {
if(window.console) {
console.log("Error");
}
}
})
and the php code:
<?php
echo "<script>
console.log(\"test\")
</script>";
$var1= $_GET['param1'];
$var2 = $_GET['param2'];
$var3 = $_GET['param3];
$var4 = '../XML/user/'. $var1.'.xml';
?>
the "success" is being printed when the JS function is executed, but php code never returns the desired output.

Wordpress Ajax returns a 404 error

I want to develop a Wordpress plugin. So, I want to call Ajax function when I click on button in my php code.
This is my php code:
function unilang_translation_page() {
echo '<div class="wrap"><h1>Translations of strings</h1> </div>';
$unilang_table_strings = new Unilang_Table_Strings;
$unilang_table_strings->prepare_items();
$unilang_table_strings->display();
$_SESSION['store_table_strings'] = serialize( $unilang_table_strings );
echo "<a type='button' class=\"button button-primary\" onClick=\"Utility.saveStringTranslations();\">Submit Changes</a>";
}
And this is my javascript file:
var Utility = {
saveStringTranslations: function() {
$.ajax({
type: "POST",
url: "/unilang/php/unilang-save-string-translations.php",
success: function(data) {
alert(data);
},
error: function(error) {
alert(error);
}
})
}
}
When I click on the button the browser console returns this:
I tried to change path but it doesn't works.
How can I set my plugin path in the URL?
Try declaring a JavaScript variable in your plugin PHP file like below
<script> var plugin_url = '<?php echo plugins_url( '/unilang/php/unilang-save-string-translations.php', __FILE__ ) ?>'; </script>
and call the plugin_url variable in the AJAX URL path - url: plugin_url + "/unilang/php/unilang-save-string-translations.php".
Hope this helps and you can read more here - https://codex.wordpress.org/Function_Reference/plugins_url.

How can I pass Javascript array to a PHP array on button click?

I am having trouble passing a Javascript array to a PHP array on the same page when the submit button is pressed. I have seen discussion of JSON.stringify and json_encode on other posts, but I am not sure how to use those functions with my code.
JS:
<script>
var kegs = [];
var textarea = document.getElementById("your_textarea");
$("#kegId").on('keyup', function (e) {
if (e.keyCode == 13) {
kegs.push($(this).val());
$("#kegId").val("");
textarea.value = kegs.join("\n");
};
});
</script>
PHP:
if (!isset($_POST['btn-addkegs'])) {
//I want to set the Javascript array 'kegs' to a php variable here
Using Ajax will do it for you! I wrote this code that sends an array to PHP on the same page. Once you get the array in PHP you can do whatever you want with it :).Just copy and paste this file and called it index.php to see the result. This will totally help you!
<?php
$data = array();
if(isset($_POST['myArray']) && !empty($_SERVER['HTTP_X_REQUESTED_WITH'])){
$data = 'You array is: ' . $_POST['myArray'];
echo json_encode($data);
die();
}
?>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<div id = "random"></div>
<script type = "text/javascript">
$(document).ready(function() {
var arr = [2,4,5,6,7];
var myArray = JSON.stringify(arr);
$.ajax({
url: "index.php",
method: "POST",
dataType: "json",
data: {myArray: myArray},
success: function (result) {
alert("result: " + result);
console.log(result);
$("#random").html(result);
}
});
});
</script>
</body>
</html>
This can be achieved by using ajax(), its syntax is:
$.ajax({
url: 'process.php', // file where data processing is done
type: 'POST',
data: {
var1 :val1,
var2 :val2
// parameter set
},
success: function(response){ // response from process.php
// do your stuff here
}
});
Read more about ajax
As you are using the jquery
var jsArray = makeJavascriptArrayhere //
$.ajax({
url: urlToPhpFile, // file where data processing is done
type: Method,
data:jsArray,
success: function(response){ // response from process.php
// do your stuff here
}
});
now in your php file
var_dump($_POST); //see on network liner tabs

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 !

PHP Function with jQuery AJAX?

I have a question regarding, PHP functions, jQuery and AJAX.
If I have a button in my php index like this:
<input type="submit" value="Download" id="download"/>
And I have another php file (dubs.php) that contains this:
<?php
function first(){
echo 'first';
}
function second(){
echo 'second';
}
?>
And my jQuery, like this:
$(document).ready(function(e) {
$("#download").click(function(){
$.ajax({
type: "GET",
url: "dubs.php",
});
});
});
How do I tell my AJAX request to select for example the second function?
I have no idea on how to do this, I've tried it with "success: first()" or with "success: function(){ first() }" but that did not work.
In your ajax pass some params to identify which function you want to use like this
$("#download").click(function(){
$.ajax({
type : "POST",//If you are using GET use $_GET to retrive the values in php
url : "dubs.php",
data : {'func':'first'},
success: function(res){
//Do something after successfully completing the request if required
},
error:function(){
//If some error occurs catch it here
}
});
});
And in your php file
you can retrive the values in data send via ajax and do the following
if(isset($_POST['func']) && $_POST['func']=='first'){
first();
}
else{
second();
}
This is what I would do:
Your PHP:
<?php
function first(){
echo 'first';
}
function second(){
echo 'second';
}
if (isset($_POST["first"])) first();
if (isset($_POST["second"])) second(); //add 'else' if needed
?>
your jQuery:
$.post("dubs.php", {"first":true}, function(result) {
$("#someDivToShowText").text(result);
});
Then, according to the object you send to $.post, the php file will know which function to run.
Try this in your PHP page:
<?php
function first(){
echo 'first';
}
function second(){
echo 'second';
}
switch($_POST['func']) {
case "first":
first();
break;
case "second":
second();
break;
default:
// Define your default here }
?>
and this in your JS:
$(document).ready(function(e) {
$("#download").click(function(){
$.ajax({
type: "GET",
url: "dubs.php",
data: {'func':'first'}
});
});
The func variable will tell php which function to run!
});
why don't you try to pass with data:{func:f1} and get it on php side and if f1 is there then fire the first function. Although you can send multiple:
jQuery:
$("#download").click(function(e){
e.preventDefault(); // <----stops the page refresh
$.ajax({
type: "GET",
url: "dubs.php",
data:{'func':'f1'}
});
});
PHP:
<?php
function first(){
echo 'first';
}
function second(){
echo 'second';
}
if(isset($_GET['func']=='f1'){
first();
}else{
second();
}
?>
JS
$("#download").click(function(){
$.ajax({
type: "GET",
url: "dubs.php",
data: {'function':'first'}
});
});
PHP
call_user_func($_GET['function']);
NOTE
Be careful with $_GET parameters, better check first the contents of $_GET

Categories

Resources