Pass javascript prompt input to PHP variable - javascript

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
},

Related

Live Search Box Using PHP, MySQL and AJAX

I am trying to make an search box which to display the "Address" from MYSQL/PHP
I have used ajax to refresh page without leaving page, but when I run in browser, it always give me an error. when I used console, the return result of echo $_POST['name'] = ( html code of header.php + "What I need" + html code of footer.php )
<?php
include 'header.php';
include 'Connect.php';
if( isset($_POST['ajax']) && isset($_POST['name']) ){
echo $_POST['name'];
exit;
}
?>
<form method="POST">
<label>Username</label>
<input type="text" name="name" required="required" id='name'>
<div id='response'></div>
</form>
<script>
$(document).ready(function(){
$('#name').keyup(function(){
var name = $('#name').val();
$.ajax({
type: 'post',
url: index.php,
data: {ajax: 1,name: name},
success: function(response){
$('#response').text(response);
}
});
});
});
</script>
<?php
if(isset($_POST['name'])){
$username = $_POST['name'];
$stmt = $con->prepare("SELECT Username, FullName, Adresse, Email, Phone FROM dbo.users WHERE Username= ?");
$stmt->execute(array($username));
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
$Username = $row["Username"];
$FullName = $row["FullName"];
$Adresse = $row["Adresse"];
$Email = $row["Email"];
$Phone = $row["Phone"];
echo "<tr>
<div>
<td>".$Username."</td>
<td>".$FullName."</td>
<td>".$sEID."</td>
<td>".$Email."</td>
<td>".$Phone."</td>
</div>
</tr>";
}
echo "</table>
</div>";
} else echo '<div class="alert alert-danger"> This Name <strong>is not exit</strong></div>';
include $tpl.'footer.php';
}
?>
Your question isn't very clear... if i understand correctly... this is broken by design, you're calling the page itself and update #name with the content of the entire page, thats why you see html + "what you need" (the response): the response is the whole page.
The right way to do this would be to move the second part of PHP code (where you perform the query ecc.) on a separate script and then call that new script by putting its name as the url parameter in the ajax call.
thank you for your respanse, i want to use the value returned by ajax to use with MYSQL/PHP to echo $row['Address'];
if i move the second part of PHP code the result is
echo $_POST['name'] = ( "What I need" + html code of footer.php )

Php post form without refresh page

I try to post my form to Mysql without refreshing page. I did these with looiking sources but not working. Could you help me?
<script>
$('#submit').click(function() {
$.ajax({
url: 'submit.php',
type: 'POST',
data: {
message: '*I couldnt find this partwhat should i write*'
}
}
});
});
</script>
<form method="post">
<textarea name="message" rows="3" cols="30">
</textarea><br><br>
<input type="submit" value="Submit">
</form>
Submit.php
<?php
include "connect.php";
if(isset($_POST['message'])) {
header('Location: ' . $_SERVER['HTTP_REFERER']);
$post = $_POST['message'];
$date = date("y-m-d G:i:s");
$query = $db->prepare("INSERT INTO chat_messages SET senderid = ?, receiverid = ?, message = ?, mod_time = ?");
$insert = $query->execute(array( $a, $b, $post, $date));
}?>
In jQuery, the click event is being triggered on an element that has an id of submit (it is id because it is represented by #)
$('#submit').click(function() {
Your submit button does not have the ID of "submit"
Change the input tag as follows:
<input id="submit" type="submit" value="Submit" />
Another problem, as #Rajan in comments pointed out, you have an extra brace. So, change:
data: {
message: '*I couldnt find this partwhat should i write*'
}
}
to:
data: {
message: '*I couldnt find this partwhat should i write*'
}
Also, I recommend that you show return some kind of message from submit.php page, for example:
echo 'Entry Added';
The above is just an example output to get you going... you really should be doing checks such as: did the entry get inserted without any errors, etc.
Edit
Also note: you are using type as one of the settings. Per the official jQuery documentation of jQuery.ajax(), type is:
An alias for method. You should use type if you're using versions of jQuery prior to 1.9.0.
(i.e. use method instead, if using jQuery version >1.9.0)
Lastly, take a look at the answer provided by #Faisal as well...
You are submitting form data through Ajax query, hence you do not need to include header('Location: ' . $_SERVER['HTTP_REFERER']); in your submit.php file.
<form>
<textarea name="message" rows="3" cols="30"></textarea>
<br>
<input type="submit" value="Submit">
</form>
<script>
$(document).ready( function() {
$("form").on("submit", function(e) {
e.preventDefault(); // Prevent default form submission action
$.post("submit.php", $("form").serialize()); // Post the data
$('textarea[name=message]').val(''); // Clear the textarea
});
});
</script>
Also, are the variables $a and $b defined in submit.php file?
$.post('../submit.php',{message:message}, function(data) {
$('.results').html(data);
});
use a div where you want to display the result
<div class="results"></div>
to finish your submit.php have to send something at the end so try this
<?php
include "connect.php";
if(isset($_POST['message'])) {
header('Location: ' . $_SERVER['HTTP_REFERER']);
$post = $_POST['message'];
$date = date("y-m-d G:i:s");
$query = $db->prepare("INSERT INTO chat_messages SET senderid = ?, receiverid = ?, message = ?, mod_time = ?");
$insert = $query->execute(array( $a, $b, $post, $date));
}
echo "it works";
?>

ajax -- add comments asynchronously

I have two php files that handle a commenting system I have created for my website. On the index.php I have my form and an echo statement that prints out the user input from my database. I have another file called insert.php that actually takes in the user input and inserts that into my database before it is printed out.
My index.php basically looks like this
<form id="comment_form" action="insertCSAir.php" method="GET">
Comments:
<input type="text" class="text_cmt" name="field1_name" id="field1_name"/>
<input type="submit" name="submit" value="submit"/>
<input type='hidden' name='parent_id' id='parent_id' value='0'/>
</form>
<!--connects to database and queries to print out on site-->
<?php
$link = mysqli_connect('localhost', 'name', '', 'comment_schema');
$query="SELECT COMMENTS FROM csAirComment";
$results = mysqli_query($link,$query);
while ($row = mysqli_fetch_assoc($results)) {
echo '<div class="comment" >';
$output= $row["COMMENTS"];
//protects against cross site scripting
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8');
echo '</div>';
}
?>
I want users to be able to write comments and have it updated without reloading the page (which is why I will be using AJAX). This is the code I have added to the head tag
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
// this is the id of the form
$("#comment_form").submit(function(e) {
var url = "insert.php"; // the script where you handle the form input.
$.ajax({
type: "GET",
url: url,
data: $("#comment_form").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
</script>
However, nothing is happening. The alert() doesn't actually do anything and I'm not exactly sure how to make it so that when the user comments, it gets added to my comments in order (it should be appending down the page). I think that the code I added is the basic of what needs to happen, but not even the alert is working. Any suggestions would be appreciated.
This is basically insert.php
if(!empty($_GET["field1_name"])) {
//protects against SQL injection
$field1_name = mysqli_real_escape_string($link, $_GET["field1_name"]);
$field1_name_array = explode(" ",$field1_name);
foreach($field1_name_array as $element){
$query = "SELECT replaceWord FROM changeWord WHERE badWord = '" . $element . "' ";
$query_link = mysqli_query($link,$query);
if(mysqli_num_rows($query_link)>0){
$row = mysqli_fetch_assoc($query_link);
$goodWord = $row['replaceWord'];
$element= $goodWord;
}
$newComment = $newComment." ".$element;
}
//Escape user inputs for security
$sql = "INSERT INTO parentComment (COMMENTS) VALUES ('$newComment')";
$result = mysqli_query($link, $sql);
//attempt insert query execution
header("Location:index.php");
die();
mysqli_close($link);
}
else{
die('comment is not set or not containing valid value');
it also filters out bad words which is why there's an if statement check for that.
<?php
if(!empty($_GET["field1_name"])) {
//protects against SQL injection
$field1_name = mysqli_real_escape_string($link, $_GET["field1_name"]);
$field1_name_array = explode(" ",$field1_name);
foreach($field1_name_array as $element)
{
$query = "SELECT replaceWord FROM changeWord WHERE badWord = '" . $element . "' ";
$query_link = mysqli_query($link,$query);
if(mysqli_num_rows($query_link)>0)
{
$row = mysqli_fetch_assoc($query_link);
$goodWord = $row['replaceWord'];
$element= $goodWord;
}
$newComment = $newComment." ".$element;
}
//Escape user inputs for security
$sql = "INSERT INTO parentComment (COMMENTS) VALUES ('$newComment')";
$result = mysqli_query($link, $sql);
//attempt insert query execution
if ($result)
{
http_response_code(200); //OK
//you may want to send it in json-format. its up to you
$json = [
'commment' => $newComment
];
print_r( json_encode($json) );
exit();
}
//header("Location:chess.php"); don't know why you would do that in an ajax-accessed file
//die();
mysqli_close($link);
}
else{
die('comment is not set or not containing valid value');
}
?>
<script>
// this is the id of the form
$("#comment_form").submit(function(e) {
var url = "insert.php"; // the script where you handle the form input.
$.ajax({
type: "GET", //Id recommend "post"
url: url,
dataType: json,
data: $("#comment_form").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
$('#myElement').append( data.comment );
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
</script>
To get a response from "insert.php" you actually need to print/echo the content you want to handle in the "success()" from the ajax-request.
Also you want to set the response-code to 200 to make sure "success: function(data)" will be called. Otherwise you might end up in "error: function(data)".

Using AJAX to send form information to another page using a button

Hello I have two files that are supposed to be connected to one another. I want to send an AJAX request to another page that uses a sql query to send form information.
The application that I'm trying to create is a questionnaire with eight questions, each questions has four answers paired together with the same id (qid) and each answer has a value from the database. After you answer eight questions you will see a button that sends an AJAX request to the page test.php, (named submitAJAX).
The problem is that although my connection with AJAX is working, the values from the form are not being sent to my database. Previously I thought that the problem may lie with the form page, but now I I think the problem lies in this file:
test.php (file with json)
<?php
$localhost = "localhost";
$username = "root";
$password = "";
$connect = mysqli_connect($localhost, $username, $password) or die ("Kunde inte koppla");
mysqli_select_db($connect, 'wildfire');
if(count($_GET) > 0){
$answerPoint = intval($_GET['radiobtn']);
$qid = intval($_GET['qid']);
$tid = intval($_GET['tid']);
$sql2 = "INSERT INTO result (qid, points, tid) VALUES ($qid, $answerPoint, $tid)";
$connect->query($sql2);
$lastid = $connect->insert_id;
if($lastid>0) {
echo json_encode(array('status'=>1));
}
else{
echo json_encode(array('status'=>0));
}
}
?>
I think that the problem may lie in the row where: if($lastid>0) {
$lastid should always be more than 0, but whenever I check test.php I get this message: {"status":0} What's intended is that I get this message: {"status":1}
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<?php
$localhost = "localhost";
$username = "root";
$password = "";
$connect = mysqli_connect($localhost, $username, $password) or die ("Kunde inte koppla");
mysqli_select_db($connect, 'wildfire');
$qid = 1;
if(count($_POST) > 0){
$qid = intval($_POST['qid'])+1;
}
?>
<form method="post" action="">
<input type="hidden" name="qid" id="qid" value="<?=$qid?>">
<?php
$sql1 = mysqli_query($connect,"SELECT * FROM question where answer != '' && qid =".intval($qid));
while($row1=mysqli_fetch_assoc($sql1)){
?>
<input type='radio' name='answer1' class="radiobtn" value="<?php echo $row1['Point'];?>">
<input type='hidden' name='tid' class="tid" value="<?php echo $row1['tid'];?>">
<?php echo $row1['answer'];?><br>
<?php
}
?>
<?php if ($qid <= 8) { ?>
<button type="button" onclick="history.back();">Tillbaka</button>
<button type="submit">Nästa</button>
<?php } else { ?>
<button id="submitAjax" type="submit">Avsluta provet</button>
<?php } ?>
</form>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script type="text/javascript">
function goBack() {
window.history.go(-1);
}
$(document).ready(function(){
$("#submitAjax").click(function(){
if($('.radiobtn').is(':checked')) {
var radiobtn = $('.radiobtn:checked').val();
var qid = $('#qid').val();
var answer = $('input[name=answer1]:radio').val();
$.ajax(
{
type: "GET",
url: 'test.php',
dataType: "json",
data: "radiobtn="+radiobtn+"&qid="+qid,
success: function (response) {
if(response.status == true){
alert('points added');
}
else{
alert('points not added');
}
}
});
return false;
}
});
});
</script>
</body>
The values that I want to send to my database from test.php are:
qid(int), tid(int), Point(int)
There is a database connection, and my test.php file's sql query should work, but its not sending form information. Is there something that I need to rewrite or fix to make it work?
First, your data parameter in the AJAX call is not using the correct syntax. You're missing brackets. It should look like:
data: JSON.stringify({ radiobtn: radiobtn, qid: qid }),
Second, I'd suggest using POST instead of GET:
type: "POST",
which means that you need to look for your data in $_POST['radiobtn'] and $_POST['qid'] on test.php. NOTE: you should check for the key you expect using isset() before assigning the value to a variable, like so:
$myBtn = isset($_POST['radiobtn']) ? $_POST['radiobtn'] : null;
Third, for testing, use a console.log() inside your condition that checks for the checkbox being checked in order to verify that condition is working as expected.
if($('.radiobtn').is(':checked')) {
console.log('here');
UPDATE:
Fourth: You should specify the content type in your AJAX call, like so:
contentType: "application/json; charset=utf-8",
After you execute your query that inserts the result you can use a sql statement to select the last insert id. Try something like
$sql2 = "INSERT INTO result (qid, points, tid) VALUES ($qid, $answerPoint, $tid)";
$connect->query($sql2);
$result = $connect->query("SELECT LAST_INSERT_ID()");
$row = $result->fetch_row();
$lastid = $row[0];
That should return the correct last insert id, if that was where your error was occurring.
mysqli_insert_id() returns the ID generated by a query on a table with a column having the AUTO_INCREMENT attribute.
In your SQL, you are providing the ID yourself, there is no auto-increment. So you should get 0 from $connect->insert_id, because the function returns zero if there was no previous query on the connection or if the query did not update an AUTO_INCREMENT value.
For your purpose, you can use the return value of mysqli_query() instead, which returns TRUE on success and FALSE on failure.
if($connect->query($sql2)) {
echo json_encode(array('status'=>1));
}
else{
echo json_encode(array('status'=>0));
}

AJAX form submission with php and jquery

I have looked at everything on here that I can find and I just can't figure out why I cannot perfect this code. What I am trying to do is allow users to delete something that they posted on my site without doing a page refresh. The form is going to be passed to a php file that will modify my MySQL DB. I am new to ajax and have only messed around with PHP for a short time as well.
form:
<form class='status_feedback' id='delete_status' onsubmit='delete_status()' action=''>
<input type='hidden' name='status_id' id='status_id' value='$status_id'/>
<input type='submit' value='X'/>
</form>
delete_status()
function delete_status(){
$.ajax({
type: "POST",
url: "/scripts/home/php/delete_status.php/",
data: status_id,
success: function() {
//display message back to user here
}
});
return false;
}
delete_status.php
<?php
$con=mysqli_connect("localhost","USER","PASSWORD","DB");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$status_id = $_POST['status_id'];
mysqli_query($con,"UPDATE status SET visibility = 'hidden' WHERE id = $status_id");
?>
at this point, all that happens when I strike the delete_status() function is my page refreshes and adds ?status_id=194 (when I click on status #194) to the end or my url.
Any help would be awesome. I have been researching for several days.
Change your HTML, Ajax and php a little.
HTML
Add this code:
<body>
<form class='status_feedback' id='delete_status' >
<input type='hidden' name='status_id' id='status_id' value='$status_id'/>
<input type='button' id='x_submit' value='X' />
</form>
<script>
$('#x_submit').on("click",function(){
var status_id= $('#status_id').val();
//Delete the alert message if you want.
alert("Check your status id :"+status_id);
$.ajax({
type: "GET",
url: "/scripts/home/php/delete_status.php?",
data: {status_id:status_id},
dataType:'JSON',
success: function(json) {
//display message back to user here
alert(json[0].response);
}
});
});
</script>
PHP:
<?php
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Methods: GET, POST');
header('Content-type: application/json');
$con=mysql_connect("localhost","USER","PASSWORD","DB");
// Check connection
if (mysql_connect_errno())
{
echo "Failed to connect to MySQL: " . mysql_connect_error();
}
$status_id = $_GET['status_id'];
$result = mysql_query("UPDATE status SET visibility = 'hidden'
WHERE id = '$status_id'");
if(! $result )
{
$data[]=array('response'=>"Unable to insert!");
}
else
{
$data[]=array('response'=>"Data successfully inserted into the database!");
}
$json_encode = json_encode($data);
print("$json_encode");
?>
Hope it will work.
You are not cancelling the form submission
onsubmit='delete_status()'
needs to be
onsubmit='return delete_status()'
and data: status_id, looks wrong unless you have a variable defined somewhere else

Categories

Resources