I'm trying to call a PHP function via radio button onclick event, but it isn't working. I'm trying to use Ajax method to call the function, code as follows:
test0.php (php file with radio buttons):
<?php
include "test1.php";
echo '<input type="radio" id="1" name="rere" value="qwqw" checked onclick="testFunc();"><label for="1">radio 1</label>';
echo '<input type="radio" id="1" name="rere" value="qwqw" onclick="testFunc();"><label for="1">radio 2</label>';
echo '<div><p id="res">sdfdsfsdfsd</p></div>';
echo condCheckedUpd();
?>
<script>
function testFunc() {
$.ajax({
url: 'test1.php',
success: function(data) {
//alert(data);
}
});
}
</script>
test1.php (contains function to call)
<?php
function condCheckedUpd() {
echo "works";
}
?>
Think of your ajax call as if you're loading up a new tab in your browser. So, when you click the radio button, your call from test0.php is retrieving whatever gets responded to by test1.php, completely in isolation.
So, no need to include test1.php in your existing file- you're calling it separately! Your solution might be as simple as editing test1.php to execute the function when called, like so:
test0.php
<?php
//include "test1.php"; // no need to include this file here
echo '<input type="radio" id="1" name="rere" value="qwqw" checked onclick="testFunc();"><label for="1">radio 1</label>';
echo '<input type="radio" id="1" name="rere" value="qwqw" onclick="testFunc();"><label for="1">radio 2</label>';
echo '<div><p id="res">sdfdsfsdfsd</p></div>';
//echo condCheckedUpd(); //also no need for this function call here
?>
<script>
function testFunc() {
$.ajax(
{
url: 'test1.php',
success: function(data)
{
//alert(data);
}
});
}
</script>
test1.php
<?php
function condCheckedUpd() {
echo "works";
}
condCheckedUpd();
?>
You also asked about passing parameters along with your request, for that there's the data setting that you can include. For example, replace your javascript in test0.php above with something like:
<script>
//...^ all your existing php/html is still above
function testFunc() {
$.ajax({
url: "test0.php",
data: { name: "John", location: "Boston" }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
}
</script>
Then, in test1.php, you can get your above parameters using the $_REQUEST global variable, and pass them into your function:
<?php
$getName = $_REQUEST['name'];
$getLocation = $_REQUEST['location'];
function condCheckedUpd($getName, $getLocation) {
echo "works for ".$getName." in ".$getLocation;
}
condCheckedUpd();
?>
For your purposes, I expect you probably want to get the value of your radio buttons. For that, you might look into html/javascript's dataset attribute as an easy way to pass these along (Examples and docs here: https://developer.mozilla.org/en-US/docs/Web/API/HTMLOrForeignElement/dataset).
Warning! If you're accepting values this way, be careful that what comes through in your $_REQUEST variables is what you expect, and be very careful if you end up displaying these back to the screen– lots of security concerns here. A few clues: How can I sanitize user input with PHP?
You can't call a function in your php file directly from the client. You can, however, pass data back which lets you determine which function to call.
For example, you could send back a query string test1.php?functionName=condCheckedUpd, and then in your test1.php file, you can check for it:
<?php
function condCheckedUpd() {
echo "works";
}
if ($_GET['functionName'] == 'condCheckedUpd') {
condCheckedUpd();
}
?>
Related
I have a php script which gets all my movies from a specific category and echos the html output using foreach loop placed inside of a function.
Instead of displaying the entire library at once I'd like to display it one category at a time by clicking a button (without page refresh) for example:
User clicks "Action" button:
<li>Action</li>
Which activates Action();
function Action()
{
jQuery.ajax({
type: "POST",
url: 'index2.php',
dataType: 'json',
data: {functionname: 'Movies', arguments: ['Action']},
success: function (returnData) {
data = returnData;
document.getElementById("Action").innerHTML = returnData;
console.log(data);
}
});
}
Action Div:
<a id="Action"></a></div>
<h3><span>Action</span></h3></center>
<div id="detail[19]">
</div>
The PHP function is Movies($var) when passing "Action" into it, it runs fine. So what do I do in order to get "Movies(Action)" to print to "detail[19]"
The PHP function:
function Movies($category){
$movies = glob('./uploads/Videos/Movies/'.$category.'/*/*.{mp4,m4v}', GLOB_BRACE);
global $images,$temp,$emtyImg,$actual_link,$dir,$rmvd;
foreach ($images as $image) {
$lookup[pathinfo($image, PATHINFO_FILENAME)] = $image;
}
foreach ($subs as $sub) {
$lookup2[pathinfo($sub, PATHINFO_FILENAME)] = $sub;
}
echo '<div id="detail['.$rmvd.']">';
include($_SERVER['DOCUMENT_ROOT']."/scripts/amzn.php");
foreach ($movies as $movie) {
*Lot's of useless code that echos div's with videos in them* }
echo '</div>';
$rmvd++;
}
I know I'm missing what I need for the PHP side and likely messed up the jquery bit. I'm at a loss at how to continue successfully.
You need to return a json object in php so that javascript can read it. For example:
<?PHP
$data = /** whatever you're serializing **/;
header('Content-Type: application/json');
echo json_encode($data);
I want to dynamically refresh the php code in this datalist, without reloading the whole page.
<form id="form1" action="1.5-unterseite-nach-Eingabe.php" method="post" enctype="multipart/form-data">
<tr>
<td>Lecture auswählen: </td>
<td><input list="files" name="unterlage"></td>
</tr>
<datalist id="files">
<?php
$files = array_diff( scandir("/srv/www/htdocs/share/"), array(".", "..") );
foreach ($files as $option) {
echo '<option value=\''.$option.'\'>';
}
?>
</datalist>
I hope you can help me out.
You can write your html form in a "index.html" file. And uses javascript intervals request the data which provide by PHP in data.php. The pseudo-code will be something like this:
// index.html
<html>
<form id="form1" action="1.5-unterseite-nach-Eingabe.php" method="post" enctype="multipart/form-data">
<tr><td>Lecture auswählen: </td><td><input list="files" name="unterlage"></td></tr>
<datalist id="files">
</datalist>
</form>
<script>
window.setInterval(function(){
function request_data(){
$.ajax({
url: 'data.php',
method: "post",
success: function (data) {
// Do something here
$("#files").html(data);
}
})
}
},2000); // 2 secends request a time
</scirpt
</html>
// data.php
<?php
$files = array_diff( scandir("/srv/www/htdocs/share/"), array(".", "..") );
return json_encode($files);
?>
Not entirely sure what your end goal is.
But one course of action is to set up an AJAX GET method that calls that PHP snippet in it's own file. Grab all the returning data and insert it into the page using JS.
Start learning JS because that's the only way you're going to be able to pull off dynamic content without page reloads.
To fetch the data using AJAX, use something similar:
<script>
$(document).ready(function(){
$.ajax({
url: 'URL_TO_PHP_FILE/scanFiles.php',
dataType: 'text',
success: function(data)
{
$("#files").html(data);
}
});
});
</script>
Now move your PHP snippet to it's own file simply as such:
$files = array_diff( scandir("/srv/www/htdocs/share/"), array(".", "..") );
foreach ($files as $option) {
echo '<option value=\''.$option.'\'>';
}
?>
Provided your only echos are what you would like to receive in your AJAX call, you should be good.
Also make sure you have the jQuery library linked to your page so that you can use AJAX. Take a look into jQuery a bit more. It'll make your life a lot easier.
You will also want a method to execute your JS code either every few seconds or a trigger based on previous user interaction.
I'm having an issue. When I hit submit, my form values are sent to the database. However, I would like the form to both send the value to the database and execute my script, as said in the title.
When I hit submit button, the form is sent to the database and the script remains ignored. However, if I input empty values into the input areas, the javascript is executed, and does what I want (which is to show a hidden < div >), but it's useless since the < div > is empty, as there is no output from the server.
What I want is:
submit button -> submit form -> javascript is executed > div shows up > inside div database SELECT FROM values (which are the ones added through the submitting of the form) appear.
Is this possible? I mean, to mix both PHP and JavaScript like this?
Thanks in advance.
By two ways, You can fix it easily.
By ajax--Submit your form and get response
$('form').submit(function (e){
e.preventDefault();
$.ajax({
type: "POST",
url: url, //action
data: form.serialize(), //your data that is summited
success: function (html) {
// show the div by script show response form html
}
});
});
First submit your from at action. at this page you can execute your script code .. At action file,
<?php
if(isset($_POST['name']))
{
// save data form and get response as you want.
?>
<script type='text/javascript'>
//div show script code here
</script>
<?php
}
?>
hers is the sample as I Comment above.
In javascript function you can do like this
$.post( '<?php echo get_site_url(); ?>/ajax-script/', {pickup:pickup,dropoff:dropoff,km:km}, function (data) {
$('#fare').html(data.fare);
//alert(data.fare);
fares = data.fare;
cityy = data.city;
actual_distances = data.actual_distance;
}, "json");
in this ajax call I am sending some parameters to the ajaxscript page, and on ajaxscript page, I called a web service and gets the response like this
$jsonData = file_get_contents("https://some_URL&pickup_area=$pickup_area&drop_area=$drop_area&distance=$km");
echo $jsonData;
this echo $jsonData send back the data to previous page.
and on previous page, You can see I Use data. to get the resposne.
Hope this helps !!
You need ajax! Something like this.
HTML
<form method='POST' action='foobar.php' id='myform'>
<input type='text' name='fname'>
<input type='text' name='lname'>
<input type='submit' name='btnSubmit'>
</form>
<div id='append'>
</div>
jQuery
var $myform = $('#myform'),
$thisDiv = $('#append');
$myform.on('submit', function(e){
e.preventDefault(); // prevent form from submitting
var $DATA = new FormData(this);
$.ajax({
type: 'POST',
url: this.attr('action'),
data: $DATA,
cache: false,
success: function(data){
$thisDiv.empty();
$thisDiv.append(data);
}
});
});
And in your foobar.php
<?php
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$query = "SELECT * FROM people WHERE fname='$fname' AND lname = '$lname' ";
$exec = $con->query($query);
...
while($row = mysqli_fetch_array($query){
echo $row['fname'] . " " . $row['lname'];
}
?>
That's it! Hope it helps
You can use jQuery ajax to accomplish it.
$('form').submit(function (e){
e.preventDefault();
$.ajax({
type: "POST",
url: url, //url where the form is to be submitted
data: data, //your data that is summited
success: function () {
// show the div
}
});
});
Yes, you can mix both PHP and JavaScript. I am giving you a rough solution here.
<?php
if(try to catch submit button's post value here, to see form is submitted)
{
?>
<script>
//do javascript tasks here
</script>
<?php
//do php tasks here
}
?>
Yes, This is probably the biggest use of ajax. I would use jquery $.post
$("#myForm").submit(function(e){
e.preventDefault();
var val_1 = $("#val_1").val();
var val_2 = $("#val_2").val();
var val_3 = $("#val_3").val();
var val_4 = $("#val_4").val();
$.post("mydbInsertCode.php", {val_1:val_1, val_2:val_2, val_3: val_3, val_4:val_4}, function(response){
// Form values are now available in php $_POST array in mydbInsertCode.php - put echo 'success'; after your php sql insert function in mydbInsertCode.php';
if(response=='success'){
myCheckdbFunction(val_1,val_2,val_3,val_4);
}
});
});
function myCheckdbFunction(val_1,val_2,val_3,val_4){
$.post("mydbCheckUpdated.php", {val_1:val_1, val_2:val_2, val_3: val_3, val_4:val_4}, function(response){
// put echo $val; from db SELECT in mydbSelectCode.php at end of file ';
if(response==true){
$('#myDiv').append(response);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
I'm coding a voting system for multiple uploads; each uploaded image is in a foreach statement with a form attached to each, with three buttons to vote up, down or none, each associated with an INT in my mysql database.
I got it to work by submitting the form data straight to the PHP function that 'UPDATE's the database. To avoid a page refresh, I attach ajax. I got the ajax to send the two variables needed for the PHP function to update the correct "image" row and INT in the db.
Question: The ajax function works, but the PHP function doesn't seem to update.
SUSPECTED PROBLEM: I'm pretty sure it's the way I'm defining the variables in ajax that I want to pass, I was trying to grab the ID of the "image" it's handling, but I don't know how to translate this data to the PHP function so that it UPDATE's correctly.
Here's the form, javascript, and php:
// IMAGE, and rest of foreach above this, and ending after form
// This form only shows one button, there are three, each
// I'll treat the same once I get one to work
<form action="feed.php" method="post" id="vote_form_1">
// If js isn't turned on in broswer, I keep this
// hidden input, to send unique ID
<input type="hidden" name ="input_id"
class="input_id" value="<?php echo $row['id']; ?>"/>
<input type="submit" name="post_answer1" onclick="sayHi(event);"
class="answer_L" id="<?php echo $row['id']; ?>"
value="<?php echo $row['post_answerL']; ?>"/>
</form>
// end of foreach
//AJAX
<script type="text/javascript">
function sayHi(e) {
var input_id = $(e.currentTarget).attr('id');
var post_answer1 = $("input[name='post_answer1']");
jQuery.ajax({
type: 'POST',
url: 'feed.php', //name of this file
data:input_id,post_answer1,
cache: false,
success: function(result)
{
alert ('It worked congrats');
}
});
e.preventDefault();
</script>
// PHP VOTE UPDATE FUNCTION
<?php>
if(isset($_POST['post_answer1'],$_POST['input_id'])){
$current_id = $_POST['input_id'];
$vote_1 = "UPDATE decision_post set " .
"post_answer1=post_answer1+1 WHERE id = '".$current_id."' ";
$run_vote1 = mysqli_query($conn2, $vote_1);
if($run_vote1){ echo 'Success'; }
}
?>
Here a simple answer, just serialize all your form data!
$('form').submit(function(){
$.post('feed.php', $(this).serialize(), function(data){
console.log(data);
}, 'json');
return false;
});
var post_answer1 = $("input[name='post_answer1']").val();
I have a form that will go through AJAX to set a session variable and back to the original page.
My problem is that I cannot set the session variable, thus, it is not working.
my main PHP page
<?php
if ($_SESSION['adminFunction'] == 'adminfunction'){
echo "<form id='userOptionRequest' action='request.php'>";
echo "<button name='adminFuncUserOption' onclick='adminFuncOption(1)'>User Option</button> <br /> <br />";
echo "<button name='adminFuncUserOption' onclick='adminFuncOption(2)'>Subject Option</button> <br /> <br />";
echo "<button name='adminFuncUserOption' onclick='adminFuncOption(3)'>Test Option</button> <br /> <br />";
echo "</form>";
}
if ($_SESSION['adminFunction'] == 'addusers'){
echo "hello world";
}
?>
my JS file
function adminFuncOption(option){
if (option == 1){
var userOptionRequest = new XMLHttpRequest();
userOptionRequest.open('POST','request.php',false);
xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
userOptionRequest.send('adminFuncUserOption=' + option);
return(1);
} }
the request.php
<?php
session_start();
$option = $_POST['option'];
if ($option != NULL){
if ($option == 1){
$_SESSION['adminFunction'] = 'addusers';
header('Location: http://rsc_naga_isd/admin');
}
}
var_dump($_POST);
var_dump($_SESSION);
var_dump($_GET);
?>
when I go back to my main PHP page, the session should now be addusers and should display 'hello world'
I have research but still had a hard time understanding AJAX or PHP
Submitting HTML form using Jquery AJAX
http://www.ajax-tutor.com/post-data-server.html
http://tutorialzine.com/2009/09/simple-ajax-website-jquery/
Oh, am still not familiar with jquery and still new to javascript, but would prefer javascript before diving in to jquery.
Hi jquery helps you to do more with less for example an AJAX call using jquery is like this:
$.ajax({
url: url,
type: 'POST',
data: data,
beforeSend: funtion(){
//DO Something before send like print a Loading text
},
success: function(data){
//DO SOMETHING IF DATA IS RETURNED
},
error: function(data){
//DO SOMETHING ON ERROR
}
});
Then you can check on you php scipt for the values sent on data for example:
if you send this data value:
data: {"adminFunction" : "mortal user not worthy" }
on your php script just do something like this:
switch($_POST['adminFunction'])
{
case 'superAdmin':
//....
break;
default:
//DO Something
break;
}
More info here:
AJAX JQUERY
In javascript you send:
userOptionRequest.send('adminFuncUserOption=' + option);
but in php:
$option = $_POST['option'];
it should be
$option = $_POST['adminFuncUserOption'];
I know you want javascript, but jquery so much easier ;)
$.post("request.php", { adminFuncUserOption: option }, function(response) {
console.log(response);
});
that's it then just check for $_POST['adminFuncUserOption']
The server side of the code (PHP) executes prior to the javascript side of the code. The server creates HTML (with javascript) to the client browser. The client browser then executes the code and javascript.
While your Session variable was updated, the requesting page was already created. You are going to need to reload the page that made the request in order to recognize the change to the session variable.
You could have the AJAX pass back non-sensitive data that you can process with javascript. If this is secure information that you don't want to be hacked, then I recommend avoiding AJAX until you get a better handle of it.