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 tried multiple ways to stop the page but unfortunately, it won't work, I have one frontend form of Wordpress Plugin
i try may time but code not worked
Plugin form code
echo '<div id="submit_car_form">';
echo '<form id="cd_car" name="cd_car" class="cd_car" method="post" action="'.$_SERVER['PHP_SELF'].'" enctype="multipart/form-data" >';
echo '<input type="hidden" name="author_id" value="'. get_current_user_id().' " />';
echo '<p><label for="title">Title</label><br />';
echo '<input type="text" id="title" value="" size="60" name="title" />';
echo '</p>';
..........................
i Have multiple inputs
..........................
echo '<p align="left"><input type="submit" tabindex="6" id="submit_car" name="submit_car" /></p>';
wp_nonce_field( "car-frontend-post" );
echo '</form>';
echo '</div>';
Javascript Code for Stop refresh on form Submit
jQuery(document).ready(function($) {
$('#submit_car').on('submit', function(event){
// $('#cd_car').on('submit', function(e){
// $('#cd_car').submit(function(e){
// $('#submit_car').click(function(e){
e.preventDefault();
var message = document.getElementById("file").value;
var title = document.forms["cd_car"]["title"].value;
if (title == ""){
alert("Title cannot be empty");
return false;
}
else {
$.ajax({
type: 'POST',
dataType: 'JSON',
data: new FormData($('#car_data')[0]),
contentType: false,
cache: false,
processData: false,
success: function(data){
console.log(data);
alert('Your Form Submited');
},
error: function(data){
console.log(data);
alert('something wrong');
}
});
return false;
}
});
});
Your form has an id of cd_car, not submit_car! Therefore, your JS handler will not target it until you change the selector.
Also, as mentioned in the comments, your event object in your handler is called event, but in your code you are using e.preventDefault() instead of event.preventDefault()
Related
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
}
So I have one form in frontend. And second form in process file.
With first form i calling second form with products information.
FIRST FORM
$izmena_proizvoda = $conn->query("SELECT * FROM proizvodi");
$izmena_proizvoda->execute();
echo '<form method="POST">';
echo '<select class="form-control" name="izmena_proizvoda" id="izaberi_proizvod" onchange="izmena_proizvoda_ajax(this.value);">';
echo '<option>Izaberite proizvod</option>';
while($izmena_proizvoda_o=$izmena_proizvoda->fetch()){
echo '<option value="'.$izmena_proizvoda_o['id_sata'].'">';
echo $izmena_proizvoda_o['nazivsata'];
echo '</option>';
}
echo '</select>';
echo '</form>';
And ajax for this form
function izmena_proizvoda_ajax(val){
$.ajax({
url: "../sadrzaj/stranice/izmenaproizvoda.php",
type: 'POST',
data: {
izmena_proizvoda:val
},
success: function (response) {
document.getElementById("izmena_proizvoda_prikaz").innerHTML = response;
console.log(response)
}
});
}
In process file i have this one.
if(isset($_POST['izmena_proizvoda'])){
$izmena_proizvoda_forma = $conn->prepare("SELECT * FROM proizvodi WHERE id_sata = :id_sata");
$izmena_proizvoda_forma->bindParam(':id_sata', $_POST['izmena_proizvoda'], PDO::PARAM_INT);
$izmena_proizvoda_forma->execute();
echo '<hr>';
echo '<form method="post" action="#" id="izmena_proizvoda_update_form" class="ajax" >';
while($izmena_proizvoda_forma_o=$izmena_proizvoda_forma->fetch()){
echo'
<input type="hidden" name="slika_za_brisanje" value="'.$izmena_proizvoda_forma_o['slika'].'">
<input type="hidden" name="id_izmena" value="'.$izmena_proizvoda_forma_o['id_sata'].'">
<label for="naslov_izmena">Naziv sata</label>
<input type="text" id="naslov_izmena" name="naslov_izmena" class="form-control" value="'.$izmena_proizvoda_forma_o['nazivsata'].'">
<label for="cena_izmena">Cena</label>
<input id="cena_izmena" type="text" name="cena_izmena" class="form-control" value="'.$izmena_proizvoda_forma_o['cenasata'].'"><br>
<label for="vodootpornost">Vodootpornost</label>
<input id="vodootpornost" type="text" name="vodootpornost" class="form-control" value="'.$izmena_proizvoda_forma_o['vodootpornost'].'"><br>
<label for="zalihe">Zalihe</label>
<input id="zalihe" type="text" name="zalihe" class="form-control" value="'.$izmena_proizvoda_forma_o['zalihe'].'"><br>
<label for="pol">Pol sata</label>
<input id="pol" type="text" name="pol" class="form-control" value="'.$izmena_proizvoda_forma_o['pol'].'"><br>
<label for="opissata_izmena"></label>';
echo ' <textarea id="opissata_izmena" rows="10" name="opissata_izmena">'.$izmena_proizvoda_forma_o['opissata'].'</textarea><br>';
echo '<input type="submit" name="izmena_proizvoda_potvrda" value="Sacuvaj izmene" class="btn btn-info">';
}
echo '</form>';
}
So when i do that on frontend. works fine. But when i try to do another ajax for form2 i have a problems. I dont know how i can run a ajax for another form.
I try to put ajax code in forntend page but didnt work. Also i tryed to put ajax in process file below the form. To call both together. also didnt fork.
How I can make some trigger for ajax 2 from ajax 1 like
Ajax1: Hey ajax2 i do my job. You now have a form. When user click submit, do your job and dont refres a page.
Sorry beacuse my bad english.
You get rid of your onchange handler, keep your <form> tags and attach your event handler to all forms instead of a specific form. Then use $(this) to reference the values of the form which generates the submission event.
$("form").on("submit", function(event) {
event.preventDefault();
var data = $(this).serialize(); // Grabs all data from the form being submitted
$.ajax({
url: "../sadrzaj/stranice/izmenaproizvoda.php",
type: 'POST',
data: data,
success: function(response) {
document.getElementById("izmena_proizvoda_prikaz").innerHTML = response;
console.log(response);
// If you need to alter success handlers you can add data elements to your form HTML and reference them here
// Same is true if you need to alter submission URL or whatever
}
});
});
You need other way to assign the event to your new HTML elements.
This way assign an event to any dynamic HTML element.
$(function() {
//Assign event to input submit with name izmena_proizvoda_potvrda
$(document).on('click', 'input[name=izmena_proizvoda_potvrda]',
function(e) {
e.preventDefault();
//Ajax request
}); //end function()
})
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 5 years ago.
Improve this question
Currently working on a messaging system for my site. I've created a JavaScript function to send post data, and a corresponding PHP file to insert the data. However, the data is not being sent to the database. I'm not sure if the error is in the JavaScript or the PHP file as there is no error log being created.
HTML:
<form action="javascript:sendPM();" name="pmForm" id="pmForm" method="post">
<input name="pm_send_id" id="pm_send_id" type="hidden" value="<?php echo $_SESSION['userID']; ?>" />
<input name="pm_send_name" id="pm_send_name" type="hidden" value="<?php echo $_SESSION['userName']; ?>" />
<input name="pm_receive_id" id="pm_receive_id" type="hidden" value="<?php echo $row['userID']; ?>" />
<input name="pm_receive_name" id="pm_receive_name" type="hidden" value="<?php echo $row['userName']; ?>" />
X
<h4>Send to <?php echo $row['userName']; ?></h4>
<div class="sectionheader"></div>
<div id="interaction"></div>
<br>
<p>Comment:</p>
<textarea name="pmTextArea" id="pmTextArea"></textarea>
<p>Select Video:</p>
<input name="pmSubmit" type="submit" value="Submit" />
</form>
JavaScript:
$('#pmForm').submit(function(){$('input[type=submit]', this).attr('disabled','disabled');});
function sendPM(){
var pmTextArea = $("pmTextArea");
var sendName = $("pm_send_name");
var sendID = $("pm_send_id");
var receiveName = $("pm_receive_name");
var receiveID = $("pm_receive_id");
var url = "messages.php";
if (pmTextArea.val() == ""){
$("#interaction").html('Comment field is empty.').show().fadeOut(5000);
}
else {
$.post(url,{ message: pmTextArea.val(), sendername: sendName.val(), senderid: sendID.val(), recname: receiveName.val(), recID: receiveID.val() }, function(data){
$("#interaction").html(data).show().fadeOut(5000);
document.pmForm.pmTextArea value='';
});
}
}
PHP:
<?php
session_start();
require_once 'class.channel.php';
require_once 'dbconfig.php';
$user_message = new USER();
if (isset($_POST['message'])) {
$to = ($_POST['recID']);
$from = ($_POST['senderid']);
$toName = ($_POST['sendername']);
$fromName = ($_POST['recname']);
$msg = htmlspecialchars($_POST['message']);
$stmt = $user_message->runQuery("INSERT INTO inbox(send_id, receive_id, timesent, comment) VALUES(?, ?, ?, ?)");
$stmt->bindValue(1,$from);
$stmt->bindValue(2,$to);
$stmt->bindValue(3,now());
$stmt->bindValue(4,$msg);
$stmt->execute();
}
?>
You need to use # to retrieve value using their id, which you are missing.
var pmTextArea = $("pmTextArea");
should be
var pmTextArea = $("#pmTextArea");
And yes, you need to correct, which #RyanHame pointed
document.pmForm.pmTextArea value='';
to
document.pmForm.pmTextArea.value='';
I want to create on-page login system.
Without javascript I can login perfectly in this structure:
<?php
require_once('login.php');
$login = new Login();
// if we are logged in here:
if ($login->isUserLoggedIn() == true) {
// yes we are
echo "<div id=\"login\">you logged in as $_SESSION[user_name]. Logout</div>";
} else {
// no
echo "
<div id=\"login\" style=\"display: none;\">
<form action=\"index_.php\" method=\"post\" name=\"loginform\" id=\"loginform\" onsubmit=\"return false;\">
<input type=\"text\" class=\"form-control\" id=\"user_name\" name=\"user_name\><br>
<input type=\"password\" class=\"form-control\" id=\"user_password\" name=\"user_password\"><br>
<label class=\"checkbox-label\" style=\"pointer-events: all;\" for=\"user_rememberme\"><input checked class=\"user_rememberme\" name=\"user_rememberme\" id=\"user_rememberme\" value=\"1\" type=\"checkbox\"/>
Remember me</label>
Forgot Password?
<input class=\"btn btn-success\" type=\"submit\" name=\"login\" id=\"loginbutton\" value=\"Login\">
</form>
</div><!-- login ends -->
";
}
?>
Currently on working system, I'm sending form to current page. And code below telling user the result: (for instance. you logged in, please activate your account, login failed.)
<?php
// I send the form same page upside.
// and if i login or not, codes below lets me know.
if (isset($login)) {
if ($login->errors) {
foreach ($login->errors as $error) {
echo "<div id=\"message\">$error</div>";
}
}
if ($login->messages) {
foreach ($login->messages as $message) {
echo "<div id=\"message\">$message</div>";
}
}
}
?>
As a next step, I want to login on-page with the help of ajax. So Here is my javascript code to start with:
<script type="text/javascript">
// login on page
$(function(){
$("#loginform").submit(function(){ // .click yerine .submit
if($("#loginform").valid()){
$.ajax({
type: "POST",
url: "index_.php",
data: $("#loginform").serialize(),
beforeSend: function(){
$('#message').html('Loading...');
},
success: function(data){
$('#message').html(data);
}
});
}
});
});
</script>
Specifically this part of javascript code
success: function(data){
$('#message').html(data);
I want to output my php result, but copying php inside of data obviously doesn't work.
What should I do?
You can add an extra POST-Field (for example "AJAX")
and return other output, if this is set
$.ajax({
type: "POST",
url: "index_.php",
data: $("#loginform").serialize() + "&ajax=1",
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to convert my javascript variable to php variable. I can get the value of "1" when i click the link but i want to echo it using PHP or i want to store it on a PHP variable.
this is my Javascript and PHP code on the same page.
<?php $userid = 1; ?>
<a href="#" onclick="sendEmail(<?php echo $userid; ?>)" > Send Mail </a>
<script type="text/javascript">
function sendEmail(userid){
var sendID = userid;
$(document).ready(function(){
$.ajax({
type: "POST",
url: "ajax.php",
data: { toID: sendID },
dataType: 'json',
cache: false,
success: function( toID ){
alert( toID ); }
});
});
}
<?php
$userid = $_POST["toID"];
echo $userid;
?></script>
no display when i echo it.
thanks.
You can't do this, because your ajax request go to another request, and your current php file can't get it.
yourFile.php -> Ajax Request -> yourFile.php
| |
| |-- here your $_POST['todID'] has the value, but it's other thread
|-- here your $_POST['toID'] is empty
UPDATE 1: You can use success callback to show results or do any.
success: function( data ) {
alert( data ); //<--- this have the result of your ajax request
javaScriptVar = data;
}
UPDATE 2: If you need send email in the same file that shows the form, you need put at head:
<?php
if(isset($_POST['toID'])) {
sendmail($_POST['toID'], "subject", "body");
}
?>
According to your code you are passing a userid to ajax request and getting another userID, Do one thing to achieve that:
<input type="hidden" name="userid" id="userid" value="<?php echo $userid; ?>">
<a href="#" onclick="sendEmail()" > Send Mail </a>
and in you js code:
function sendEmail(){
var sendID = $('#userid');
$(document).ready(function(){
$.ajax({
type: "POST",
url: "ajax.php",
data: { toID: sendID },
dataType: 'json',
cache: false,
success: function( toID ){
//alert( toID );
// update the userID
sendID(toID);
}
});
});
}