Accessing the PHP Variable in javascript - javascript

Good day to all of you Ma'am and Sir
I have a problem to my project (never mind the name of the project because it is for privately use and it is for security of the website).
The problem is I can not access or forward the PHP Variable value to the external javascript file.
this is the code in insert.php
<?php
$username = $_POST['username'];
?>
<input type="text" id="code"/>
<button id="con_btn"/>Continue</button>
this is the code in insert_auth.js
$(document).ready(function(){
$("#con_btn").click(function(){
var code = $("#code").val();
$.ajax({
method: "post",
url: "post.php",
data:{
code:code,
},
success: function(data){
$("#insertresult").html(data);
}
});
});
});
I just want to get the value of the $username from php file. Thanks in advance!

I take it as you already have the POST value : $_POST['username'];. So, I'd suggest you to store this value as a hidden input field.
<?php $_SESSION['username'] = $_POST['username']; // Store username in session ?>
<input type="text" id="code"/>
<button id="con_btn"/>Continue</button>
Now, in your JS, you can access this hidden field value:
$(document).ready(function(){
$("#con_btn").click(function(){
var code = $("#code").val();
var username = "<?php echo $_SESSION['username']; ?>" // Read username from session
$.ajax({
/* Other code */
});
});
});

Related

I cannot figure out why my ajax is not sending the data to my php file

I'm having a problem with my Ajax. It seems to not be sending the data to my php file even though it worked properly 2 days ago. HTML:
<form id='comment' action='process.php' method="POST">
<textarea></textarea>
<button type='submit'>Comment</button>
</form>
My ajax code:
$('#comment').submit(function(event) {
var form = $(this);
var method = form.attr('method');
var url = form.attr('action');
info = {
comment: $('textarea').val()
};
console.log(method);
console.log(url);
console.log(info);
$.ajax({
type: method,
url: url,
data: info,
success: function(data){
alert(data);
}
});
event.preventDefault();
});
I'm doing this for a friend and I'm using this exact same Ajax code (slightly modified) on my website and it's working flawlessly.
I think the biggest red flag here is that in my php file I have an if-else that should send an alert in case the textarea is empty but for some reason it's not doing that here even though nothing is getting through. I used console.log on all the variables to see if their values are correct and they are. The alert(data) just returns an empty alert box.
EDIT: As requested, PHP code from process.php
<?php
session_start();
include_once 'db_connection.php';
date_default_timezone_set('Europe/Zagreb');
if(isset($_POST['comment'])){
function SQLInsert($id, $date, $komentar, $conn){
$sql = "INSERT INTO comments (user, date, comment) VALUES ('$id', '$date',
'$comment')";
$conn -> query($sql);
$conn -> close();
}
$id = $_SESSION['username'];
$date = date('Y-m-d H:i:s');
$comment = htmlspecialchars($_POST['comment']);
SQLInsert($id, $date, $komentar, $conn);
} else {
echo '<script>';
echo 'alert("Comment box is empty.");';
echo '</script>';
}
?>
EDIT: Problem solved, thanks for the help everyone.
You are no getting alert because you are no displaying anything as response in php file. Add the insert function out side the if condition too
function SQLInsert($id, $date, $komentar, $conn){
$sql = "INSERT INTO comments (user, date, comment) VALUES ('$id', '$date',
'$comment')";
if($conn -> query($sql)){
return true;
}else{
return false;
}
$conn -> close();
}
if(isset($_POST['comment'])){
$id = $_SESSION['username'];
$date = date('Y-m-d H:i:s');
$comment = htmlspecialchars($_POST['comment']);
$insert = SQLInsert($id, $date, $komentar, $conn);
//On based on insert display the response. After that you will get alert message in ajax
if($insert){
echo 'insert sucess';
die;
}else{
echo 'Error Message';
die;
}
}
<form id='comment' action='process.php' method="POST">
<textarea></textarea>
<button id="submit_button">Comment</button>
</form>
starting from this html you have to trigger your function as:
$("#submit_button").click(function(e){
I have added an id to your button for simplicity and removed the type because it is useless in this case.
If you want to catch the submit event of the form you have to change your html as:
<form id='comment' action='process.php' method="POST">
<textarea></textarea>
<input type='submit'>Comment</button>
</form>
and then you can keep the same javascript
This here is the issue. Have you tried providing a "method" ?
$.ajax({
**type: method,**
method : method,
url: url,
data: info,
success: function(data){
alert(data);
}
});
Also if this doesn't solve it. show me the console output
<form name="fileInfoForm" id='comment' method="post" enctype="multipart/form-data">
<textarea id="textarea"></textarea>
<button type="submit"></button>
</form>
<script type="text/javascript">
$('#comment').submit(function (e) {
e.preventDefault();
var textarea=$('#textarea').val();
var form=document.getElementById('comment');
var fd=new FormData(form);
fd.append('textarea',textarea);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: 'action.php',
data: fd,
dataType: "json",
processData: false,
contentType: false,
cache: false,
success: function (data) {
alert(data);
}
})
});
</script>
in action.php
$textarea= $_POST['textarea'];
echo $textarea;

Pass javascript prompt input to PHP variable

So I am working on a code signing system for iOS. I need a user's UDID before they can access the website. How can I pass the javascript prompt input to a php variable.
I have tried posting the variable back to the same page.
<?php
$udid = $_POST['udid'];
if(empty($udid)){
$udid = file_get_contents("saves/" . $ip . ".txt");
}
if(empty($udid)){
?>
<script>
var udid=prompt("Please enter your UDID");
$.ajax(
{
type: "POST",
url: "app.php",
data: udid,
success: function(data, textStatus, jqXHR)
{
console.log(data);
}
});
</script>
<?php
}
if( strpos(file_get_contents("cert1.txt"),$udid) !== false) {
echo "Device status:<br><span class='badge badge-dark'>Signed</span><br>";
echo "Signed on cert:<br><span class='badge badge-dark'>1</span><br>";
} else {
$t = ' ' . time();
echo "<p>Device status:<br><span class='badge badge-dark'>Unsigned</span><br>You are now<br>on the waitlist</p><script>alert(\"Your device isn't approved yet. We have added you to the waitlist. Check back soon.\");</script>";
$txt = $_GET['udid'] . $t;
$myfile = file_put_contents('notsigned.txt', $txt.PHP_EOL , FILE_APPEND | LOCK_EX);
header("Location: notsigned.php");
}
?>
<br>
Get your udid
<br><br>
<form class='form-horizontal well' action='#' method='post'>
<input type='text' name='udid' class='input-large' size="9" border="2" placeholder="udid" value='<?= $udid ?>'>
<button type="submit" id="submit" style="text-decoration:none;font-family:arial;font-size:15px;color:#fff;padding:8px;border-radius:5px;background-color:springgreen;margin-bottom:5px;" class="badge-primary">Save</button>
</form>
<?php
setcookie("udid", $udid, time()+31536000000, "/");
file_put_contents("saves/" . $ip . ".txt",$udid);
if(empty($udid)){
alert('You cannot access anything till you enter your udid.');
}
?>
What I need it to do is set $udid (PHP) to what the user entered in either the prompt or the input form.
reposting my comment as an answer (with a little more detail):
You should have data: {udid: udid} rather than data: udid. The documentation says that data should be on "object, string or array", but it only mentions a string in the explicit case that it's a query string (eg ?key1=value1&key2=value2). By passing it as an object as shown then you ensure that the PHP backend will be able to access $_POST['udid'] and it will have the intended value.
Note: this object can be abbreviated as just data: {udid} if you're using ES6.
Change the data attribute to the following,
data: {
udid: udid
},

how to make submit button both send form thru' PHP -> MySQL and execute javascript?

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>

Unable to pass javascript variable to PHP through ajax?

I have searched through a couple of QA here at stackoverflow, none of solutions seemed to help. I am trying to pass input to my PHP file but for some reason the inputdoesn't get passed from javascript to and it keeps on returning undefined on the console.
my javascript:
$.ajax({
type:"GET",
url:"go.php",
data:{input:input},
success:function(data){
console.log(data); //data outputs https://mp3skull.wtf/search_db.php?q=&fckh=1d41a1579f21a921d1008d90dc6246a7
}
});
my php:
<?php
$input = $_GET['input']; //$input here is empty
$keywords= explode(" ",$input);
$link = "https://mp3skull.wtf/search_db.php?q=" . $keywords[0];
for($i = 1; $i < count($keywords); $i++){
$link .= "+" . $keywords[$i];
}
$link .= "&fckh=1d41a1579f21a921d1008d90dc6246a7";
echo $link; //$keywords is not appended to $link
?>
the code works you probably console.log from outside the ajax call.
hi first you need to declare it as a variable. Second does your variable really have a value? I'll give u sample you can run your code do it something like this
var input = $("#input").val();
$.ajax({
type:"GET",
url:"go.php",
data:{input:input},
success:function(data){
console.log(data); //data outputs https://mp3skull.wtf/search_db.php?q=&fckh=1d41a1579f21a921d1008d90dc6246a7
}
});
hope this helps
If you have the following Html:
<input type="text" class="field" />
<input type="button" class="button">
You should use the following script:
$(document).ready(function() {
$('.button').click(function(){
$.ajax({
type:"GET",
url:"go.php",
data:{'input':$('input.field').val()},
success:function(data){
console.log(data);
}
});
});
});
I think it's because when you send data in "data: { input: input } " are defining the variable input with the same name. It should be like that
var inputValue = $("#idInput").val();
$.ajax({
type:"GET",
url:"go.php",
data:{input:inputValue},
success:function(data){
console.log(data);
}
});

How to post data without a form

Good day sir/ma'am I am a new programmer, I would like to ask how to post data like the functionality of form that when submitting the form the URL in action will display using javascript.
"WITHOUT USING A FORM" or using xmlHTTP that not return to main page
sample is
HTML
<input type="button" value="revise" onclick="revisetask(<?php echo $id; ?>)">
JS
function revisetask(idtask)
{
//In this function sir i would like to post here
}
Im very sorry if my english is too bad.. thanks in advance :D
You can use javascript for submitting the values of input boxes,
to do so,
write a javascript function which will read all your input boxes values into javascript variables,
Prepare a URL, and call that URL using window.location.href
function SubmitMyForm
{
var Firstname = document.getElementbyId('FirstName').value;
var Lastname = document.getElementbyId('LastName').value;
var URL="myDBoperations.php?firstname="+Firstname+"&lastname="+Lastname;
window.location.href= URL;
}
On the operations form you will receive these value in GET.
Hope this will help you.
U can use ajax for this. U don't need a form for ajax post, and it won't refresh the page too.
Below is an example code
<input type="text" id="test_name" />
<input type="button" value="Submit" obclick="save_this()" />
<script type="text/javascript">
function save_this(){
var text = $('#test_name');//stores te value in text field
$.ajax({
url: 'http://example.com/test.php',//your URL
type: 'POST',
data: { text: text },
success: function(data){
alert(data);
}
});
}
</script>
test.php
<?php
echo $_POST['text'];
As I've seen in this code:
<input type="button" value="revise" onclick="revisetask(<?php echo $id; ?>)">
I assume and believe that the reason why you don't want to use form because you want your $id to be submitted through javascript/jquery. But alternatively, you could just do it this way:
HTML:
<form method = "POST" action = "updatetask.php">
<input type = "hidden" value = "<?php echo $id; ?>" name = "taskid" id = "taskid"/>
<input type = "submit" value = "UPDATE" name = "updatebutton">
</form>
PHP:
<?php
$taskid = $_POST['taskid'];
?>
In the above code I just set the type hidden and which contains the value of your $id in which would be post in your Php file.
UPDATE:
If it still doesn't fit to what you want then you could just have this other alternative which will be using the GET method: <a href = "updatetask.php?id='<?php echo $id; ?>' REVISE </a>"
That's the only option you have. and if you don't want to show the id in your url then you could just use URL Rewriting (refer to this link: https://www.addedbytes.com/articles/for-beginners/url-rewriting-for-beginners/)
Hope this helps.

Categories

Resources