Run PHP file to get value for field [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I know I can include a PHP file with an echo to use as a value in form:
value="<? include('generatecode.php'); ?>">
But is it possible to send a value to this php file before it generates the code? For example in this PHP file it has an if statement relating to a value...
if ($value == 1) { do this } else { do this }
Is there any way I can use a checkbox that sends $value to this php file and updates if the box is checked or unchecked?
Thanks in advance.

You need Ajax to do this:
Lets suppose u have a checkbox with an id of #check then :
$('#check').click(function() {
var checkVal;
if($(this).is(':checked')) {
checkVal = 'checked';
} else {
checkVal = 'unchecked';
}
$.post('generatecode.php', {input : chechVal}, function(data) {
// do something with the data returned from generatecode.php
alert(data);
});
});
In the generatecode.php file:
//catch the checkVal variabe u sent
$checkVal = $_POST['input'];
//do somthing with it, depending what you do the output will be in the *data* variable in the above js script
if($checkVal == something) {
//do something
} else {
//do something else
}
NOTE :
What the above code does is from the page you are at the moment catches if the checkbox with id #check is checked or not.Then sends to generatecode.php the relative checked or unchecked ,there this gets caught in a PHP variable and depending on its value performs an operation which result then gets back to your starting page as a jquery variable data, which then you can manipuate as you like instead of alerting it as i did above.
Hope this helped feel free to ask for any clarifications.

You can assign a value to your variable in your main file. As soon as you include the file, $value will be available in your included file.
<?php
$value = 1;
?>
value="<?php include('generatecode.php'); ?>">
This is kind of a weird way of assigning a value to what I assume is an HTML input element. Typically, you would generate some value and assign it to a variable in your include file and then output the variable.

Related

Not able to transfer variables from javascript to php using ajax [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I tried sending data stored in an array(emp) using ajax and other string variables like 'gtotal' in code but data has not been transferred to the PHP file. It doesn't show any error but when I removed the isset() function it says unidentified index. I tried with different variables but no luck so far. Console function is working in HTML file and returning the values passed but data has not been collected in PHP file-like return value of $_POST shows empty array.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script >
$('#btn').click(function(){
var grandtotal=document.getElementById("gt");
var x =grandtotal.textContent;
var gtotal= String(x);;
var emp={};
emp.name=gtotal;
if(x=== '₹0'){
alert("Add to your cart")}
else{ $.ajax({
method: "POST",
url: "connect2.php",
data: emp,
success: function(data){
console.log(data);
}
});
// location.href='connect2.php'
}});
</script>
<?php
print_r($_POST);
if(isset($_POST['gtotal']))
{
$gtotal = $_POST['gtotal'];
echo $gtotal;
}
?>
The problem is that no item called gtotal is being sent in the $_POST.
Do a var_dump($_POST) to check exactly what is being sent.
You asked for an object to be sent which has an item name. If you see that in the dump then you need to use $_POST['name'] not $_POST['gtotal']

How to convert PHP function to become called using Ajax [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Edit: I am not directly trying call a PHP function using Javascript. The application routing will help frontend to hit the correct function.
I think my problem might have a simple solution, but I am not able to figure it out.
I have a bunch of PHP functions that output HTML. Something like:
<?php
function sample1($param1)
{
//make DB query and loop and print HTML
?>
<div class='some-class'>
Some dynamic output here...
</div>
<?php
}
?>
So like I said there are a bunch of such functions. And I want to call them using Ajax so that their values can be returned and I can print them/update DOM using Javascript. I know that I can update all the functions so that the HTML they generate can be stored into a string and then I can each that string. But is there an easier, cleaner solution to this problem?
Because you are not providing me the javascript ajax call i will focus on the php side.
I am using a simple get Ajax call:
$.get( "https://someKindofLink.php?callFunction=Hallo&doctor=who", function( data ) {
alert( data );
});
On the php side we need to check is the function exists and the run it with all variables in $_GET:
if (isset($_GET['callFunction'])) {
if(function_exists($_GET['callFunction'])){
echo $_GET['callFunction']($_GET);
exit;
}
}
function hallo($params)
{
return "Goodbye".$params['doctor'];
}
I would not advise this approach for security reasons but it should get the job done.

Multiple files not appearing on server side [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I have a problem when I'm trying to upload files to my server. I have done this many times before so I'm not sure why this is happening now. Nothing has changed to my knowledge.
What's happening is the following:
submit the 1, 2, etc... files through the uploader
check the headers it clearly shows N amount of files.
test php file and put the line print_r($_FILES); it will show only one file, the last one on the file stack specifically.
Just for reference I am using the jquery plugin Bootstrap File Input by Krajee.
file input plugin docs
http://plugins.krajee.com/file-input
JS
$.ajax({
url : '../assets/server/trade/submitTradeForm.php',
type : 'post',
data : data,
dataType : 'JSON',
success : function(response){
if(!response.errors){
if($('#images').get(0).files.length > 0){
$('#images').on('filebatchuploadsuccess', function(event, data, previewId, index){
//$('#tradeForm')[0].reset();
bootbox.alert(data.response.success_message);
});
$('#images').on('filelock', function(event, filestack, extraData){
extraData['trade_form__id'] = response.trade_form__id;
});
$('#images').fileinput('upload');
}else{
bootbox.alert(response.success_message);
}
}else{
bootbox.alert(response.error_message);
}
}
});
PHP
<?php
print_r($_FILES);
if(!empty($_FILES)){
if(!empty($_FILES)){
$names = array();
$files = array();
$mime_types = array();
foreach($_FILES['file']['name'] as $name){
array_push($names, $name);
}
foreach($_FILES['file']['tmp_name'] as $temp){
array_push($files, $temp);
}
foreach($_FILES['file']['type'] as $type){
array_push($mime_types, $type);
}
}
?>
Thank you ahead of time for any and all assistance!
Since the form wasn't posted along with how your file inputs are named, the name attribute for each file requires it to be accessed via an array.
For example:
<input type="file" name="file[]"> with the square brackets.
The brackets declares/signifies it as an array.
Therefore, PHP took in a file alright, only one and is the last one used because of the missing array declaration.
References:
http://php.net/manual/en/language.types.array.php
http://php.net/manual/en/features.file-upload.multiple.php

How to call php method in javascript? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I already doing research in here.
Many people say ajax is better.
But I want to ask something first because I never use ajax.
I want to delete some row in database if I push yes on the windows.confirm using javascipt.
My HTML button
<button onclick="deleteFunction()">Del</button>
My Javascript function
<script type="text/javascript">
function deleteColumn(id)
{
if (confirm("Are you want to delete?") === true) {
// Do delete method in PHP
} else {
// Cancel delete
}
}
</script>
My delete method in Storage class
class Storage
{
public function delete($condition)
{
// Delete from database with condition
}
}
Do I must use ajax to call PHP method?
It's important to have two concepts clear, execution in server side and execution in client side.
Server side, like php, the code is interpreted in the web server.
Client side, like javascript, the code is interpreted in the browser of the user.
AJAX is really good to make the two sides work "together" without disturbing the user experience.
Using AJAX in this case isn't a must. AJAX is useful when you want to make an action without reloading all your site. If what you want to do is that, try using some jQuery function, like:
$.ajax({
url: "yourPHPfunction.php",
data: {
row: 123
}
}).done(function() {
alert("The row was deleted.")
});
in your js delete() function.
If you don't want to use AJAX, make a GET or POST request (via js) to the PHP file where you had coded the delete function.
It will be good if you take a look to jQuery API documentation here.
But before, to have a background about AJAX, it's good to read that.
This should give you basic flow:
<!-- the form sample -->
<form method="POST" action="your_php.php" onsubmit="return confirm('Are you want to delete?');">
ID: <input type="text" name="id" /><br/>
<input type="submit" name="submit" />
</form>
In PHP:
<?php
class Storage
{
public function delete($id)
{
// should be better if this is another class
$connection = new mysqli('localhost', 'your_db_username', 'db_password', 'database_name');
$stmt = $connection->prepare('DELETE FROM `table` WHERE id = ?');
$stmt->bind_param('i', $id);
$stmt->execute();
}
}
if(isset($_POST['submit'])) {
$id = $_POST['id'];
$storage = new Storage();
$storage->delete($id);
}
?>
I would answer with a simple phrase :
Look this video : How PHP Works
You will understand yourself, why what you are asking is not possible without AJAX.
Enjoy the video, and see you :)
I hope this answer will help you to figure out why you cannot do what you want to, without using AJAX or similar ;)
The php code need the php interpreter to run.
The browser cannot find the php interpreter to run your code in the javascript. So you must call a php server to help you.It will run your code and return your result.Using ajax is a better idea!

Count and display button click on page [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am looking for a very simple solution to tracking and displaying the number of clicks of a button on a webpage. I searched Google and all the solutions I found were far more complicated than what I am looking for.
Basically all I need it to do is track every time a single button is clicked, store the value of total clicks in a database and then display that value on the same page. I'm guessing I will need to use PHP/MySQL to accomplish this, can anyone point me in the right direction?
Thank you!
This can be done with PHP/MySQL/jQuery. I haven't tested any of this code and it won't be very effective at tracking bursts of fast clicks, but it should get you started:
Include jQuery in the footer of your webpage
Include click.js (below) beneath the jquery call
Set up an SQL table called click_log that contains user_id (INT) and time (DATETIME)
Include this code at the bottom of your document. It feeds the increment script a user ID (assuming you have a user's ID handy as variable):
<script>
$(function () {
// Event handler for the click
$(document).click(function(e){
// Feed the increment function the user's ID
increment(<?= $user_id ?>);
});
})
</script>
Include a counter div wherever you want the total count displayed, and include get_count.php in it:
<div id="counter">
<?php include("get_count.php?user_id=".$user_id); ?>
</div>
click.js - jQuery function to call the increment script below via AJAX
$(function () {
// Define an increment function to accept a user_id
function increment(user_id){
// Create a data object
data = {
user_id = user_id
}
// Deliver the payload
$.ajax({
type: "POST",
url: "increment.php",
dataType:"JSON",
data: data,
success:function(response){
$("#counter").empty().load("get_count.php?user_id="+user_id);
}
});
}
}
increment.php - PHP script to register a click in database from an AJAX request
<?php
// Set the header to accept JSON
header("Content-type: application/json");
// Insert your database connection here (should probably use mysqli)
$host = "localhost"; // or IP or whatever
$db_user = "admin";
$db_pass = "password";
$db_name = "your_db";
mysql_connect($servername, $db_user, $db_pass) or mysql_error();
mysql_select_db($db_name) or db_name();
// Grab user id from post data
$user_id = $_POST["user_id"];
// Write the query
$sql = "INSERT INTO click_log (user_id, time) VALUES ('".$user_id."', CURRENT_DATE());"
// Encode a JSON response if the query is successful
if(mysql_query($sql)){
echo json_encode("Success");
}
?>
get_count.php - File to load in your counter div that displays total clicks by user
<?php
// Get the user id from the URL ($_GET)
$user_id = $_GET["user_id"];
// Write the SQL to count the number of rows ('clicks') with that user
$sql = "SELECT count(*) FROM click_log WHERE user_id = '".$user_id."';";
// Run the query
$result = mysql_query($count_sql);
// Format the result and set it a variable
$total_clicks = mysql_result($result, 0);
// Print the total clicks by that user
echo $total_clicks;
?>
Hope this helps get you started! :)
Here is about as simple as it gets for saving a number on the server. http://www.w3schools.com/php/php_ajax_poll.asp Or in other words its not that simple. Try out some code and then ask a more specific question.
Note w3schools isn't the best html resource but it does give
I found a text document solution which fits my needs perfectly. I've implemented it, but the problem is that the action remains in the URL after the button is initially clicked so all you need to do to increase the count is to refresh the page. What would be the easiest way to prevent this?
PHP:
if ( ! file_exists('./count.txt'))
{
file_put_contents('./count.txt','0');
}
if (trim($_GET['action']) == 'increment')
{
counter('increment');
}
function counter($action)
{
if ($action == 'count')
{
return file_get_contents('./count.txt');
}
else
{
file_put_contents('./count.txt', (string) (((int) file_get_contents('./count.txt')) + 1));
}
return true;
}
?>
HTML:
<span id="button">Click Here</span>

Categories

Resources