I know that PHP is a Server-Side and Javascript is Client-side , But I'm wondering if it's possible to do the following .
I have a javascript function that calls an Ajax call to a PHP file , Here is the code:
function reloadData(fileName){
$.ajax({
//I want to insert the fileName parameter before .php
url: '<?php echo $filePath ."/fileName.php";?>',
type: 'GET',
async: true,
success: function( data ){
//Do Some Thing With Returned Data.
}
});
}
I want to pass PHP file name to the reloadData function
reloadData('get_data');
So that the url within ajax will be:
url: 'get_data.php',
Is it possible?
Do like this, where you use the filename variable and split the url string like this ' + fileName + '
function reloadData(fileName){
$.ajax({
//I want to insert the fileName parameter before .php
url: '<?php echo $filePath ."/' + fileName + '.php";?>',
type: 'GET',
async: true,
success: function( data ){
//Do Some Thing With Returned Data.
}
});
}
As a note though, when PHP echo this server side you might need to do something like this
'<?php echo $filePath ."/"?>' + filename + '.php'
Set your filepath as a global variable in your js so that you can make use of it throught you code. Then make use of this variable like this in your function:
var filePath = "<?php echo $filePath ?>/";
function reloadData(fileName){
$.ajax({
//I want to insert the fileName parameter before .php
url: filePath + fileName.trim() + '.php',
type: 'GET',
async: true,
success: function( data ){
//Do Some Thing With Returned Data.
}
});
}
Just change
url: 'fileName.php',
To:
url: `${fileName}.php`,
Related
I am trying to send values to other page Using Ajax
But i am unable to receive those values , i don't know where i am wrong
here is my code
<script type="text/javascript">
function get_more_info() { // Call to ajax function
var fval = document.getElementById('get_usecompny').value;
var dataString1 = "fval="+fval;
alert(fval);
var sval = document.getElementById('country').value;
var dataString2 = "sval="+sval;
alert(sval);
$.ajax({
type: "POST",
url: "getmoreinfo.php", // Name of the php files
data: "{'data1':'" + dataString1+ "', 'data2':'" + dataString2+ "'}",
success: function(html)
{
$("#get_more_info_dt").html(html);
}
});
}
</script>
in alert i am getting those value but in page 'getmoreinfo.php' i am not receiving any values
here is my 'getmoreinfo.php' page code
if ($_POST) {
$country = $_POST['fval'];
$country1 = $_POST['sval'];
echo $country1;
echo "<br>";
echo $country;
}
Please let me know where i am wrong .! sorry for bad English
You are passing the parameters with different names than you are attempting to read them with.
Your data: parameter could be done much more simply as below
<script type="text/javascript">
function get_more_info() { // Call to ajax function
var fval = document.getElementById('get_usecompny').value;
var sval = document.getElementById('country').value;
$.ajax({
type: "POST",
url: "getmoreinfo.php", // Name of the php files
data: {fval: fval, sval: sval},
success: function(html)
{
$("#get_more_info_dt").html(html);
}
});
}
</script>
Or cut out the intermediary variables as well and use the jquery method of getting data from an element with an id like this.
<script type="text/javascript">
function get_more_info() { // Call to ajax function
$.ajax({
type: "POST",
url: "getmoreinfo.php", // Name of the php files
data: { fval: $("#get_usecompny").val(),
sval: $("#country").val()
},
success: function(html)
{
$("#get_more_info_dt").html(html);
}
});
}
</script>
No need to create 'dataString' variables. You can present data as an object:
$.ajax({
...
data: {
'fval': fval,
'sval': sval
},
...
});
In your PHP, you can then access the data like this:
$country = $_POST['fval'];
$country1 = $_POST['sval'];
The property "data" from JQuery ajax object need to be a simple object data. JQuery will automatically parse object as parameters on request:
$.ajax({
type: "POST",
url: "getmoreinfo.php",
data: {
fval: document.getElementById('get_usecompny').value,
sval: document.getElementById('country').value
},
success: function(html) {
$("#get_more_info_dt").html(html);
}
});
I'm trying to call a function using ajax in a wordpress admin submenu. Here is my code.
jQuery('#deleteProj').submit(ajaxSubmit);
function ajaxSubmit(){
var tobeDeleted = jQuery(this).serialize();
alert(tobeDeleted);
jQuery.ajax({
type:"POST",
url: ajaxurl,
data: tobeDeleted,
success:function(){ alert(tobeDeleted);},
error:function(errorThrown){alert(errorThrown);}
});
return false;
}
However, the code opens a new page querying the admin.php file looks like this:
wp/wp-admin/admin.php?q=id&action=deleteproj
I'm really at a loss for why this is happening. I'm calling the function from inside my plugin's admin menu
Update
The issue turned out to be that I had to define the php functions on the main file of my plugin. I also made sure to absolutely define the location of admin-ajax.php this allowed the jQuery to properly execute.
Try this:
jQuery('#deleteProj').submit(function() {
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
var formData= jQuery(this).serialize();
jQuery.ajax({
url:ajaxurl,
action:'function_name',
data:formData,
type: "POST",
success: function(data) {
// return
}
});
return false;
});
Regards:)
It seems like you are redirecting instead of ajaxing ,try changing you submit event to a click event
jQuery('#deleteProj').find('[type="submit"]').click(function(e){
e.preventDefault();
var tobeDeleted = jQuery(this).serialize();
alert(tobeDeleted);
jQuery.ajax({
type:"POST",
url: ajaxurl,
data: tobeDeleted,
success:function(){ alert(tobeDeleted);},
error:function(errorThrown){alert(errorThrown);}
});
});
If you have written the code in side your php file, then the answer from Gulshan is correct, but if you have written this code in a different .js file you can not access the ajax url into it. Then you need to localize the script to add the ajax url.
Please follow the example code :
wp_enqueue_script( 'mainscript', get_template_directory_uri() . '/js/main.js', array(), 'v1', true );
wp_localize_script( 'mainscript', 'sitesettings', array('ajaxurl' => admin_url( 'admin-ajax.php' )));
for both the function you need place same handle [ 'mainscript' ], now in your main.js file you need to write the following code :
jQuery('#deleteProj').submit(function() {
var ajaxurl = sitesettings.ajaxurl; // here you are accessing the admin-ajax.php
var formData= jQuery(this).serialize();
jQuery.ajax({
url:ajaxurl,
action:'function_name',
data:formData,
type: "POST",
success: function(data) {
// return
} });
return false;
});
Hope this work for you
So, I have the following ajax call:
jQuery.ajax({
type: "GET",
url: custom.ajax_url,
dataType: 'html',
data: ({ action: 'ajax_call'}),
success: function(data){
jQuery('.container').append(data);// Need changes
});
Then my php:
function rhmain_tag() {
// 1. Getting wp tag list:
$args = array(
'orderby' => 'count',
'order' => 'DESC'
);
$tags = get_tags($args);
foreach ( $tags as $tag ) {
echo $tag->term_id;
}
//2. Getting "another.php" file
$template_part_path = 'page-parts/another_php';
get_template_part($template_part_path);
exit;
}
add_action('wp_ajax_ajax_call', 'ajax_call');
add_action('wp_ajax_nopriv_ajax_call', 'ajax_call');
As you can see, in the php function, there are two separate thing going on.
Getting tag list passed onto the js as variable.
echo $tag->term_id; shows a number like this "16508164981650616502165031650416505165071650116520." So, somehow I need to put comma in between each term id (not sure how) so it looks like this : "16508,16498,16506,16502,16503,16504,16505,16507,16501,16520"
Then I need to pass these values to js to be used as a variable (not sure how)
another_php file is passed onto js (Works fine).
Questions:
How to do I add "comma" in between the tag term_id?
How do I pass these tag values to js?
EDIT: Using json_encode to pass data
PHP
function rhmain_tag() {
$template_part_path = 'page-parts/another_job';
$return_data['another_job'] = get_template_part($template_part_path);
$return_data['tag_id'] = '16498';
echo json_encode($return_data);
exit;
}
add_action('wp_ajax_rhmain_tag', 'rhmain_tag');
add_action('wp_ajax_nopriv_rhmain_tag', 'rhmain_tag');
JS:
jQuery.ajax({
type: "GET",
url: custom.ajax_url,
dataType: 'html',
data: ({ action: 'ajax_call'}),
success: function(data){
jQuery('.container').append(data.another_php);
var tag_list = data.tag_id;
});
Using json_encode to send an array containing both data that you require front end you then need to make the following changes to your ajax function.
Change the dataType to json
Access the data as data.another_php and data.tag_id
The full ajax:
jQuery.ajax({
type: "GET",
url: custom.ajax_url,
dataType: 'json',
data: ({ action: 'ajax_call'}),
success: function(data){
jQuery('.container').append(data.another_php);
var tag_list = data.tag_id;
});
To add the comma in between you could use a variable to store instead of echo'ing immediately. Like this :
$args=array(
'orderby'=>'count',
'order'=>'DESC'
);
$tags = get_tags($args);
$tag_list = "";
foreach ( $tags as $tag ) {
$tag_list += $tag->term_id + ",";
}
// Now trim the last comma
$tag_list = rtrim($tag_list, ",");
echo $tag_list;
Not able to pass PHP encoded array to js.
index.php
echo '<script src="script.js"></script>';
$a=array(1,2,3,4,5);
echo json_encode($a);
?>
script.js:
$.ajax({
method: 'GET',
url: 'index.php',
dataType: 'json',
success: function (Data) {
alert("Success!" + Data);
},
error: function (Data) {
alert("Wrong");
}
});
I always got message - "Wrong".
You have not pass html tags in your json value generated from php
echo '<script src="script.js"></script>';
simply delete the code above. also, you have to parse your JSON string after your function is succssed, :
function (data) {
JSON.parse(data).forEach(function (x) {
alert(x);
});
}
use post method i think It work
method: 'POST',
I am trying to use javascript to call a php script which then will return multiple variables back to my javascript so I can manipulate them.
This is my JS.
$.ajax({
url: 'test.php',
data: { id : lastFileId },
success: function(output) {
alert(output);
}
});
my PHP
<?php
$fileId = ($_GET['id']);
$num1 = 1;
$num2 = 2;
?>
From here, how can I return variables $num1 and $num2 so i can use them in my javascript. Is it possible?
also this is a very basic idea of what I have planned to do if I can achieve this.
You can return as many variables as you want with json_encode().
Try in your PHP:
<?php
echo json_encode(array($num1, $num2));
?>
You can add to that array , $num3, $num4, ... and so on.
In your JS, you can access each number as follows.
First, you will need this line of code to parse the encoded JSON string, in your success function.
var result = $.parseJSON(output);
That sets result as a JSON object. Now you can access all fields within result:
result[0] -- $num1 in PHP
result[1] -- $num2 in PHP
You can go for Json in PHP and javascript if you want array in response for a ajax request
PHP Code
<?php
$fileId = isset($_GET['id'])?$_GET['id']:0;
echo json_encode(array("field"=>$fileId,"num1"=>1,"num2"=>2));
?>
Js Code
jQuery.ajax({
type: "GET",
url: 'test.php',
dataType: "json",
success: function(response) {
console.log(response);
alert(response.num1);
}
});
convert json to object
jQuery.ajax({
type: "GET",
url: 'test.php',
dataType: "json",
success: function(response) {
item=JSON.parse(response);
console.log(item);
alert(item.num1);
}
});
Use a simply string and explode(split) it further in ajax response. Here is PHP code
<?php
$fileId = ($_GET['id']);
echo $num1."|".$num2;
?>
Now split(explode) the response with JavaScript
$.ajax({
url: 'test.php',
data: { id : lastFileId },
success: function(output) {
var my_arr = output.split("|");
console.log(my_arr[0] + "" + my_arr[1]);
}
});
you can simply return it like that
return ['num1'=>$num1,'num2' => $num2];
and also, you can access it as followed,
respone.num1