How to execute a PHP function inside of a Javascript function? - javascript

I made a two PHP functions for my project, these two functions responsible for fetching different product category for different "online shop".
Now, I am implementing the function that when employee adding a new product, the employee first select which online shop does the new product belongs to (via a select), then depends on the online shop, the second select menu should display the correct options.
so, the first select looks like this
< Select name="Select_CCV_Webshop[]" id="ccv-webshop"
onchange='loadNew_CCV_Category()'>
here I need help on how to execute /call /trigger the php function inside of method "loadNew_CCV_Category".
Inside of function "loadNew_CCV_Category", it will get the select value, and this value will be the parameters for the php function.
Please help :D, Thank you !!!!

You can try this way,
<?php
function square($num)
{
echo $num * $num;
}
?>
<select name="Select_CCV_Webshop[]" id="ccv-webshop"
onchange='loadNew_CCV_Category()'>
<option>Select</option>
<option>Test Php</option>
</select>
<script>
function loadNew_CCV_Category(){
var phpData = "<?php square(4) ?>"
alert(phpData);
}
</script>

The short answer
You can not. PHP is executed server-side and only the PHP-generated page is then delivered to the browser, where JS takes over and can continue reacting to input, but only with information it already has.
The more helpful answer
You can, however, either deliver the information for both cases to the browser and decide which one should be shown, or, which in most cases will be what you would rather do, make another call to the server from within your JS.
That means you would have an additional PHP script, which executes the function and generates the page content you want to insert.
You would then access that script file using JS and insert the generated contents into your page.
As for how to do that, maybe
this answer might help.
EDIT: Also refer to Avi's answer on that.

You cannot execute php inside javascript. because php is server side program and javascript is browser related.
If you want to write php then you can try this.
alert("<?php echo 'hello' ?>")
or
$.ajax({
url: 'yourphpfilepath.php',
success: function(respon) {
$('.result').html(respon);
}
});
your code will be like this.
<Select name="Select_CCV_Webshop[]" id="ccv-webshop" onchange='loadNew_CCV_Category()'>
<div id=wheretoshowresult> </div>
<script>
function loadNew_CCV_Category(){
$.ajax({
url: 'yourphpfilepath.php', //url for your php function or file
success: function(respon) {
$('#wheretoshowresult').html(respon);
}
});
}
</script>

Related

Minor difficulties with Ajax and PHP interaction

I working in CodeIgniter and I am trying to spit out all of the items I have in a table and order them as they should be using the dropdown. I want it to happen without page reload and without submit buttons, so I am using this jQuery function to make immediately react, when it is changed:
$(document).ready(function() {
$(".order-by-select").click(function() {var orderValue = this.value;
$.post("<?php echo base_url() ?>welcome/index", {val: orderValue}, function(data) {
alert(data);
});
});
Inside you can see the $.post method, with wich I am trying to send the data to php script (orderValue).
After that, I am getting an alert (not even sure, why do I need it (Maybe to check if everything is ok there))
In PHP, I am receiving the chosen select option and assigning a variable ($data['people']) to the results of MySQL query (that is placed in the model) to be able to access it withing the view. This - $_POST['val'] represents, how can I order the list (select * from people order by $theorder" ($theother is just a variable inside the query function. It recieves the value of $_POST['val'])).
if(isset($_POST['val'])) {
$data['people'] = $this->database->listPeople($_POST['val']);
exit;
}
After that I recieve this variable in the view and I am running foreach loop to take different parts of the array(name of the person, his age, etc..) and placing it in the way they should be.
The problem is - if I do that without ajax, when I have static order by value - everything works fine. I did not mean that was the problem :D, the problem basically is that is doesn't work with ajax... I was trying to recieve the array in the js callback and create a layout using
$.each(eval(data), function() {
$('#container').text('<div>' + eval(res).name + '</div>');
});
But that was also a failure...
How should I organize and create my code to make everything work properly?
I am kinda new to Ajax, so I hope I'll really learn how to do that from you guys. I already searched through the whole internet and have seen a lot of ajax tutorials and other kind of material (e. g. StackOverflow), but I still can't get, how can I do all of that in my particular situation. I have wasted already about 12 hours trying to solve the problem and couldn't do that, so I hope You will tell me if there is any useful salvation.
Thank you for your consideration.
Hi the skinny is you need 3 parts to make ajax work,
serverside code to generate the page
ajax ( clientside ) to make the call and respond
seperate serverside to receive it.
Also it will be easier to replace the table completely then to pick out elements. But that is up to you.
So say we have the page with our ajax call
<script type="text/javascript" >
$(document).ready(function() {
$(".order-by-select").click(function() {var orderValue = this.value;
$.post("<?php echo base_url() ?>welcome/index", {val: orderValue}, function(data) {
alert(data);
});
});
</script>
Now you seem to have some json response I'll assume you get this from the alert above;
[{"id":"1","name":"Nick","age":"18"},{"id":"2","name":"John","age":"23"}]
I'll also assume that this comes from something like
echo json_encode( array( array('id'=>1, ...), array('id'=>2 ...) .. );
It's important before doing the echo that you tell the server that this is json, you do this using a header, but you cannot output anything before the header, and after the json header all output must be in the json format or it wont work, it's like telling the browser that this is html, or an image etc. what the content is.
Header("Content-Type: application/json");
echo json_encode( ....
You can get away without doing this sometimes, but often you'll need to use eval or something, by telling the browser its json you don't need that. Now doing an alert is great and all but if you see the string data [{"id": .. your header is wrong, you should get something like [object] when you do the alert.
No once we have a factual Json object we can make use of all that wonderful data
<script type="text/javascript" >
$(document).ready(function() {
$(".order-by-select").click(function() {var orderValue = this.value;
$.post("<?php echo base_url() ?>welcome/index", {val: orderValue}, function(data) {
$.each(data, function(i,v){
alert(v.id);
alert(v.name);
});
});
});
</script>
This should loop through all the data and do 2 alerts, first the id then the name, right. Next it's a simple matter of replacing the content using .text() or .append()
<script type="text/javascript" >
$(document).ready(function() {
$(".order-by-select").click(function() {var orderValue = this.value;
$.post("<?php echo base_url() ?>welcome/index", {val: orderValue}, function(data) {
$.each(data, function(i,v){
$('#test').append('<p>'+v.id+'</p>');
});
});
});
</script>
<p id="test" ></p>

Executing PHP & SQL with HTML button

I have a webpage which contains an array generated with JavaScript/jquery. On a button press, I want to run a PHP function, which updates a MySQL database with the JavaScript array.
I have a .php file with a PHP function that connects to the database and runs an UPDATE query, I want to use the array with that.
So I have home.php, which has the button:
<?php
include_once ('submit.php')
?>
<center><button id="submit" class="button1" >Submit<span></span></button></center>
and the array:
<script>
selectedItemsArray;
</script>
and I have submit.php, which has the sql UPDATE:
function submit(){
$sql = $dbh->prepare("UPDATE pending_trades SET item_list=:itemlist,");
$sql->bindParam(':itemlist', /*array taken from home.php*/);
$sql->execute();
}
I'll convert the array into a JSON before I put it into the database, but I need to know how to get access to the array with my submit.php file, and how to run the submit() function on the HTML button click.
There are multiple issues here. Most crucially, you seem to be confusing server-side and client-side scripting.
You are including submit.php in home.php, which declares a function submit() on the server-side. Your code never executed this function while on the server-side, and so the server-side output is empty,i.e. <?php include_once ('submit.php');?> evaluates to nothing. What the client-side receives is a HTML file with only the button, the function submit() is never passed to the browser.
Remember: server-side scripts are ALWAYS executed on the server and NEVER passed to the browser. That means you will never see anymore <?php and ?> when the file hits the browser - those PHP codes have long finished.
What you need to find out in order to accomplish what you intend:
Use client-side script (JavaScript) to listen to button clicks.
Use client-side script (JavaScript) to submit the form to server through AJAX.
Use server-side script (PHP) to read the data POST-ed, extract the data into an array.
In effect, you are asking three questions. And they are really straightforward; you can read up yourself.
What I'd do is to suggest an architecture for you:
home.php or home.html: contains the button, <link href="home.css"> and <script src="home.js">.
home.js: client-side script to listen for button click and submit AJAX to submit.php.
home.css: styles for the button and other elements in home.html/home.php.
submit.php: server-side script to check for POST variables and the SQL update operation.
Another issue: you are using a deprecated tag <center>. I'd advise you to remove it and layout the button using CSS instead.
use jquery AJAX.
<button id = "submit" class = "button1" > Submit <span></span></button>
your js code
$('#submit').click(function(){$.ajax({
method: "POST",
url: "submit.php",
data: itemlist,
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
and your php file. don't include file
$array = json_decode($_POST['itemlist'], true);
Remember your js array itemlist should be json format e.g.
$itemlist = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

How to pass javascript variables to php variables with yii

First: I KNOW this is a duplicate. I am creating this because none of the answers to all the other questions satisfy me. I have a very particular situation where I'm using yii and tryi I can't send it through ajax because the php and javascript are on the same page on the same page.
Basically what I'm asking is if you have a page that uses yii and chart js, and you need to render a page that requires two arguments from the clicked bar, which is represented by activeBars[0]:
<script>
canvas.onclick = function(event) {
var activeBars = getBarsAtEvent(event);
<?php $controller->functionThatRendersView($arg1 /**(activeBars[0].value*/,$arg2 /**(activeBars[0].label*/); ?>
}
I don't care if it will render automatically, that is another problem. I just need to get those arguments to the php.
Thanks.
Also, if it helps, I am passing those two values to javascript through php for loops:
labels: [<?php for ($i=1;$i<=$numberIssues;$i++) {
echo $i . ",";
}?>],
The problem with grabbing $i and putting it into the label argument is that I don't know which bar label is the clicked one, I need javascript to pass the clicked bar values back to php.
Explain to us again why you can't use ajax. You say "because the php and javascript are on the same page". That's not what ajax is - you need a different URL for the ajax request, and a separate PHP file or something to handle it.
Without ajax it's impossible for javascript to send information to PHP, because the PHP runs on the server before the javascript runs on the client. Unless of course you want to do a complete page refresh, which is slower and generally worse from the user perspective.
I found an answer to my question! I'm just doing this for anyone else who is stumbling:
To pass javasctipt variable var jsInteger = 5; to php you type (in javascript):
window.location.href = "yourPhpFile.php?phpInteger="+jsInteger;
You access the variable in php like so:
$phpInteger = $_GET['phpInteger'];
This will require a page refresh, and will redirect you to the php file.

Get Ajax to work for all Users on Wordpress

some Plugins that use Ajax in Wordpress only work when you are logged in as admin or added these hooks:
add_action('wp_ajax_my_action', 'my_action_callback');
add_action('wp_ajax_nopriv_my_action', 'my_action_callback');
But I'm really having a hard time with getting everything to work for non-admin users and I'm wondering if there is a easy way (for js/php noobs) to tell wordpress to globally activate all ajax functions for alls users, wether logged in or not.
I know this is probably a very stupid and risky way if that is possible somehow, but please let me know!?!!?
PHP wise, you've hit the nail on the head with your code above. This is required for each AJAX action, as each action will of course call a different function.
Now, I'm making the assumption that you are using the default Wordpress AJAX call -
jQuery.post(ajax_object.ajax_url, data, function(response) {
If that is indeed the case, for front end calls it is likely that ajax_object.ajax_url is not set. To set this, add the following to your functions.php file -
<?php
add_action('wp_head', 'plugin_set_ajax_url');
function plugin_set_ajax_url() {
?>
<script type="text/javascript">
var ajax_object = {};
ajax_object.ajax_url = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
<?php
}
?>

get a variable from javascript and use it in php [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 9 years ago.
I want that when the user clicks an image a pop up window shows up asking the user to input a name, in this case I want to create a folder in a directory therefore the user has to input the name of the new folder to be created.
Now to create the pop up I need to use javascript and to create the folder I need to use PHP (server side). I am using the following code:
When the user clicks the image:
<div>
<a id="myLink" onclick="MyFunction();">
<img src="images/create_folder.png" width="60px" alt="create folder"/>
</a>
</div>
The code I am using to execute this operation:
<script>
function MyFunction(){
var foldername = prompt('Enter Folder Name');
<?php
$foldername = $_GET['foldername'];
mkdir('users_page/folders/', true);
?>
}
</script>
The pop up window I showing however when I click the ok button the folder is not being created.
Can any one please help.
Thanks!
It is a good pratice on understand how php code works with javascript. Be precisely, how server works with client.
First, create a new file called CreateFolder.php and put it on same directory of javascript file and write following code.
<?php
$foldername = $_POST['foldername'];
mkdir('users_page/folders/matthewborgcarr/'.$foldername, true);
echo 'the folder name is:' .$foldername; // add this line
?>
Then, on your javascript, remove all php code and add ajax function
<script>
function MyFunction(){
var foldername = prompt('Enter Folder Name');
$.ajax({
type: "POST",
url: 'CreateFolder.php',
data: {foldername: foldername},
success: function (dataCheck) {
alert(dataCheck); // foldername is returned on alert.
}
});
}
</script>
The PHP code runs before the page is loaded, this means it runs before the javascript. In order to execute PHP code by means of javascript you'll need to implement an AJAX request.
Check out my answer on this question: Using AJAX to return query results based on drop down box
It's an commented example on how to do Ajax requests with Jquery & PHP. You might find it helpful as a starting point.

Categories