This question already has answers here:
Javascript and PHP functions
(7 answers)
Closed 9 years ago.
In my index.php file, I have a php function "InsertTheRecord" which gets a parameter and insert it into the database. It return 1 if that parameter is inserted successfully otherwise 0.
I have following JavaScript function "InsertRecord" in same index.php from where I want to call php InsertTheRecord function. How can I call php function from JavaScript function?
My JavaScript function:
function InsertRecord() {
var myParameter = 40;
var result = ////call InsertTheRecord(myParameter) //I don't know how to do this?
if result == 1 { //do something}
else { //show error message}
}
php server side scripting language and javascript is client side scripting language
you can do this by ajax call(Jquery)
<div id="yourdiv"></div>
var data ="hello world";
var data2="hello all";
function run(){
$.ajax({ url: 'myscript.php',
data: {'q': data,'z':data2},
type: 'post',
success: function(output) {
alert(output);
document.getElementById("yourdiv").innerHTML += output; //add output to div
}
});
}
myscript.php
<?php
myfun();
function myfun(){
$myvar2 = $_POST['z'];
$myvar = $_POST['q']."how are you?";
echo $myvar."\n";
echo $myvar2;
}
?>
this alert "hello world how are you?"
Try
var result = <?php echo InsertTheRecord(myParameter); ?>
updated after OP's comment
$.ajax
function InsertRecord() {
$.ajax({
type: "POST",
url: "your_php_page.php",
data: "arg1=id&arg2=name",
success: function (data) {
var myParameter = 40;
var result = data;
if result == 1 {} else {}
}
});
}
PHP is serverside,
JS is clientside,
So the PHP works first, after that the JS works dynamically in the browser.
You cannot call the PHP function in runtime. But you can use AJAX which can do that. Check this out: http://www.w3schools.com/ajax/ajax_aspphp.asp
What if you echod the myParameter to a hidden input field and then grabbed it with javascript:
HTML/PHP file:
<input type="hidden" id="myParameter" value="<?php echo InsertTheRecord(myParameter); ?>"/>
In Javascript:
function InsertRecord() {
var myParameter = 40;
var result = document.getElementById("myParameter").value();
if result == 1 { //do something}
else { //show error message}
}
It is not possible
Javascript is client side scripting language where PHP is server side scripting language
But, you can try AJAX methods to get similar results where you can pass variables same as function
as function myfunction(var1, var2 ,....){return var1*var2}
using ajax, you can run a php script externally on button click
$.ajax({key:var},function(result){alert(result)});
http://www.w3schools.com/jquery/jquery_ajax_intro.asp
http://www.tutorialspoint.com/ajax/
Related
This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 4 years ago.
I have php page which contains two javascript functions like this:
function PregledDokumenta(id)
{
var info = id.split('-');
var vrdok = info[0];
var brdok = info[1];
$.ajax({
type: "POST",
url: "../Php/Dokument/Pregled.php",
data: { vrDok: vrdok, brDok: brdok },
success: function(returnedData)
{
document.getElementById('Content').innerHTML = returnedData;
<?php
$_SESSION['vrDok'] = vrdok;
$_SESSION['brDok'] = brdok;
?>
<?php
$a = $_SESSION['vrDok'];
echo("alert($a);");
?>
}
});
}
function UnosNoveStavke()
{
var vrdok = <?php echo($_SESSION['vrDok']);?>;
var brdok = <?php echo($_SESSION['brDok']);?>;
<?php
$a = $_SESSION['vrDok'];
echo("alert($a);");
?>
$.ajax({
type: "POST",
url: "../Php/Dokument/IzborRobe.php",
data: {vrDok: vrdok, brDok: brdok},
success: function(returnedData)
{
document.getElementById('Content').innerHTML = returnedData;
}
})
}
So when i load page and press button i run PregledDokumenta(id) function. In there i pass some values from id of element and then i echo back some other text and buttons as you can see i alert $_SESSION['vrDok'] to see if it is assigned and it returns value. Then when i click button (about 10 sec after running first function) that i echoed back from first function i run second UnosNoveStavke function. There you can see I again alert to see if $_SESSION return value but it return undefined. Why is that happening?
You are very confused regarding how JavaScript and PHP communicate with each other!
For example, with the following code, you are effectively trying to assign JavaScript variables, which you get from an AJAX request, into PHP sections:
<?php
$_SESSION['vrDok'] = vrdok;
$_SESSION['brDok'] = brdok;
?>
This can't work, because all PHP expressions are evaluated before the page even loads.
If you need to save these values in PHP sessions, you have to do it either in the file the AJAX request is sent, in your case Pregled.php, or a PHP file that you include in it.
I want to access a javascript variable inside a php query
function myFunction2(){
Total=parseInt(point2)
<?php
$con->query("UPDATE eventlist SET P2 = $this.Total WHERE Eid=$PID");
?>
}
I want the query to set p2=value of total
I understand that php is a serverside script and I cant do this like this. What is an alternative to this.?
EDIT
ok i got this on the JS side
function myFunction2(){
var Total = parseInt(point1)+parseInt(point2);
$.ajax({ url: 'ajax.php',
data: {'total' : Total},
type: 'post',
dataType:'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error");
}
and if i put
echo $_POST['total']
in ajax.php i get an alert with the value passed. So i think the value is being passed properly.
But what i need to do is a Mysql Query.
$con->query("UPDATE eventlist SET P2 = $_POST['total']; WHERE Eid=1");
Something like this. How do i do this
Try send javascript value to another php page which contain your query
function myFunction () {
var param = "value";
$.post('query.php', { postvalue: param}, function(data) {
//do what you want with returned data
//postvalue should be the name of post parameter in your query page
})
}
Change your PHP in this way:
$total = $_POST['total'];
$con->query("UPDATE eventlist SET P2 = $total WHERE Eid=1");
This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 7 years ago.
I am trying to execute the below code which perfectly returns me an output from database.
<?php if(isset($_POST['submit']))
{
$email = $_POST["Email_i"];
$checkRe = mysql_query("select * from contact_form where email='$email'",$con);
if(mysql_num_rows($checkRe)>0)
{
$check = 1;
}
?>
I am trying to call a function using onSubmit event as follows;
<form action="#" method="post" name="myForm" onSubmit="return CheckForm()">
<input type="submit" name="submit">
</form>
<script type="text/javascript">
function CheckForm()
{
var calc =1;
var Checkre = "<?php
$check="";
echo $check; ?>";
if(calc == Checkre)
{
alert('phone number exists');
return false;
}
}
</script>
the above function does not set the value of $check hence not resulting into its execution.
instead of HTML FORMS, try to use and utilize jQuery AJAX.
Sample Code (where data is passed as object [or named array], dataType is declared for your api.php response, timeout is included for network error, error + success + complete functions):
$(document).ready(function(){
$("#btnSubmit").click(function(){
var x = $("#textbox").val();
$.ajax({
type: "POST",
url: "url-to-php-api",
data: { reference:x },
dataType: "HTML-or-JSON-or-JSONP",
timeout: 30000, //1 sec = 1000 ms
error: function(x, t, m) {
if (t === "timeout") {
alert("Network Connection Delayed.");
//this is for network error i.e.: connection delays
}
//and some other codes for other errors~
//error function runs when there is some error with the jQuery AJAX syntax
},
success: function(retData) {
alert("PHP RESPONSE: " + retData);
//success function runs when the js successfully communicated, passed the values to PHP, gets result and back
},
complete: function() {
alert("jQuery AJAX Function Complete.");
//complete function runs after the process is completed, regardless of being error of successful
}
});
});
});
this code is of course, as far as my personal coding is concerned
This question already has answers here:
jQuery Ajax POST example with PHP
(17 answers)
Closed 7 years ago.
The title of this question is probably misleading, I didn't know a good way to consicely ask what I need help with.
So basically, I use the following ajax to send a javacript variable on index.php to a separate php file (page2.php)
var Variable1 = '1';
$.ajax({
type: "POST",
url: 'page2.php',
data: "NewVariable=" + Variable1,
success: function() {
...Save or echo the value of $newervariable here ....
}
});
So basically above I am sending the variable Variabl1 to page2.php . Page2.php looks something like this:
<?php
if(isset($_POST['NewVariable'])) {
$NewVariable = $_POST['NewVariable'];
$NewerVariable = $NewVariable + 1;
}
?>
I know the example is kind of obsolete because you could just do add 1 using javascript without having the 2nd php page, but I just simplified it down really it boils down to me needing the 2nd php page, and also knowing how to save the values of it after success (if it's even possible)
On JS
success: function(data) {
Variable1=data;
}
On PHP:
<?php
if(isset($_POST['NewVariable'])) {
$NewVariable = $_POST['NewVariable'];
$NewerVariable = $NewVariable + 1;
echo $NewerVariable;
}
In php page echo the output :
<?php
if(isset($_POST['NewVariable'])) {
$NewVariable = $_POST['NewVariable'];
$NewerVariable = $NewVariable + 1;
echo $NewerVariable;
}
?>
And in your js :
var Variable1 = '1';
$.ajax({
type: "POST",
url: 'page2.php',
data: "NewVariable=" + Variable1,
success: function( data ) {
// data --> data you echo from server side
alert( data );
// do whatever you want here
}
});
This question already exists:
Deleting a specific node based on dropdown selection in XML [duplicate]
Closed 7 years ago.
Here's my jquery code
<script>
$(function () {
$('#deleteform').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'get',
url: 'delete.php',
success: function () {
alert('Worked');
}
});
});
});
</script>
And my PHP code (I'm just trying to test it out, so I added a simple function)
<?php
header("Location: http://www.google.com/");
?>
And nothing happens when I click the button (when the form submit) except that "Worked" alert box. But whatever I put in that PHP file (delete.php), nothing happens. What am I doing wrong? My "delete.php" file will have a script to delete data in a XML file, just in case it changes something. (for now Im trying with a simple php line)
EDIT
The real PHP code that will go in the PHP file is this :
<?php
$xml = simplexml_load_file("signatures.xml");
$name = $_POST['nom'];
$signs = $xml->xpath('//Signature[Nom = "'.$name.'"]');
$xml -> SignaturesParent -> removeChild($signs);
?>
Nothing happens when I try that.
Try this.
The ajax call now alerts whatever is sent to it from the delete.php
The ajax call does a POST and not a GET so that it matches the fact that you are using $_POST[''] and send some data i.e. smith you are going to have to change that to something that actually exists in your XML file
The delete.php actually returns something
The delete.php saves the changed xml document back to disk to a file with a different name, so you can see if it actually did anything. just while you are tesing.
<script>
$(function () {
$('#deleteform').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'delete.php',
data: {nom:"smith"},
success: function (data) {
alert(data);
}
});
});
});
</script>
<?php
$xml = simplexml_load_file("signatures.xml");
$name = $_POST['nom'];
$signs = $xml->xpath('//Signature[Nom = "'.$name.'"]');
$xml -> SignaturesParent -> removeChild($signs);
$result = $xml->asXML("signatures2.xml");
echo $result ? 'File Saved' : 'File Not Saved';
?>