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}';
Related
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>
This question already has answers here:
How do I pass JavaScript variables to PHP?
(16 answers)
Closed 6 years ago.
I have one php file where I have a number input field. I can grab the value of my input field with jQuery and store it in a javascript variable, but now I want to pass this javascript variable in to a php variable. How easily can I achieve it ?
<input id="custom_price" type="number" class="custom_price" name="custom_price" value="10" min="10" max="1000">
<script type="text/javascript">
jQuery("#custom_price").live("change", function () {
var user_amount = jQuery('#custom_price').val();
});
</script>
<?php $final_value = *How can I pass user_amount here* ?>
You can't. You need to send that variable to server using GET or POST method to save in a PHP variable.
PHP is confusing, because two (or three) different scopes are running within the same sourcecode file.
Your sample has plain PHP:
<?php $final_value = *How can I pass user_amount here* ?>
Plain HTML:
<input id="custom_price" type="number" class="custom_price" name="custom_price" value="10" min="10" max="1000">
<script type="text/javascript">
</script>
and plain JavaScript:
jQuery("#custom_price").live("change", function () {
var user_amount = jQuery('#custom_price').val();
});
HTML and JavaScript run on the client (web-browser) side while PHP runs on the server side.
One step back:
A HTTP access has two basic different steps**:
Client (Webbrowser) sends a request
Server sends a response
That's all, no more magic, nothing inbetween: One question, one answer. Further communication requires additional HTTP requests (and responses).
Whenever a browser sends a request to yourscript.php, that request is received, all arguments are parsed and your script is starting. All PHP code sections are processed and everything else plain unknown static data.
In the end, the static data plus the dynamic output from your script are send back to the browser as one package. End of communication.
Each HTML page may contain one (or more) forms which tell the browser that additional information (arguments) should be included in the next request:
<form action="myscript2.php">
<input type="hidden" name="foo" value="bar">
<input type="submit" name="button" value="Send request">
</form>
A click on the submit button creates a completely new request, adds the values of the fields named foo and button and sends (submits) everything to the server.
Again the target PHP script is running and could output something, but not on the previously delivered web page***.
** Some techniques are working more or less slightly different, like continuation requests or websockets, but they're way behind the scope of this question.
*** JavaScript/Ajax could be used to manipulate a web page without reloading it, but thats again just a request, response and Javascript source processing the response on client side.
When a user visits the site, the PHP code is executed on the server and then sent to to the user. Javascript, on the other hand, is sent to the user and then executed on that user's machine. In a basic definition, this illustrates the difference between 'front-end' and 'back-end' development.
That being said. You CAN use PHP to insert values into javascript code, as that can happen on the server and then be executed by the user's machine. However, you CANNOT pass a javascript value to a PHP variable (within the same script/page) because the PHP has already been executed on the server by the time it makes it to your web browser.
As was mentioned by others, the solution is to send the (javascript) data to a PHP script on your server via a network call. You could utilize jQuery.ajax() to do this in your javascript, then your PHP script will need to accept the data and do something with it.
Indeed , there is a way to embed Js Inside PHP code , but , is it applicable or not , this is another issue
see the following simple code :
<input id="custom_price" type="number" class="custom_price" name="custom_price" value="10" min="10" max="1000">
<?php $final_value ="<script type=\"text/javascript\">
var e = document.getElementById('custom_price').value;document.write(e); </script>";
echo $final_value; ?>
First remember php is run on server side and javascript is run in client side. So to pass the variable to the server/php you need to send it via http request. You could for example use ajax:
$.post('file.php', { 'varname': 'varvalue'});
Also you will need to capture the parameter on you server side:
#file.php
<?php
$value = $_POST["varname"];
?>
Before i go on, I'm aware that this question has been asked a couple of times but it doesn't deal with specificity.
I have a functions.php script which contains a couple of functions and i would like to call a specific function when the user clicks on an anchor tag.
I have gone through most of the questions in this manner and i understand that this would be done through javascript and ajax load the page specified with the on-click attribute.
My question is when this happens(page is being loaded) how do I call a specific function out of the functions.php script and if I have required it on the current page where the anchor tag exists will it cause complications?
To be more precise i have a register.php page which does the following; take user data then validate, if validated insert into DB and send a mail to the user to verify his account then redirect to a registration_complete.php page which has the option of resending the link if user didn't receive it. Hence clicking the link will run a specific mail function in the functions.php file.
The Code is written below
register.php
<?php
session_start();
$_SESSION['name'] = hmtspecialchars($_POST['name']);
//validation code goes here
if (isset ($_POST)){ //check that fields are not empty etc...
// insert into db code...
// email the user code...
// redirect to registration_complete.php code..
}
?>
<form method='post' action="">
<input type="text" name="name" id="name">
<input type="text" name="email" id="email">
<input type= "submit" value="submit">
</form>
registration_complete.php
<?php
require'functions.php'
session_start();
$Name = $_SESSION['name']
$RegisterationComplete = "Thank you . ' ' . ' $Name' . ' ' . for registering pls click on the link in the email sent to the email address you provided to verify you account. If you didn't recieve the email click on the resend email link below to get on resent to you. Please make sure to check your spam folder if you did not see it in your inbox folder."
?>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
function doSomething() {
$.get("somepage.php");
return false;
}
</script>
Resend Verification Link
Please not that i have copied the js code from one of the answers related to my question
functions.php
<?php
//connect to db code
// insert into db code
// send verification link code using PHP Mailer function..
?>
So when ajax loads the functions.php page how does javascript call the exact function(PHP Mailer).
I just want to state that i am new to programming i'm only a bit conversant with php. My knowledge of Javascript and Ajax can be said to be negligible. Also want to say a big thank you to all contributors.
Javascript will never call PHP functions, since PHP is running on the server and Javascript is running in the web-browser. The server and the web-browser are assumed to be different machines, the only exception being testing by developers. Therefore, if you have a function in functions.php called foo, Javascript will not be able to call it.
As you have already mentioned in your question, this might involve AJAX, which is surely true, but let's be more exact: when your Javascript code intends to "execute" a PHP function, it needs to trigger a request to the server. Not necessarily with AJAX, as you can trigger form submission, or anchor click as well. The request will reach the server, which will handle it.
Now, since we know that the life cycle is as follows:
Javascript detects that foo has to be executed
Javascript triggers a request to the server
Server is requested
Server handles the request
Server responds
The missing piece in the puzzle is to let the server know that it has to execute foo. To achieve this, the server has to determine somehow whether foo needs to be executed. This can be done with various way, including get params or post params. Next, you need to modify your Javascript code or html structure to let the server know that the function needs to be executed.
You can add a get parameter to the href of the anchor tag, for instance, but in general, you need to let the server know what the intention is and at server-side you need to handle that intention.
Also, you are doing validation on the server. This is ok, but may I advise you to validate the inputs on client-side and prevent posting if the input is invalid, to reduce server load... On server-side, if the post is valid, you need to execute the needed functions.
Also, this part is not exactly correct:
if (isset ($_POST)){
This is not the right approach to check whether this was a post request. You need
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
instead.
It is not important if the Request comes from javascript or a regular server Request (user clicks on link). You need to check the GET or POST parameters and redirect the Request to a specific function.
<?php
if( isset( $_GET['method'] ) ) {
// NOTE: untested and REALY unsecure Code
$method = $_GET['method'];
if( function_exists( $method ) ) {
call_user_func( $method );
}
}
else {
echo '<a id="link" href="?method=foo">klickme</a>';
}
function foo(){
echo 'in method';
}
?>
<div id="answer"><!-- server answer here --></div>
when you now have a link
http://yourSite.com?method=foo
and the function foo gets executed.
Now the JS part you have to check if the user clicks on a link, or sends a form. Then you have to send the request to server using Ajax and handle the result from the Server.
// inject the serverData in DOM
function loadSuccess( e ) {
document.getElementById( 'answer' ).innerHTML = e.target.response;
}
// handle click, open ajax request
function doClick( e ) {
e.preventDefault();
var ajax = new XMLHttpRequest();
ajax.open("GET", e.target.href ,true);
ajax.send();
ajax.addEventListener('load', loadSuccess);
}
var link = document.getElementById( 'link' );
link.addEventListener( 'click', doClick );
I got stuck when using ajax as primary request sender to php.
I was trying to send data to php file and then take that data to view in another file, but the problem is I don't know how to do it .
I tried
var ajax = ajaxObj("POST", "function.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
window.location = "view.php";
}
}
ajax.send("a="+a+"&b="+b);
it locate view.php and I want to take contents that sent
function.php and view it's contents in view.php.
That is where my problem occurs.
So, my question is HOW TO TAKE THOSE CONTENTS
I think you don't understand the use of ajax... here you don't need ajax at all. Ajax is used to update/send content without refreshing the page. So if you want to pass data to a new php file, just pass the variables directly to view.php in your case.
For instance:
go to view.php?a=[your value]&b=[your value]
in view.php you can get the values:
$a = $_GET['a'];
$b = $_GET['b'];
and pass it to your function.php
Use Jquery to avoid dealing with browsers specifications and also jquery is pretty popular and simple to use library
Assuming you are familiar with php and JavaScript
first you have to do all this work in you www or htdocs folder depending on the stack you are using whether it is XAMPP,WAMP or LAMP
let's say as an example we want to send post request to function.php file and that file should verify the existance of $_POST['username'] and return the length of username otherwise it returns 0
so the function.php file should be something like this :
if(isset($_POST['username'])){
echo strlen($_POST['username']);
}else{
echo 0;
}
and the view.php file is the file used to send post request and get the response and displays it in a #display div
so here is the content of view.php
// first you should include jquery
// here is a cdn link
// https://code.jquery.com/jquery-2.1.3.min.js
// or you can use a local jquery file it is up to you
<div id="display">
</div>
// here is the simple js code to send and get the data from function.php file
<script>
$(document).ready(function(){
// waiting for the document until it is ready to use
$.post('function.php',{username:'myusername'},function(data){
// data here is the returned data from the function.php file
$('#display').text('username length is : '+data);
});
});
</script>
i'm trying to update is a javascript which when you hover over an image, a div object floats near your mouse with information, this information is stored in a .js file as an array,
eg.
Text[0]=["image 1","data 1"]
Text[1]=["image 2","data 2"]
in the past if this array is change/data added to/removed from it would require uploading a new copy of the .js file, if data was added to/removed from it would also require a change to the .dwt file for the new image which would update every file that use the .dwt file as the main template which could result in 20+ pages being uploaded
i figured i can automate this by using the database by flagging records if they are active and using a mysql query to get only those which are active, this way a blackened app can add to the database and deactivate record thus eliminating having to upload files every so soften.
to do this, i had planned on storing the information in the database and building the above array based off the results, researching how to use mysql queries in javascript lead me to code like this
$.ajax( "path/to/your.php" )
.done(function() { alert("success"); })
.fail(function() { alert("error"); })
now i understand that i need to make a .php file which runs my query and that my formatting of the query results into the array would be one in the .done part but what i don't understand is what i'm supposed to do in the .php file to output the query results how in the .done part i'm supposed to reference the output
bellow is the code i use to echo my query results to the page to ensure i am getting results
$resultIndex = 0
while($row = $results->fetch_array(MYSQLI_ASSOC))
{
echo '<'.strval($resultIndex).'><br>';
echo 'id = 'strval($row['id']).'<br>';
echo 'name = 'strval($row['name']).'<br>';
echo 'desc = 'strval($row['desc']).'<br>';
echo 'active = 'strval($row['active']).'<br>';
echo '-----------------------<br>';
$resultIndex += 1;
}
i am wondering 2 things
do i just echo or print_r what i want returned from my .php file
how to i access what my .php file returns in .done
I recommend using http://www.php.net/json_encode to output into Json. Yes, just echo the output. On success, a callback is called passed with the data from server.
$.post (url, function (data){
//do some stuff with data from server
});
See http://api.jquery.com/jQuery.post/
Your $.ajax function just points to a page and reads the data on that page. If you want that page to use MySQL, you will need to use php to set up the MySQL query and print the data. The layers of a web app are complicated, but I'll try to break it down for you.
A traditional php/mysql setup works like this:
Javascript:
Client side, only deals with content already available on the page. Often edits html based on user interaction.
HTML
Client side, defines the content on a page
PHP
Server side, runs on the server and construct the html
MYSQL
Server side, used to communicate between the php and the database
Database
Server side, used to permanently store data
Ajax is a way for the Javascript layer to call some php in the background. That php can use MySQL to access data in the database and print it out in a format that the javascript can parse and use. Typically the javascript will then edit the HTML.