I have a database and I get info from it and put it into php page. BUT the thing is, I cant put data from that php file to database. I use form to put there the value of variable, but it says [html span element]. and I get errors:
Notice: Undefined index: souls in xxx/the_cave.php on line 20
Notice: Undefined index: bones in xxx/the_cave.php on line 21
Here is the code:
JS:
document.getElementById("souls_form").value=<?php echo $souls_value; ?>;
document.getElementById("bones_form").value=<?php echo $bones_value; ?>;
function upload(){
<?php upload(); ?>}
PHP part:
$current_souls=$_POST['souls'];
$current_bones=$_POST['bones'];
function upload(){
mysqli_query($db,"UPDATE Data SET Souls=$current_souls, Bones=$current_bones WHERE Username='$username'");
HTML form
<form style="visibility:hidden" action="" method="post">
<input name="souls" id="souls_form">
<input name="bones" id="bones_form">
</form>
UPDATED CODE
<script>
var souls1=<?php echo $souls_value;?>
var bones1=<?php echo $bones_value;?>
//do your process
//after the values changes for variables souls1,bones1
//YOU HAVE TO CALL AJAX CALL TO SAVE YOUR UPDATED VARIABLES DATA INTO DB
$.ajax({
url:'updatedata.php',
type:"POST",
data:{souls:souls1,bones:bones1},
success:function(result)
{
if(result)
{
alert('updated succesfully');
}
}
});
updatedata.php
<?php
if(isset($_POST['souls'])&&isset($_POST['bones']))
{
$current_souls=$_POST['souls'];
$current_bones=$_POST['bones'];
if(mysqli_query($db,"UPDATE Data SET Souls='$current_souls', Bones='$current_bones' WHERE Username='$username'"))
{
echo 'TRUE';
}
}
?>
As the Php code executes first than all other codes, the $current_souls=$_POST['souls']; is executing first so you have to check form submission using isset() other wise no error will be printed
Related
Here is the situation.
I'm trying to pass from some Javascript values to various PHP functions within my ajax so it can properly be displayed on the page.
Here is my code:
$("[data-department-id]").click(function() {
id = $(this).attr('data-department-id');
document.getElementById('department'+id).innerHTML = '';
$.ajax({
url:"/desk/template/fetchtickets.php",
type: 'POST',
dataType: 'json',
data : {
'id' : id
},
success: function (res) {
$('#department'+id).append('<ul>');
for (var key in res) {
var ticketId = res[key].id;
var clientId = res[key].clientid;
var clientName = res[key].name;
var clientColor = res[key].hexColor;
<?php $ticketId = '"+ticketId+"'; ?>
<?php $clientId = '"+clientId+"'; ?>
<?php $clientName = '"+clientName+"'; ?>
<?php $clientColor = 'clientColor'; ?>
$('#department'+id).append('<li class="list-group-item list-group-item-light" data-date-2="<?php echo Ticket::lastReplyStamp($ticketId); ?>"> <span class="text-width">'+res[key].ticket+' '+res[key].subject+'</span><div class="tools" ><span class="client-listing"> <?php clientBadge($clientId,$clientName,$clientColor); ?> <?php // echo "<scipt>document.writeln(test)</script>"; ?> '+test+' </div></div></li>');
}
$('#department'+id).append('</ul>');
}
});
})
When I do a console.log();
It shows the proper value, however, when I do an echo $ticketId, it shows +ticketId+ .
Now I did do a document.write and document.writeln and it still doesn't work.
Is there a proper solution to resolve my problem?
You can not add php code here.You can use JQuery to change value in the Dom or set some hidden inputs value, but you can not set php variable in JS. PHP runs on the server side. When the php code is running, your js code is waiting to be run on the client's computer.
These line are always going to be interpreted as string assign from server side.
<?php $ticketId = '"+ticketId+"'; ?>
<?php $clientId = '"+clientId+"'; ?>
<?php $clientName = '"+clientName+"'; ?>
<?php $clientColor = 'clientColor'; ?>
The order of your code processing is something like this :
PHP code get processed
PHP returns HTML
User clicks an element (in your case data-department-id)
JQuery sends ajax request
Server processes the request and sends response back to the frontend
Ajax success function receives the response and now has the response in javascript variable res which is passed as argument of success(res) function
All the code inside success is executed
Alternatively if the server throws an error response, no 6. and 7. would trigger the error callback
But the main part it, the PHP code in your success() function will NOT run as you are thinking, which is after the Ajax receives response. At this point all you can do is use javascript to manipulate the variables.
So in short, change below part and use javascript or jQuery if you have it to change DOM elements based on response.
<?php $ticketId = '"+ticketId+"'; ?>
...
...
For example, let's say you have an H1 tag which shows ticket id. You would do
// jQuery
$('#ticketIdElement').text(res.id);
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();
}
?>
I am trying to send form data and js array to mysql database. I am having problem with receiving js array into my php. I receive data from form but not the array. I can't find the problem.
index.php
<!doctype html>
<html lang="en">
<head>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"><!--bootstrap-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script><!--jquery-->
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script><!--angular js-->
<script type="text/javascript" src="assets/js/main.js"></script>
</head>
<body>
<form method="post" action="upload.php">
<!--dynamic form created from javascript-->
<input id="submit" type="submit" value="Upload" name="submit" onclick="upload()"/>
</form>
</body>
</html>
javascript -- main.js
var objArray = []; //Array of questions
function upload(){
var jsonArray = JSON.stringify(objArray);
$.ajax({
type:'post',
url: 'upload.php',
data: { jsonData : jsonArray},
success: function(data){
console.log("success!");
}
});
} else {
console.log("no data javascript!");
}
}
upload.php
<?php
if(($_SERVER['REQUEST_METHOD'] == "POST") && (isset($_POST['submit']))){
$servername = "......";
$username = "......";
$password = "......";
$dbname = ".....";
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(!empty($_POST['jsonData'])){
$json = $_POST['jsonData'];
var_dump(json_decode($json, true));
echo "<script type=\"text/javascript\">
console.log('received data');
</script>";
} else {
echo "data not received";
}
$conn->close();
}else {echo "unsecure connection";}
?>
objArray looks like this:
[{"questionId":1,"questionTypeObj":"single","options":3},{"questionId":2,"questionTypeObj":"single","options":3}]
upload.php outputs "data not received"
Your output indicates what the problem is: You get to the part where you echo data not received but you are not sending a submit key: $_POST['submit'] is not set when called through ajax.
So you are submitting your form the "normal" way and not through ajax.
This is caused by the fact that you are not cancelling the default submit action of your button.
The best way to solve that (in my opinion...), is to remove the inline javascript - the click handler - and replace your function with:
$("form").on('submit', function(e) {
// Cancel the default form submit
e.preventDefault();
// The rest of your function
var jsonArray = JSON.stringify(objArray);
...
});
Note that I am catching the form submit event. You could also replace that with the button click event but that might not work correctly when a visitor uses the enter key in a form field.
You shouldn't be doing it this way. There's no way to guarantee that the javascript will execute before you redirect. In fact, it won't run fast enough, and will just redirect to the next page. Try
<form method="post" action="upload();">
This will get the data to the page, but it won't display it. If you want it displayed you should have forms submitting it. If you post with ajax you can also try to catch the response with jquery.
when you click the button your code are going to send 2 requests to the server
First request-the ajax
this ajax request has the parameter you need jsonData : jsonArray
and right after that you are going to send another request
Second request-submitting the form
and the form has no jsonData : jsonArray paramter sent with it
you don't need this ajax at all!
all you need to do to receive the jsonData : jsonArray paramter is to send it along with the form
for example:
change your form to be like this
<form method="post" action="upload.php">
<input id="jsonData" type="hidden" name="jsonData" value="">
<input id="submit" type="submit" value="Upload" name="submit" onclick="upload()"/>
</form>
and change your button function to be like this
function upload(){
var jsonArray = JSON.stringify(objArray);
$('input#jsonData')[0].value=jsonArray ;
}
EDIT :
Or if you want upload.php to process the ajax request, and not to response with a whole document then you don't need the form, remove the form from your HTML , and just add submit:Upload to the ajax request
data: { jsonData : jsonArray, submit:"Upload" }
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 am now about to give up for ajax in javascript to pass JSON array to PHP. I have first PHP file in which I have form which contains a text area and checkboxes. The snippet is below:
<form name="drugForm" onsubmit="return validateForm()" method="post">
Drug name: <input type="text" name="dname"></pre>
<pre>
<input type="checkbox" name="drug" value="one">1 <input type="checkbox" name="drug" value="two">2</br>
<input type="checkbox" name="drug" value="three">3 <input type="checkbox" name="drug" value="four">4</br></br>
<input type="submit" value="Submit">
</pre>
Here, with validateForm() call I am calling javascript to check whether text area is filled and at least a checkbox is checked. Also, it is creating array, in javascript, to get checked values. Here with this js I want to send this array to PHP file by converting it JSON using ajax. COde snippet is below:
function validateForm()
{
var x=document.forms["drugForm"]["dname"].value;
var y=document.drugForm.drug;
var y_array = new Array();
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
else if (Boolean(x))
{
for(k=0;k<y.length;k++)
{
if(y[k].checked)
{
var arr_val = y[k].value;
y_array.push(arr_val);
//alert(arr_val);
}
}
$.ajax({
type: "POST",
url: "drug_form3.php",
dataType: 'json',
data: {json: JSON.stringify(y_array)},
});
alert("Check one checkbox at least");
return false;
}
}
Here, with js array is getting created and whenever I am printing values with alert, it is giving proper result. But, when I am trying to send it to next PHP file even after using json_decode in php file, it is not able to get array printed with PHP. Below is code snippet for second PHP:
<body>
<?php
$json = $_POST['json'];
$array=json_decode($_POST[$json]);
// here i would like use foreach:
print_r ($array);
echo "Its in form2 and working fine";
?>
</body>
Please guide me in this issue, how to pass json array to PHP file using javascript.
You have the following lines confused:
$json = $_POST['json'];
$array=json_decode($_POST[$json]);
Change to:
$array=json_decode($_POST['json']);
Can you try this and check whether you getting the post values here,
$json = $_POST['json'];
echo "<pre>"; print_r($json);echo "</pre>";
Try this and see if it works for you
$array = json_decode($_POST['json'], true);