jQuery ajax not working when trying to call php function - javascript

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.

Related

Updating an input field with PHP vale in JavaScript

I want to update the value of an input field when I receive some information from an api. I tried using:
$('#txtFirstName').val($_SESSION['jUser']['first_name']);
But an error occurs due to the PHP not being able to run in a js file. How can I make this update otherwise? Is there a way in js to update the entire form and input fields without submitting?
I can't reload the entire window, because it will eliminate other information that the user of the website has put in.
1) put value into #txtFirstName from php script
// script.php code
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
echo $_SESSION['jUser']['first_name'];
}
// javascript code
function func(){
$.ajax({
type: "POST",
url: "script.php",
success: function (response) {
$('#txtFirstName').val(response);
},
error: function (e) {
console.log("ERROR : ", e);
}
});
}
2) put value into $_SESSION['jUser']['first_name'] from javascript
// javascript code
function func(){
var your_value = "some_value";
$.ajax({
type: "POST",
url: "script.php",
data: { va: your_value },
success: function (response) {
console.log("value setted to session successfully");
},
error: function (e) {
console.log("ERROR : ", e);
}
});
}
// script.php code
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $_POST['va'] !='') {
$_SESSION['jUser']['first_name'] = $_POST['va'];
echo "ok";
}
Why don't you just echo the value from php script and make an AJAX request from javascript to get the value ? This should be the recommended approach.
However, it can also be accomplished with the approach you've taken:
let first_name = <?php echo $_SESSION['jUser']['first_name']; ?>:
$('#txtFirstName').val(first_name);
For further reading, you can visit How do I embed PHP code in JavaScript?
.

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

Using ajax to send a JS variable, but how can I use PHP variables afterwards to my main file?

How can I use some PHP variables from the ajax-send.php to the index.php file? I use AJAX as shown below. Do I have to replace AJAX with something else?
index.php
$.ajax({
type: 'POST',
url: 'ajax-send.php',
data: { one: hash },
success: function(data) {
}
});
ajax-send.php
$token = $_POST['one'];
echo "ok"
$toINDEX = "use this in index.php"
Try this
Ajax
$.ajax({
type: 'POST',
url: 'ajax-send.php',
data: { one: hash },
success: function(data) {
var response = data;
//alert(data);To see what you have received from the server
}
});
PHP
if(isset($_POST['one'])){
$token = $_POST['one'];
echo "ok";
$toINDEX = "use this in index.php";
die();
}
In PHP just echo variable or json_encode array. In JS do the following:
var result = $.ajax({
url: this.fileUrl,
type: "POST",
data: data,
async: false,
dataType: 'json'
}).responseText;
Your vaiable is fully accessable.
take the variables in php sessions
//On page 1(ajax-send.php)
session_start();
$_SESSION['token'] = $_POST['one'];
//On page 2(index.php)
session_start();
$var_value = $_SESSION['token'];
You can simply echo the variable and then access it via javascript inside the success function.
But a better approach would be to json_encode the data. The beauty of this is that it will help you to pass multiple values/variables in a single echo. So
PHP
.
..
if(<all is okay>)
{
$toINDEX = "use this in index.php"
$data['result'] = 'ok';
$data['msg'] = $toINDEX;
$data['some_other_value'] = 'blah blah';
// notice how I'm able to pass three values using this approach
}
else
{
$data['result'] = 'notok';
}
echo json_encode($data);
Javascript
$.ajax({
type: 'POST',
url: 'ajax-send.php',
data: { one: hash },
dataType:'json',
success: function(data) {
if(data.result == 'ok')
{
console.log(data.msg);
console.log(data.some_other_value);
}
else
{
// something went wrong
}
}
});
The important thing to note here is dataType:'json' which tells the function to expect the returned data in json format.
EDIT:
As per you comment, you could do this
$toINDEX = "use this in index.php";
// now use the variable here itself
mysql_query("SELECT * FROM table WHERE column = '$toINDEX'");
.
.
if(<all is okay>)
{
$data['result'] = 'ok';
$data['msg'] = 'anything you would like to show the user';
$data['some_other_value'] = 'blah blah';
// notice how I'm able to pass three values using this approach
}
else
{
$data['result'] = 'notok';
}
echo json_encode($data);

Call php function from javascript and send parameter

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()

Categories

Resources