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 3 years ago.
Improve this question
I am trying to post a form to a PHP script, and it is getting stuck at validating the request as a POST request, and thus it exits from the PHP script. The AJAX request returns as successful, but the data returned from the database says the recognition of the request as POST failed. I've tried changing the content types etc, to no avail.
JS:
$(document).ready(function() {
$("#delete4").on('click', function(e) {
e.preventDefault();
var ok = confirm('Are you sure you want to delete this?');
if (ok == true)
{
console.log("true")
var data = $("#form4").serialize();
$.ajax({
data: data,
type: "post",
url: "delete_AJAX.php",
success: function(data) {
console.log("successfully deleted");
console.log(data);
//$("#div4").remove();
},
error: function(data) {
alert("fail");
console.log(data);
}
});
} else {
return;
}
});
});
HTML:
<form type="text" name="form4" id="form4" action="delete_AJAX.php" method="post">
<div class="aligner">
<button type="button" class="button_div" name="edit" onclick="send(52)">Edit</button>
<button type="button" class="button_div" id="delete4">Delete</button>
<button type="button" class="button_div" name="read" onclick="send2(52, 13)">See</button>
</div><br>
<input type="hidden" id="hidden_c4" value="13" name="hidden_c">
<input type="hidden" id="hidden_bid4" name="hidden_bid" value="52">
</form>
PHP:
require_once("db.php");
if ($_REQUEST['REQUEST_METHOD'] === 'POST')
{
$bid = $_POST['hidden_bid'];
echo "passed request";
$sql = "SELECT * FROM xxx WHERE yyy = $bid";
$result = mysqli_query($connection, $sql);
if ($result === false)
{
die("f1");
}
$resultCheck = mysqli_num_rows($result);
if (!resultCheck > 0)
{
echo "ERROR NO RESULT";
exit();
};
$row = mysqli_fetch_assoc($result);
$delete_cover = $row['cover'];
unlink($delete_cover);
// updating table row
$sql2 = "DELETE FROM xxx WHERE (yyy=?);";
$stmt = mysqli_stmt_init($connection);
if (!mysqli_stmt_prepare($stmt, $sql2))
{
header("Location: ../create.php?error&prepare1111");
exit();
}
else
{
$stmt->bind_param("i", $bid);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
$connection->close();
echo "successfully deleted";
}
} else {
echo "FAILURE TO REQUEST";
}
So I keep consistently getting failure "FAILURE TO REQUEST", and when I remove any barrier to the script, post is shown as empty, and the variables arent set. Thus it stops at the "f1" error. Any help would be amazing!! Thankyou!
You seem to be using the wrong global variable for the "REQUEST_METHOD".
Instead of $_REQUEST['REQUEST_METHOD'] use $_SERVER['REQUEST_METHOD']
In the conditional,
$_REQUEST['REQUEST_METHOD'] should be replaced with $_SERVER['REQUEST_METHOD'].
Maybe could this help
if( $_POST ) {
echo 'posted';
//do some stuff
}
Related
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
So our project is to make an ordering website, we had everything down design-wise. Now that the designing is done, we're now focused to the function of the website. I've done a different approach where i'm able to insert an item into the database but the php page reloads everytime I add an item.
I want to make my ordering page be able to add an item and not reload, i've searched on how to do it and it says i have to use a javascript or ajax, this is what i've tried so far as i don't actually know javascript
this is my ordering php page
function onSubmit() {
$.ajax({
url: 'inserttocart.php',
method: 'post',
data: $("#orderid").serialize(),
success: function(response) {
alert(response);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus);
alert("Error: " + errorThrown);
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="orderid">
<p><br>Your choice of 1 marinade: </p>
<input class="chkb1" type="checkbox" name="choice1" value="Bulgogi">  Bulgogi<br>
<input class="chkb1" type="checkbox" name="choice1" value="Galbi">  Galbi<br>
<input class="chkb1" type="checkbox" name="choice1" value="Gochujang">  Gochujang<br>
<input class="chkb1" type="checkbox" name="choice1" value="JRAMS">  JRAMS Special
<button class="cart-button" type="button" onclick="onSubmit()" id="addtocartbtn" name="beefbtn">
<span class="add-to-cart">Add to Cart</span>
<span class="added">Added</span>
<i class="fas fa-shopping-cart"></i>
<i class="fas fa-box"></i>
</button>
</form>
This is my inserttocart.php
$connect = mysqli_connect("localhost", "root", "", "pigmedb");
if ($connect == false) {
die("ERROR: Could not connect. ".mysqli_connect_error());
}
if (isset($_POST['choice1']) && (isset($_POST['beefbtn']))) {
$marinade = ($_POST['choice1']);
if ($connect == false) {
die("ERROR: Could not connect. ".mysqli_connect_error());
}
if ($marinade == "Bulgogi") {
$sqlresult = "SELECT foodname FROM pigme_cart WHERE foodname='Beef Set (Bulgogi Marinated)'";
}
elseif($marinade == "Galbi") {
$sqlresult = "SELECT foodname FROM pigme_cart WHERE foodname='Beef Set (Galbi Marinated)'";
}
elseif($marinade == "Gochujang") {
$sqlresult = "SELECT foodname FROM pigme_cart WHERE foodname='Beef Set (Gochujang Marinated)'";
}
elseif($marinade == "JRAMS") {
$sqlresult = "SELECT foodname FROM pigme_cart WHERE foodname='Beef Set (JRAMS Special Marinated)'";
}
$result = mysqli_query($connect, $sqlresult);
if (mysqli_num_rows($result) > 0) {
// row exists
echo "Item Already Added";
mysqli_close($connect);
} else {
if ($marinade == "Bulgogi") {
$sql = "INSERT INTO pigme_cart(foodname, quantity, price) VALUES ('Beef Set (Bulgogi Marinated)', '1', '399')";
}
elseif($marinade == "Galbi") {
$sql = "INSERT INTO pigme_cart(foodname, quantity, price) VALUES ('Beef Set (Galbi Marinated)', '1', '399')";
}
elseif($marinade == "Gochujang") {
$sql = "INSERT INTO pigme_cart(foodname, quantity, price) VALUES ('Beef Set (Gochujang Marinated)', '1', '399')";
}
elseif($marinade == "JRAMS") {
$sql = "INSERT INTO pigme_cart(foodname, quantity, price) VALUES ('Beef Set (JRAMS Special Marinated)', '1', '399')";
}
else {
echo "Please select one of the marinade of the Beef Set.";
}
if (mysqli_query($connect, $sql)) {
echo "Added to Cart";
} else {
echo "ERROR: Could not able to execute $sql. ".mysqli_error($connect);
}
mysqli_close($connect);
}
}
My goal is to prevent the first page from reloading as this is a cart, but at the same time, its able to insert an item into the mysql database. pls help thank you
Buttons aren't included in the result of .serialize(), since it doesn't know which button was clicked. So $_POST['beefbtn'] won't be set.
You can add it yourself.
data: $("#orderid").serialize() + '&beefbtn=1'
Or you could remove that check from the PHP.
This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 4 years ago.
I would like to try to find a way to reload my HTML page without making it refresh. For example, I want through a PHP file to reload my 1st page to a second page. Here is my try, but it shows me this message -->
Parse error: syntax error, unexpected '<' in C:\wamp64\www\PHP\pesto.php on line 26
Here is my php file:
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("127.0.0.1", "root", "", "mysql3");
// Check connection
if($link === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$user_id =$_POST['user_id'];
$book_id =$_POST['book_id'];
$game_id =$_POST['game_id'];
$site_id =$_POST['site_id'];
//Attempt insert query execution
$query = "SELECT site_id FROM components WHERE user_id='$user_id' && book_id='$book_id' && game_id='$game_id' ORDER BY site_id DESC LIMIT 1";
$res = mysqli_query($link,$query);
$result = array();
$res = mysqli_query($link,$query) or die(mysqli_error($link));
while($row = mysqli_fetch_assoc($res)){
$result[]=$row['site_id'];
}
if ($res){
if($result[0] <20){
<script>
$.get("updated-content.html", function(data, status){ $("body").html(data); }).fail(function(e) { alert( "error" +JSON.stringify(e)); })
</script>
});
}
}
// while($row = mysqli_fetch_array($res)){
// array_push($result, array($row[0]));}
// echo json_encode(array($result));
// Close connection
mysqli_close($link);
?>
I don't want to use PHP redirection. I want to make that happen with the usage of jquery. Is it possible?
The error unexpected syntax clearly explains what the problem is... it does not expect that to be there!
Common fix : Check your semicolon and brackets.
It is obious you MUST use a " or '.
if ($res){
if($result[0] <20){
echo '<script>
$.get("updated-content.html", function(data, status){ $("body").html(data); }).fail(function(e) { alert( "error" +JSON.stringify(e)); })
</script>';
}
}
Also you should be using prepared statements as your code above is vulnerable to SQL injection. You can learn more by Googling "SQL Injection" and "Prepared Statements PHP".
You can also use PHP to include or require files based on conditions...
Such as :
<?php
if ($res){
if($result[0] <20){
include 'updated-content.html';
}else{
include 'file.html';
}
}
?>
I have a login script that should return 'success' or 'failure' respectively, but it adds many spaces before the result, in the console it shows tha value as "<tons of space> success". This is the PHP for the login script:
public function login() {
global $dbc, $layout;
if(!isset($_SESSION['uid'])){
if(isset($_POST['submit'])){
$username = mysqli_real_escape_string($dbc, trim($_POST['email']));
$password = mysqli_real_escape_string($dbc, trim($_POST['password']));
if(!empty($username) && !empty($password)){
$query = "SELECT uid, email, username, password, hash FROM users WHERE email = '$username' AND password = SHA('$password') AND activated = '1'";
$data = mysqli_query($dbc, $query);
if((mysqli_num_rows($data) === 1)){
$row = mysqli_fetch_array($data);
$_SESSION['uid'] = $row['uid'];
$_SESSION['username'] = $row['username'];
$_SERVER['REMOTE_ADDR'] = isset($_SERVER["HTTP_CF_CONNECTING_IP"]) ? $_SERVER["HTTP_CF_CONNECTING_IP"] : $_SERVER["REMOTE_ADDR"];
$ip = $_SERVER['REMOTE_ADDR'];
$user = $row['uid'];
$query = "UPDATE users SET ip = '$ip' WHERE uid = '$user' ";
mysqli_query($dbc, $query);
setcookie("ID", $row['uid'], time()+3600*24);
setcookie("IP", $ip, time()+3600*24);
setcookie("HASH", $row['hash'], time()+3600*24);
echo 'success';
exit();
} else {
//$error = '<div class="shadowbar">It seems we have run into a problem... Either your username or password are incorrect or you haven\'t activated your account yet.</div>' ;
//return $error;
$err = 'failure';
echo($err);
exit();
}
} else {
//$error = '<div class="shadowbar">You must enter both your username AND password.</div>';
//return $error;
$err = "{\"result\":\"failure\"}";
echo json_encode($err);
exit();
}
}
} else {
echo '{"result":"success"}';
exit();
}
return $error;
}
and the form and JS
<div class="shadowbar"><form id="login" method="post" action="/doLogin">
<div id="alert"></div>
<fieldset>
<legend>Log In</legend>
<div class="input-group">
<span class="input-group-addon">E-Mail</span>
<input type="email" class="form-control" name="email" value="" /><br />
</div>
<div class="input-group">
<span class="input-group-addon">Password</span>
<input type="password" class="form-control" name="password" />
</div>
</fieldset>
<input type="submit" class="btn btn-primary" value="Log In" name="submit" />
</form></div>
$(function login() {
$("#login").validate({ // initialize the plugin
// any other options,
onkeyup: false,
rules: {
email: {
required: true,
email: true
},
password: {
required: true
}
}
});
$('form').ajaxForm({
beforeSend: function() {
return $("#login").valid();
},
success : function(result) {
console.log(result);
if(result == " success"){
window.location = "/index.php";
}else if(result == " failure"){
$("#alert").html("<div class='alert alert-warning'>Either you're username or password are incorrect, or you've not activated your account.</div>");
//$("#alert").show();
}
}
});
});
but the result always has a lot of spaces for some reason. I'm new to JS, so if this is common, I don't already know.
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
define("CCore", true);
session_start();
//Load files...
require_once('include/scripts/settings.php');
require_once('include/scripts/version.php');
require('include/scripts/core.class.php');
require('include/scripts/nbbc_main.php');
$parser = new BBCode;
$core = new core;
$admin = new admin;
require_once('include/scripts/layout.php');
require_once('include/scripts/page.php');
//Set Variables...
global $dbc, $parser, $layout, $main, $settings, $core;
$page = new pageGeneration;
$page->Generate();
?>
this is my index, and anything before the page is generated and login() is called, is in there.
I suppose you are using Ajax calls. I had the same problem, but it my case the result hadn't contain spaces, it was returned in new line. The problem was that my script which was requested by Ajax, contained "new line" character before the PHP script. Search your script file for spaces before PHP script starting with <?php //code... If you had included some scripts in the script which returns success note, search them as well.
I dont know if it matters but your
if(result == " success"){ // <<<<<< Here is a Problem maybe
window.location = "/index.php";
}else if(result == " failure"){ // <<<<<< Here is a Problem maybe
$("#alert").html("<div class='alert alert-warning'>Either you're username or password are incorrect, or you've not activated your account.</div>");
//$("#alert").show();
}
compares your result from the server which is i.e. "success" with " success". There is space too much.
EDIT:: I dont get ether why you jumps between the response format. Sometimes you echo "success" which is plain and good with your if condition but sometimes you return json encodes strings.
These Responses you can't just compare with plain text. These Responses you have to Parse into a JSON Object. Then you could compare with:
if (parsedJSONobject.result == "success"){}
The comments on the question are most probably correct: the spaces are being (again, probably, nobody can know for sure without reading the whole source) echoed by PHP included before this. For example, if you do:
<?php
// there's a space before the previous line
you'd get that space in the output.
What you can do is a bit of a hack, you include a header, for example:
header('Content-Type: text/html');
just before your success output, this will (yet again, probably) output something like:
Warning: Cannot modify header information - headers already sent by (output started at /some/file.php:12) in /some/file.php on line 23
(note the "output started" part) and now you know where to start looking.
HTH.
I am trying to add some data to a relational database, and would like the session_user_id to be the foreign key for that database. When a user clicks a button, I want to make a database entry with the session_user_id and some other information I have POSTed to the page. My ajax posts to the php webpage page which it is run on (meaning all my scripts are on the same page)
I am currently getting a Uncaught ReferenceError: $sess_user_id1 is not defined. The jquery is firing. While I would love to get the undefined variable fixed, overall this does not seem like a very direct way to to this, and has added a bunch of confusing variables, when all the variables I need were already in my PHP statement. Is there any way to trigger the PHP entry without going through ajax and having to define the variables again?
Here is my php, which is at the header which is on the same page as my JS and HTML:
<?php
$markerid = $_POST["id"];
$name = $_POST["name"];
$type = $_POST["type"];
$point = $_POST["point"];
$lat2 = $_POST["lat"];
$lng2 = $_POST["lng"];
$locationdescription = $_POST["locationdescription"];
$locationsdirections = $_POST["locationdirections"];
session_start();
if (!isset($_SESSION['sess_user_id']) || empty($_SESSION['sess_user_id'])) {
// redirect to your login page
exit();
}
$sess_user_id1 = $_SESSION['sess_user_id'];
if ((isset($_POST['usid'])) && (isset($_POST['usid']))) {
$user_id_follow = strip_tags($_POST['usid']);
echo $user_id_follow;
$query = "INSERT INTO markerfollowing ( userID, markerID, type )
VALUES ('$user_id_follow', '$markerid', '$type');";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
mysql_close();
}
?>
Here is the HTML button:
<div class="btn pull-right">
<button class="btn btn-large btn-followmarker" type="submit"id="followmarker">Add me to the list</button>
</div>
Here is the jquery/ajax post:
<script/javascript>
$(document).ready(function () {
$("#followmarker").click(function(){
$.ajax({
type: "POST",
url: "", //
data: { usid: <?php echo '$sess_user_id1'; ?>},
success: function(msg){
alert("success");
$("#thanks").html(msg);
},
error: function(){
alert("failure");
}
});
});
});
</script
A sincere thanks for any and all help. I haven't worked with relational databases before.
<?php echo '$sess_user_id1'; ?>
is wrong. If you wont to get
data: { usid: 123} at $sess_user_id1 is 123, you should write
data: { usid: <?php echo "$sess_user_id1"; ?>}
See your html source code in your brawser. I think there is data: { usid: $sess_user_id1}, and javascript is not understand what is the $sess_user_id1
This is the only one problem that I can see now, but I don't understand your current task whole to say more.
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