Differentiate multiple form on AJAX - javascript

I have a php page with multiple form inside.
<form id="form_<?php echo $rowProduct['Product_ID'];?>">
<a id="wh_<?php echo $rowProduct['Product_ID'];?>"><i class="fal fa-heart"></i></a>
<input type="hidden" name="PID_<?php echo $rowProduct['Product_ID'];?>" value="<?php echo $rowProduct['Product_ID'];?>">
<input type="hidden" name="mail_<?php echo $rowProduct['Product_ID'];?>" value="<?php echo $rowProduct['Mail'];?>">
Those form generate from looping through all data on MySQL.
Every form and input has their unique id by Product_ID.
Below is ajax script to submit data to database.
<script>
$('[id^=wh_]').click(function(e) {
$.ajax({
url: 'submit.php',
type: 'POST',
data: $("[id^=form_]").serialize(),
success: function(data) {
alert('Success add item');
}
});
e.preventDefault();
});
</script>
Currently this code successfull to insert data to MySql, but the submited data always be the last form only whatever which submit button clicked.
I'm using AJAX to submit those forms to achieve a form submit without refreshing the php page.
Much appreciate for every help.

Try by changing this data: $("[id^=form_]").serialize(), to
data: $(this).closest('form').serialize()

Related

how to insert data information in db using html and javascript

I have created a chatbot using rivescript and javascript. I want to save the user's messages and chatbot responses to a database.
In html code I have made this form for the messages:
<div id="dialogue"></div>
<form onSubmit="return chatbot.sendMessage()">
<div class="text-box">
<input type="text" name="message" id="message" autocomplete="off" placeholder="Please wait... loading...">
<input class="send-button" type="submit" value=" " id="butsend">
</div>
</form>
</div>
I used a php file named connect.php to connect with the db.
I modified the command:
<form onSubmit = "return chatbot.sendMessage ()"> to
<form onSubmit = "return chatbot.sendMessage ()" method = "POST" "action =" connect.php>
resulting in the user's first message being entered in the database and then a new blank page appearing instead of the dialog.
Ιs there any way to continue the dialogue and at the same time store the data in the database when the send button is pressed?
I have solved the problem using this function:
function writetoDB(inputmessage, outputmessage){
$.ajax({
url: "save.php",
type: "POST",
data: {
user: inputmessage,
botreply: outputmessage,
},
cache: false,
success: function(dataResult){
}
})
}
that calls the php file:
<?php
include 'database.php';
$user=$_POST['user'];
$botreply=$_POST['botreply'];
$sql = "INSERT INTO `dialogs`( `user`, `bot`)
VALUES ('$user','$botreply')";
if (mysqli_query($conn, $sql)) {
echo json_encode(array("statusCode"=>200));
}
else {
echo json_encode(array("statusCode"=>201));
}
mysqli_close($conn);
?>
My problem now is that not all values are imported in database. For example, if there are 20 messages, only 10 are written to the db.

JAVASCRIPT - jQuery - Inserting value into input field

I was wondering why this code won't work for me. I am trying to append value from database into input field of this submit button as I want to send it back to another table in my database. Thanks!
</div>
<form>
<input type="input" value="'+ jobpost.jobID+'" id="jobID"/>
<br>
<button type="submit" id="submit3" name="submit3"
onclick="myFunctionjobStatus();">Submit</button></form></div>
I am using the following ajax post to send data to my php file to enter into the database. Please see below.
function myFunctionjobStatus() {
var jobID = document.getElementById("jobID").value;
//AJAX code to submit form.
$.ajax({
type: "POST",
url: "http://localhost:8888/EduSubOct/jobstatus.php",
data: { userEmail: localStorage.getItem("email"), jobID:
jobID},
cache: false,
success: function(html) {
alert("Request Sent");
}
});
}
php file -
<?php
// Selecting Database
include_once 'dbh.php';
/Here we fetch the data from the URL that was passed from our HTML
form
$userEmail = $_POST['userEmail'];
$jobID = $_POST['jobID'];
$sql = "INSERT INTO jobStatus (email, jobID) VALUES
('$userEmail','$jobID');";
mysqli_query($conn, $sql);
?>

Ajax call to a php file is not working

I am trying to implement a simple form which will eventually connect to a database and make entries in it. In the tag,I am calling the php file which will connect me to the database in the back-end.
index.html
<html>
<head>
<script>
function submitForm(formId){
//var formData= $.(formId).serialize();
$.ajax({
url:'new-user.php',
type:'POST',
data:{
user_name=$("#user_name").val(),
password=$("#password").val();
}
success:function(response){
alert(response);
}
});
}
</script>
</head>
<body>
<form onsubmit="submitForm('#myForm');" id='myForm'>
User Name: <input type="text" name="user_name" id="user_name" />
Password: <input type="text" name="password" id="password" />
<input type="submit"/>
</form>
</body>
</html>
new-user.php
<?php include 'database.php';?>
<?php
mysqli_query($connect,"create table login(User_name varchar(50) NOT NULL,Password varchar(50) NOT NULL)");
$user_name=$_POST['user_name'];
$password=$_POST['password'];
if(empty($user_name)){
$name_error="name is required";
}
mysqli_query($connect,"Insert into login(User_name,Password) values('$user_name','$password')");
if(mysqli_affected_rows($connect)>0){
echo "<p>Credentials added</p>";
echo "<a href='index.html'>Go back</a>";
}else{
echo "<p>Error</p>";
echo mysqli_error($connect);
}
?>
database.php
<?php
$connect=mysqli_connect('localhost','root','','testdb');
if(mysqli_connect_errno($connect)){
echo 'failed to connect';
}
?>
The above is not creating any table in the testdb database.Neither,it is generating any alert messages.The Url however changes after clicking the submit button as http://localhost/try2/?user_name=aayushi&password=ded but after that nothing happens. This is my first php code, so I don't really know what's the meaning of this exactly.
Okay, since no one seems to actually be reading your code, there's a couple of syntax errors that I missed until I threw it into PhpStorm
Change your function to this:
function submitForm(formId){
$.ajax({
url:'/new-user.php',
type:'POST',
data:{
user_name: $("#user_name").val(),
password: $("#password").val()
}
})
.complete(function (response) {
alert(response)
})
return false; // Prevents the form from submitting the standard way
}
EDIT: Change the form to this:
<form onsubmit="return submitForm('#myForm');" id='myForm'>
In your ajax method, the success property is wrong
It is written as suceess, when it was supposed to be success
Also, to avoid refreshing the page, insert return false; at the end of the function submitForm

Using ajax in for each loop to refresh a div content

Jquery/Ajax rookie here
This is how my code should work...
When the submit button is clicked, JavaScript handles the form and post the values to the same page. The values are used in a SQL query to update a column in the database. The value from the column is echoed out and updated each time the button is clicked (SQL UPDATE QUERY), all this would be done without refreshing the page using ajax (i.e "ONLY" the value from the database would be refreshed when the button is clicked and the page shouldn't scroll back to the top). The problem is my JavaScript isn't handling the form submission as i expect it to. The div around the value isn't refreshing, i have to redirect to a different page and back to see the changes (SQL query works). How do i solve my problem to achieve this?
file.php
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1
/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#ajaxform').submit(function() { // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: "POST", // POST
url: "file.php", // the file to call
success: function(response) { // on success..
$('#emailform').html("Thank you!"); // update the DIV
}
});
return false; // cancel original event to prevent form submitting
});
});
</script>
</head>
<body>
<?php
...................
foreach($stmt as $obj){
$id = $obj['id'];
$likes = $obj['like1'];
echo '<form action="" method="post" id="ajaxform"
enctype="multipart/form-data">';
echo '<input type="hidden" name="lkcv[]" value="'.$id.'">';
echo '<input type="hidden" name="like" value="">';
echo '<input type="image" src="images/like.png" id="lksub" width="15"
value="som" height="15" style="float:right;position:relative;
margin-right:290px;"/><div class="ld">'.$likes.'</div>';
echo '</form>’;
echo '<div id="emailform"></div>';
}
?>
</body>
</html>
query.php
<?php
if( isset( $_POST['lkcv'] ) && is_array( $_POST['lkcv'] ) )
{
$idArray = array();
foreach( $_POST['lkcv'] as $value )
{
$idArray[] = intval( $value );
}
$db->query( "UPDATE comment SET like1 = like1 + 1 WHERE id IN (".implode(
',', $idArray ).")" );
}
?>
NOTE: file.php always has a dynamic url such as "file.php?post=1"
I don't know php, so apologies if some of this is wrong.
does file.php write out a full html page? If so, it should only be sending out a fragment as ajax deals with partial updates rather than pulling in an entire page.
In your success handler, you are only updating the #emailForm div, when really you also want to be replacing the content on the page with the new version.
2nd, in html, tags with an id are expected to be unique. You output
<div id="emailForm"></div>
in a loop, therefore, it isn't unique on the page, so you might not get the right one being updated
There is a parameter for $.ajax called cache, setting that will append a timestamp to your query, ensuring it is unique, no need to manually create a unique url.
$.ajax({
cache: false,
....
Lastly, to make sure that you are getting fresh content, check your web server logs to look for a http response, which means that the content hasn't changed, so the webserver sent a cached copy
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1
/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#content').on("submit", "form", function(e) { // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: "POST", // POST
cache: false,
url: "file.php?=" + $(e.currentTarget).find("name=lkcv[]").val(), // the file to call
success: function(response) { // on success..
$(e.currentTarget).html(response); // only replace the form that caused the submit
$('#emailform').html("Thank you!"); // update the DIV
}
});
return false; // cancel original event to prevent form submitting
});
});
</script>
</head>
<body>
<?php
...................
echo '<div id=content>';
foreach($stmt as $obj){
$id = $obj['id'];
$likes = $obj['like1'];
echo '<form action="" method="post" enctype="multipart/form-data">';
echo '<input type="hidden" name="lkcv[]" value="'.$id.'">';
echo '<input type="hidden" name="like" value="">';
echo '<input type="image" src="images/like.png" id="lksub" width="15"
value="som" height="15" style="float:right;position:relative;
margin-right:290px;"/><div class="ld">'.$likes.'</div>';
echo '</form>’;
}
echo '</div>';
echo '<div id="emailform"></div>';
?>

validate captcha before submit

I've use captcha for form registration, within that I have validation engine for form inline validation. I'm stuck in validating the equity of captcha.
<p class="veriText">
<label>Enter the Verification Text </label> <span style="color:red;">*</span>
<input class="validate[required] text-input" type="text" name="captcha" id="captcha" class="text" value="" />
</p>
<img src="<?= get_bloginfo('template_url'); ?>/captcha_code_file.php?rand=<?php echo rand();?>" id='captchaimg'><br/>
PHP validation: (works perfectly)
if(strcasecmp($_SESSION['code'], $_POST['captcha']) != 0){
//----mismatch values
}
But the same thing in js I have tried like
var session = <?php echo $_SESSION['code'] ?>; // this value is different
// from captcha image
Is it possible to validate captcha before submitting the form in Javascript/jQuery?
Assuming the line var session = <?php echo $_SESSION['code'] ?>; is in your html page.
When the page is generated your captcha image script is not invoked and thus $_SESSION['code'] is not initialized. The value you are getting is the code from the previous request to captcha_code_file.php. Once your page is loaded (at-least the html part) and the browser decides to call captcha_code_file.php your captcha image gets invoked and a new $_SESSION['code'] is created.
I don't recommend this, but if you want to get the current $_SESSION['code'] try to use an Ajax request to retrieve the new $_SESSION['code'] from another php file (don't call captcha_code_file.php or your session will be reset again.
Note: Never try to validate your captcha at user end. You are defeating the main purpose of captcha.
Create one ajax request for checking capcha using JavaScript, example is provided below:
var postData = $("form").serialize();
var requestUrl = '/check_capcha.php';
$.ajax({
type: "POST",
dataType: "json",
data: postData,
url: requestUrl,
success:function(data){
// success or fail message
}
});
check_capcha.php contains:
if(strcasecmp($_SESSION['code'], $_POST['captcha']) != 0){
//----mismatch values
echo 0;
}else{
echo 1;
}
exit;
You can put the javascript code before (although session is same throughout the page).
Just try a dummy code in a plain file and check the session value
OR
You can use $.ajax() to call PHP page for captcha validation
html look like this
$rand = mt_rand(100000,999999);
<span class="captcha"><?php echo $rand; ?></span>
<input name="captcha" type="text" id="captcha-compare" />
In javascript use something like that for validation engine
$('#frm-register').submit(function() {
if( $('#captcha-compare').val() != $('.captcha').text() ) {
$('#captcha-compare').validationEngine('showPrompt', 'Invalid captcha', 'load');
return false;
}
});
and in php first take $rand in session then submitting capture the input text captcha and session
You can try the below code to validate the captcha or you can also use AJAX code to validate the values before submitting the code.
<script language="JavaScript">
var session = '<?php echo $_SESSION['code'] ?>';
if(Form.captcha.value == session)
{
return true;
}
else
{
Form.submit();
}
</script>

Categories