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.
Related
I'm sorry but I'm having a hard time setting up something simple but that doesn't work for me. I'm trying to put a code that counts the number of clicks on a phone number ( the last 4 hidden digits that appear ) then record this data in my DB. I set up the JAVASCRIPT at the bottom of my PHP page where I will listen if there is a click ( Addeventlistener.... ) on the phone number.
I understood that we can not execute PHP code in a JS script, OK, so I execute an Ajax code to send to a PHP file the values to insert in a new entry to my DB. Except that during the execution the functions that open a connection to the DB are not recognized while in the same way I use others functions in the same PHP file that selects and returns me data from the DB.
Is the difference that they are two different types of request SELECT and INSERT or it is because I send the data through Ajax that the PHP files that load the function of DB connection are not loaded?
AJAX Script
<script>
var phoneclick = document.querySelector(".data-phone");
var baseUrl = "public_html/oc-content/themes/delta/"
phoneclick.addEventListener("click", function() {
var item_id = 8111;
var ajaxPhoneClick = 1;
$.ajax({
url: '<?php echo osc_current_web_theme_url('model/sql_projet.php'); ?>',
type: "GET",
data: {
id: '1111'
},
success: function(data) {
console.log(data);
}
});
});
</script>
PHP FIle
$itemId = $_GET['id'];
$conn = DBConnectionClass::newInstance();
$data = $conn->getDb();
$comm = new DBCommandClass($data);
$db_prefix = DB_TABLE_PREFIX;
$query = "INSERT INTO {$db_prefix}t_item_stats (item_id,phone_clicks) VALUES ($itemId,1) ";
$result = $comm->query($query);
The error i get is this Fatal error: Uncaught Error: Class 'DBConnectionClass' not found in /Applications/XAMPP/
I want to know the reason why this error is throwing and what should i do to bypass this
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 has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 7 years ago.
im making and update in mysql table when button click, the problem is ajax jquery not working sometimes. It works fine and somehow after x attempts it stop working and stars cancelling my petitions
the problem is after x number of attempts the success part of ajax object is not being used and im getting the STATUS (canceled) from network.
Pass these values to hidden fields. These fields are called through ajax to send data to next-page to update.
<input type='hidden' value="<?echo $costo_sem;?>" class="costosemanal">
<input type='hidden' value="<?echo $fi;?>" class="fechai">
<input type='hidden' value="<?echo $ff;?>" class="fechaf">
echo "<script>
var r = confirm('OK to update, CANCEL to do nothing');
if(r === false){
document.location.href = 'costos.php';
}else{
var costosemanal=$('.costosemanal').val();
var fechai=$('.fechai').val();
var fechaf=$('.fechaf').val();
$.ajax({url:'UpdatePage.php?costosemanal='+costosemanal+'&fechai='+fechai+'&fechaf='+fechaf,cache:false,success:function(result){
alert('Updated');
}});
}
</script>";
Add one UpdatePage.php to update your query.
UpdatePage.php
<?
$costosemanal=$_GET['costosemanal'];
$fechai=$_GET['fechai'];
$fechaf=$_GET['fechaf'];
$update = "UPDATE tbl_costos SET costo_semanal = '$costosemanal' WHERE fechai = '$fechai' AND fechaf ='$fechaf' ";
//Write Mysql Command To Update This Query
?>
$('.removeItem').click(function (event) {
if (confirm('Are you sure you?')) {
$.ajax({
url: 'myUrl',
type: "POST",
data: {
// data stuff here
},
success: function () {
// does some stuff here...
}
});
}
});
Use above code inside url there must be php page url...
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';
?>
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/