ajax form request still reloads page - javascript

I am trying to submit a form using ajax with jquery mobile without it refreshing the page and am having no luck..
I have this form -
index.php:
<script>
function SubmitForm() {
var name = $("#name").val();
$.post("bump.php", { name: name},
function(data) {
//alert(data);
});
}
</script>
<form method="post" data-ajax="false">
<input name="name" type="hidden" id="name" type="text" value="<?php echo $id; ?>" />
<input type="image" style="height:35px;top:4px;" id="bump" src="../img/bump.png" id="searchForm" onclick="SubmitForm();" value="Send" />
</form>
Here is bump.php
$date = date('y/m/d H:i:s');
$id = $_POST['name'];
$sql = "UPDATE images SET update_date='$date' WHERE id=$id";
if ($conn->query($sql) === TRUE) {
} else {
echo "Error updating record: " . $conn->error;
}
I would like to maintain my position on the page but it refreshes each time? What am I doing wrong here?

Use event.preventDefault(); Cancels the event if it is cancelable, without stopping further propagation of the event.
Default behaviour of type="image" is to submit the form hence page is unloaded
function SubmitForm(event) {
event.preventDefault();
var name = $("#name").val();
$.post("bump.php", {
name: name
},
function(data) {
//alert(data);
});
}
<form method="post" data-ajax="false">
<input name="name" type="hidden" id="name" type="text" value="<?php echo $id; ?>" />
<input type="image" style="height:35px;top:4px;" id="bump" src="../img/bump.png" id="searchForm" onclick="SubmitForm(event);" value="Send" />
</form>

user return false in onclick`
function SubmitForm() {
//event.preventDefault();
var name = $("#name").val();
console.log(name);
$.post("message.html", { name: name},
function(data) {
alert(data);
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<form method="post" data-ajax="false">
<input name="name" type="hidden" id="name" type="text" value="<?php echo $id; ?>" />
<input type="image" style="height:35px;top:4px;" id="bump" src="http://switchon.global2.vic.edu.au/files/2015/07/4x5-1jroh2i.png" id="searchForm" onclick="SubmitForm(); return false;" value="Send" />
</form>

Related

How to copy a file then rename it based on input field via buttonclick?

Good day experts!
I want to copy a file and rename it based on input value via button click. MY code is not working. There is no file being copied nor being renamed.
Here's my code:
<?php
error_reporting(0);
if($_POST['action'] == 'call_this') {
echo Success!;
};
$file = 'data.php';
$newfile = '$_GET['subject'].php';
echo copy($file, $newfile);
?>
<form action="<?php echo $newfile ?>" method="get">
<input type="text" name="subject" required>
<button type="submit">Change</button>
</form>
<script>
function change() {
$.ajax({
type: "POST",
url: 'data.php',
data:{action:'call_this'},
success:function(html) {
alert(html);
}
});
}
</script>
i think this is what you looking for:
<html>
<body>
<form method="post" action="copy.php">
<input type="text" placeholder="new name" name="newFileName"/>
<input type="submit" value="Change"/>
</form>
</body>
</html>
copy.php :
<?php
$file = 'sample.txt';
$newfile = $_POST["newFileName"].'.txt';
if (!copy($file, $newfile)) {
echo "failed to copy";
}else {
echo "copy with new name";
}
?>

how to set unique id for multiple form using JQuery and PHP

i have more than 1 form in my page. i submit this forms using ajax to database. the problem is each of this form should have unique id in order to submit with ajax(JQuery id selector), and the first form always get submitted using ajax and other form submitted with php. how can i have unique id for each form and submit all forms with AJAX?
<form action="inc/new.comment.php" method="post" id="new_comment_answer_form">
<textarea name="new_answer" id="new_answer" cols="30" rows="10" placeholder="enter your new answer"></textarea>
<!-- <input type="text" name="comment_author" id="comment_author" placeholder="author name"> -->
<input type="hidden" name="post_id" id="post_id" value="<?php echo $post_id ?>">
<input type="hidden" name="comment_id" id="comment_id" value="<?php echo $comment_id ?>">
<input type="submit" name="submit_answer" value="send" id="submit_answer">
</form>
<p id="new_answer_result"></p>
jQUERY:
$("#new_comment_answer_form").submit(function (e) {
e.preventDefault();
var new_answer = $("#new_answer").val();
var submit_answer = $("#submit_answer").val();
var post_id = $("#post_id").val();
var comment_id = $("#comment_id").val();
$(document).ajaxStart(function () {});
$(document).ajaxComplete(function () {});
$.post("./inc/new.comment.php", {
new_answer: new_answer,
submit_answer: submit_answer,
post_id: post_id,
comment_id: comment_id
}, function (data, status) {
$("#new_answer_result").html(data);
$("#new_answer").val("");
});
});
use of this code is comment on other comments in a blog site.(if that helps)
You can give for each your form unique IDs, but set the same class, for example class="submit_form". Next you should call the function by this class. Other fields you can call by names.
$(".submit_class").submit(function (e) {
e.preventDefault();
var new_answer = $(this).find("[name=new_answer]").val();
var submit_answer = $(this).find("[name=submit_answer]").val();
var post_id = $(this).find("[name=post_id]").val();
var comment_id = $(this).find("[name=comment_id]").val();
$(document).ajaxStart(function () {});
$(document).ajaxComplete(function () {});
$.post("./inc/new.comment.php", {
new_answer: new_answer,
submit_answer: submit_answer,
post_id: post_id,
comment_id: comment_id
}, function (data, status) {
$("#new_answer_result").html(data);
$(this).find("[name=new_answer]").val("");
});
});
I am guessing you have the form creation code in loop.
try this..
<?php i=0; // take post_id, if you want ?>
<form action="inc/new.comment.php" method="post" id="new_comment_answer_form_<?php echo ++i; ?>">
<textarea name="new_answer" id="new_answer" cols="30" rows="10" placeholder="enter your new answer"></textarea>
<!-- <input type="text" name="comment_author" id="comment_author" placeholder="author name"> -->
<input type="hidden" name="post_id" id="post_id" value="<?php echo $post_id ?>">
<input type="hidden" name="comment_id" id="comment_id" value="<?php echo $comment_id ?>">
<input type="submit" name="submit_answer" value="send" id="submit_answer">
</form>
<p id="new_answer_result"></p>
You will have different id as "new_comment_answer_form_1", "new_comment_answer_form_2".
You can submit multiple forms with php as well.
at the top of your file.php
if(isset($_POST['btnName1'])){
... manipulate form's content
}elseif(isset($_POST['btnName2'])){
... manipulate another forms content
}
then later on in your file have the forms, they don't even need ID, php will recognise form by button name tag
<form method="POST">
<input type="text" name="inputField">
<input type="submit" name="btnName1">
</form>
<form method="POST">
<input type="text" name="inputField">
<input type="submit" name="btnName2">
</form>

How to add onkeypress save in php form

**This is my php index.php file. I want to type first name and last name type and auto it has to be save the database. I wrote the code using ajax. but, this is not working properly. Please can any one help me. **
index.php
<?php
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("type", $connection);
if(isset($_POST['submit'])){
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
if($firstName !=''||$lastName !=''){
//Insert Query of SQL
$query = mysql_query("insert into users(firstName, lastName) values ('$firstName', '$lastName')");
echo "<br/><br/><span>Data Inserted successfully...!!</span>";
}
else{
echo "<p>Insertion Failed <br/> Some Fields are Blank....!!</p>";
}
}
mysql_close($connection);
?>
<html>
<head>
<meta><title>Home Page</title>
<script type="text/javascript">
$(document).on('keyup','firstName','lastName',function(){
var rel = $(this).attr('rel');
var flatvalue = $(this).val();
$("#firstName"+rel).val(flatvalue);
});
</script>
</head>
<body>
<form action="" method="post">
<label for="firstName">First Name</label>
<input type="text" name="firstName" ><br><br>
<label for="lastName">Last Name</label>
<input type="text" name="lastName" ><br><br>
<input type="submit" id="submit" name="submit" value="submit"/>
</form>
</body>
</html>
onKeyPress event not proper because it call many times as per user hit.
Use onBlur event instead of onKeyPress for submit the form and save it to MySql users table.
Try below example,
PHP
<?php
$connection = mysql_connect("localhost", "jaydeep_mor", "jaydeep_mor");
$db = mysql_select_db("jaydeep_mor", $connection);
if(isset($_POST['firstName']) && isset($_POST['lastName'])){
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
if($firstName != '' || $lastName != ''){
//Insert Query of SQL
$query = mysql_query("insert into users(firstName, lastName) values ('$firstName', '$lastName')");
header("Location: test.php?msg=Data Inserted successfully...!!");
}
else{
echo "<p>Insertion Failed <br/> Some Fields are Blank....!!</p>";
}
}
mysql_close($connection);
?>
HTML / JAVASCRIPT
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<meta><title>Home Page</title>
<script type="text/javascript">
function saveData(){
document.forms["userDataForm"].submit();
}
</script>
</head>
<body>
<?php if(isset($_GET['msg']) && trim($_GET['msg'])!=""){ ?>
<br /><div><?php echo $_GET['msg']; ?></div><br />
<?php } ?>
<form action="test.php" method="post" name="userDataForm">
<label for="firstName">First Name</label>
<input type="text" name="firstName" value="<?php echo isset($_POST['firstName'])?$_POST['firstName']:''; ?>" ><br><br>
<label for="lastName">Last Name</label>
<input type="text" name="lastName" value="<?php echo isset($_POST['lastName'])?$_POST['lastName']:''; ?>" onblur="return saveData();" ><br><br>
<!--input type="submit" id="Submit" name="Submit" value="submit"/-->
</form>
</body>
</html>
<?php
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("type", $connection);
if(isset($_REQUEST['firstName'])){
$firstName = $_REQUEST['firstName'];
$lastName = $_REQUEST['lastName'];
if($firstName !=''||$lastName !=''){
//Insert Query of SQL
$query = mysql_query("insert into users(firstName, lastName) values ('$firstName', '$lastName')");
echo "<br/><br/><span>Data Inserted successfully...!!</span>";
die();
}
else{
echo "<p>Insertion Failed <br/> Some Fields are Blank....!!</p>";
die();
}
}
//mysql_close($connection);
?>
<html>
<head>
<meta><title>Home Page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#submit').click(function(){ alert('d');
var firstname = $('#firstName').val();
var lastname = $('#lastName').val();
$.ajax({
url:'',
data:{'firstname':firstname,'lastname':lastname, },
type: 'POST',
success: function(data){
alert("Data Save: " + data);
}
});
});
});
</script>
</head>
<body>
<label for="firstName">First Name</label>
<input type="text" name="firstName" id="firstName"><br><br>
<label for="lastName">Last Name</label>
<input type="text" name="lastName" id="lastName"><br><br>
<input type="submit" id="submit" name="submit" value="submit"/>
</body>
</html>
may be this can help you,
if you want to do it via form submit then just you need to give the url of your controller function in the action method of the form
<form action="" method="post">
<label for="firstName">First Name</label>
<input type="text" name="firstName" ><br><br>
<label for="lastName">Last Name</label>
<input type="text" name="lastName" ><br><br>
<input type="submit" id="submit" name="submit" value="submit"/>
</form>
if you want to do it via ajax then you can add id attribute for first_name and last_name input and can do it in following way,
$('#submit').on('click', function(){
var first_name = $("#first_name").val();
var last_name = $("#last_name").val();
$.ajax({
url: url of your controler, //url of your controller function
type: "POST",
data: {'first_name' : first_name,'last_name':last_name},
success: function (data) {
//whatever you want to do on success
} else {
//in case of no data
}
}
});
});
in the same way you can give a class attribute to the input box and on keyup event can save the data via class
have you try doing it this way
$('body').delegate('input[type="text"]', 'keypress keydown keyup change propertychange paste', function(event) {
event.stopImmediatePropagation();
if (event.type === 'keydown' || event.type === 'keypress') {
return;
}
//insert what you want to do here
//perform some ajax
/*
$.ajax({
url: 'index.php',
method: 'POST',
data: {
'firstName' : $('input[name=firstName]).val(),
'lastName' : $('input[name=lastName]).val()
},
success: function(mResponse) {
alert(mResponse);
}
});
*/
});

SESSION variable slow to update textfield in php

I have a form, contained 3 fields, which when the submit button in submitted,
it will changes the session variable values according to the fields, in this case there are 3 variables. then i echo back the variable onto the fields.
For the first time submit, it stores the value beautifully and display in the fields correctly, the problem is that, when i submit the second time, the values are still the same. after i refresh the page, then the values in the fields are changed.
this is partially the codes i'm using now.
<?php
session_start();?>
?>
<form name="form1" id="form1" action="">
<input type="text" name="acc1" value="<?php echo $_SESSION['acc_main']" />
<input type="text" name="acc2" value="<?php echo $_SESSION['acc_id']" />
<input type="text" name="acc3" value="<?php echo $_SESSION['acc_cat']" />
<input type="submit" name="submit">
</form>
<?php
if(isset($_POST['submit']) != '')
{
$_SESSION['acc_main'] = $_POST['acc1'];
$_SESSION['acc_id'] = $_POST['acc2'];
$_SESSION['acc_cat'] = $_POST['acc3'];
}
?>
After i refresh(F5), then the value changed. i want it to be, when i clicked the submit button, it will change to the new value.
PHP Code:
<?php
if(isset($_POST['submit']) != '')
{
$_SESSION['acc_main'] = $_POST['acc1'];
$_SESSION['acc_id'] = $_POST['acc2'];
$_SESSION['acc_cat'] = $_POST['acc3'];
echo '<script type="text/javascript">'
, 'jsfunctionToPrintUpdatedValues();'
, '</script>'
;
}
?>
Javascript Sample Code
function jsfunctionToPrintUpdatedValues()
{
/* retrieve the updated session variables in javascript variables */
var acc_main_js = <?php echo $_SESSION['acc_main']?>
var acc_id_js = <?php echo $_SESSION['acc_id']?>
var acc_cat_js = <?php echo $_SESSION['acc_cat']?>
document.getElementById("main").value=acc_main_js;
document.getElementById("id").value=acc_main_js;
document.getElementById("cat").value=acc_main_js;
}
in the input fields you have to write like this
`
Below
`
<input type="text" name="acc1" value="<?php if(isset($_SESSION['acc_main'])) echo $_SESSION['acc_main']" />
Use if(isset($_POST['submit']) != '') before the form. Change your code to this:
<?php
session_start();
if(isset($_POST['submit']) != '')
{
$_SESSION['acc_main'] = $_POST['acc1'];
$_SESSION['acc_id'] = $_POST['acc2'];
$_SESSION['acc_cat'] = $_POST['acc3'];
?>
<form name="form1" id="form1" action="">
<input type="text" name="acc1" value="<?php echo $_SESSION['acc_main']" />
<input type="text" name="acc2" value="<?php echo $_SESSION['acc_id']" />
<input type="text" name="acc3" value="<?php echo $_SESSION['acc_cat']" />
<input type="submit" name="submit">
</form>
<?php
}else{
?>
<form name="form1" id="form1" action="">
<input type="text" name="acc1" value="<?php echo $_SESSION['acc_main']" />
<input type="text" name="acc2" value="<?php echo $_SESSION['acc_id']" />
<input type="text" name="acc3" value="<?php echo $_SESSION['acc_cat']" />
<input type="submit" name="submit">
<?php } ?>

Jquery not receiving any form values

I'm using cluetip to open popups with a pm system in. When i post the pm Jquery is not receiving the values in any fields. Here is a JsFiddle can anyone help?
The html form
<div class="interactContainers" id="private_message1">
<form action="javascript:sendPM();" name="pmForm" id="pmForm" method="post">
<font size="+1">Sending Private Message to <strong><em><?php echo "$username"; ?></em></strong></font><br /><br />
Subject:
<input name="pmSubject" id="pmSubject" type="text" maxlength="64" style="width:90%;" />
Message:
<textarea name="pmTextArea" id="pmTextArea" rows="8" style="width:90%;"></textarea>
<input name="pm_sender_id" id="pm_sender_id" type="hidden" value="<?php echo $sessionid ?>" />
<input name="pm_sender_name" id="pm_sender_name" type="hidden" value="<?php echo $user ?>" />
<input name="pm_rec_id" id="pm_rec_id" type="hidden" value="<?php echo $profileid ?>" />
<input name="pm_rec_name" id="pm_rec_name" type="hidden" value="<?php echo $username ?>" />
<input name="pmWipit" id="pmWipit" type="hidden" value="<?php echo $thisRandNum ?>" />
<span id="PMStatus" style="color:#F00;"></span>
<br /><input name="pmSubmit" type="submit" value="Submit" />
<span id="pmFormProcessGif" style="display:none;"><img src="../_Images/loading.gif" width="28" height="10" alt="Loading" /></span></form>
</div>
the jquery
$('#pmForm').on('submit', function (e) {
e.preventDefault();
$('input[type=submit]', this).attr('disabled', 'disabled');
var pmSubject = $("#pmSubject").val();
var pmTextArea = $("#pmTextArea").val();
var url = "../_Scripts/private_msg_parse.php";
if (!pmSubject)
{
$('input[type=submit]',this).removeAttr('disabled');
$("#jqueryReply").html('<img src="../_Images/round_error.png"
alt="Error" width="31" height="30" /> Please type
a subject.')
.show().fadeOut(6000);
return false;
}
else if (!pmTextArea) {
$('input[type=submit]', this)
.removeAttr('disabled');
$("#jqueryReply").html('<img src="../_Images/round_error.png"
alt="Error" width="31" height="30" /> Please type in your
message.')
.show().fadeOut(6000);
return false;
} else {
$("#pmFormProcessGif").show();
$.post(url, $('#pmForm').serialize(), function (data) {
$("#jqueryReply").html(data).show().fadeOut(10000);
$("#pmTextArea").val('');
$("#pmSubject").val('');
$("#pmFormProcessGif").hide();
});
}
});
http://jsfiddle.net/RKN39/
Thanks
I'm not sure about cluetip but I don't think that the form field values are being passed since they are inside a container that is hidden - .interactContainers has a css value of display:none. You can keep that designation and try something like
$('#private_message').on("click", function(){
$('.interactContainers').css('display','block')
});
or maybe there is a way to integrate that into your cluetip code?

Categories

Resources