Submit multiple forms with jQuery php mysql - php

I have any page for answer/question. i retrieve list of question for admin. admin see this. now i need to send answer to each question. so i for each question put textarea and form with post action. now i need to when send answer of question message, if send message to external php files = true; of message(ID) remove(jquery slideup effect). for this i have jquery submit form code ( without refresh page ) but I have big problem. this worked ONLY with one form ! and not worked for all list form ( question + answer form ) . how to worked my code for multiple form ? I chose the right way?
html code :
<form action="insert.php?id=42" id="forms" method="POST" name="form">
<div id="box">
<div class="messagequestion"></div>
<div class="messagereply"><textarea></textarea><input type="submit" class="submit" name="submit" value="submit"></div>
</div>
</form>
<form action="insert.php?id=45" id="forms" method="POST" name="form">
<div id="box">
<div class="messagequestion"></div>
<div class="messagereply"><textarea></textarea><input type="submit" class="submit" name="submit" value="submit"></div>
</div>
</form>
<form action="insert.php?id=48" id="forms" method="POST" name="form">
<div id="box">
<div class="messagequestion"></div>
<div class="messagereply"><textarea></textarea><input type="submit" class="submit" name="submit" value="submit"></div>
</div>
</form>
<form action="insert.php?id=50" id="forms" method="POST" name="form">
<div id="box">
<div class="messagequestion"></div>
<div class="messagereply"><textarea></textarea><input type="submit" class="submit" name="submit" value="submit"></div>
</div>
</form>
Thanks

Your major issue is probably that you are trying to reuse ids. All the forms have the id of "forms" and you are also sharing the id "box".
All ids should uniquely identify an element. Use a class when you need to classify an element. I'd recommend you change id="forms" on all the forms to class="reply_form" and then also change id="box" on all the divs to class="reply_box". Then change styles set for #forms and #box to those set for .reply_form and .reply instead.
EDIT - tweaks made in jsfiddle after some discussion with the OP.
http://jsfiddle.net/gvnfg/5/

just change the selector. id attribute must be unique in html
$("[name='form']").submit(function() {
$this = $(this);
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: $(this).serialize(),
cache: false,
beforeSend: function() {
$('#loading').show();
$('#result').hide();
},
success: function(data) {
if(data==1){
$('#loading').hide();
$('#result').fadeIn('slow').html("ok");
$('#result').addClass('true');
$this.slideUp(1000);
}
else {
$('#loading').hide();
$('#result').fadeIn('slow').html(data);
$('#result').addClass('errors');
}}
});
e.preventDefault();
return false;
});

use Jquery .each() method:
$(document).ready(function() {
$('#forms').each(function() {
this.submit(function() {
$.ajax({ ... });
});
});
})

Related

My HTML form has its action linked to php code. When the submit button is clicked though, the form redirects to the PHP file. How can I prevent this?

I have a signup form in my HTML file. The action of the form is a PHP file. I want the PHP to process the entered data and leave the user on the signup page (HTML.) However, when the submit button is clicked, the website redirects to the PHP file. Is there some way of preventing this?
I have tried setting the form's target to "_self", but that didn't help.
HTML:
<? include('signup.php'); ?>
<?php include('errors.php'); ?>
<form method="post" action="signup.php">
***More Input fields here***
<button type="submit" name="submit">Sign Up</button>
you can actually leave that empty, so the same page gets targeted :)
Remove or blank the action attribute in form like as:
HTML:
<?php include('signup.php');
include('errors.php');
?>
<form method="post">
***More Input fields here***
<button type="submit" name="submit">Sign Up</button>
</form>
If you don't want to refresh the page and handle user input you can use AJAX
Simple example:
<form>
<label for="username">
Username
<input type="text" id="username">
</label>
<label for="password">
Password
<input type="password" id="password">
</label>
<button id="submit"></button>
</form>
<script>
$(function () {
$('#submit').click(function () {
$.ajax({
method: 'POST',
url: 'signup.php',
data:
{
name: $('#username').val(),
password: $('#password').val()
}
}).done(function (msg) {
alert('Data Saved: ' + msg);
});
});
});
</script>
If you want to send POST request to the same page, just remove action attribute from the form
<form method="post">
***More Input fields here***
<button type="submit" name="submit">Sign Up</button>

Multiple different forms in one ajax php page

Due to language limitations I might not understood how to ask Google about what I want to accomplish, but I hope you will understand.
I have three forms which i want to show on the same page without refresh. First form submits action to php which determines which function (with yet another form) to show. But buttons interfere and I am nowhere near what I wanted to do.
Index.php is supposed to send user input to calculator.php which then opens next form depending on value:
<form id="form1" method="post" formaction="calculator.php">
<input id="form1" type="submit" value="Submit" />
<div id="parseSecondForm"></div>
<script type="text/javascript">
$(function(){
$('#form1').on('submit', function(e){
e.preventDefault();
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('formaction'),
data: $(this).serialize(),
beforeSend: function(){
$('#parseSecondForm').html('<img src="loading.gif" />');
},
success: function(data){
$('#parseSecondForm').html(data);
}
});
});
});
</script>
calculator.php receives user input and echoes next form in #parseSecondForm div in index.php:
if (form1 === '1') {
echo '
<form id="form2" method="post" formaction="form2.php">
<input id="form2" type="submit" value="Submit" />
<div id="thankyou"></div>
<!--submit saves php result in MySQL and thanks the user in next div-->
';
}
else {
echo '
<form id="form3" method="post" formaction="form3.php">
<input id="form3" type="submit" value="Submit" />
<div id="thankyou"></div>
<!--submit saves php result in MySQL and thanks the user in next div-->
';
}
I tried to echo modified javascript from index.php, but it just resets all the forms.
Maybe there are some form scripts designated for the cause or any other ideas how can I fix the issue?
In Javascript/HTML you cannot have two items with the same IDs:
<form id="form1" method="post" formaction="calculator.php">
<input id="form1" type="submit" value="Submit" />
form1 can be used only once.
Same for the php dynamically created forms.

PHP image upload through Ajax serialize()

File upload through ajax serialize():
<form id="addform" class="form-horizontal" enctype="multipart/form-data" >
<div class="form-group">
<label for="link" class="control-label col-xs-3">Image</label>
<div class="col-xs-6">
<input id="file" name="file" type="file" class="form-control">
</div>
</div>
</form>
AJAX CODE using serialize():
$('#save11').click(function(){
$.ajax({
type : "POST",
url : "page/add-journal.php",
data :$('#addform').serialize(),
success : function(data)
{
alert(data);
window.location.href="home-page.php";
}
});
});
Here PHP code:
<?php
include '../dbConnection.php';
$tmp=$_FILES['file']['tmp_name'];
$serverpath="upload/".$_FILES['file']['name'];
$file=$_FILES['file']['name'];
move_uploaded_file($tmp,$serverpath);
$sql="insert into journal set file='".$file."'";
$query=mysql_query($sql);
?>
Only give me solution using serialize() only. If not so give me best solution.
I have made some changes in your code.. you can use below code for uploading images using ajax
<form id="addform" class="form-horizontal" enctype="multipart/form-data" >
<div class="form-group">
<label for="link" class="control-label col-xs-3">Image</label>
<div class="col-xs-6">
<input id="file" name="file" type="file" class="form-control">
</div>
<input type="submit" name="save" value="save" />
</div>
</form>
<script>
$('#addform').submit(function(e) {
e.preventDefault();
var data = new FormData(this); // <-- 'this' is your form element
$.ajax({
url: 'page/add-journal.php',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data) {
alert(data);
window.location.href = "home-page.php";
}
});
});
</script>
Note:
you haven't provided that how you submit your form, so I have put a submit button
You are using mysql functions, but they are officially deprecated now from php, you should use mysqli or PDO.
Form id in HTML is addform and in ajax you are using #addformkey. You will have to change the id at one place. I doubt this will work though.
only give me solution using serialize () only
https://api.jquery.com/serialize/
The .serialize() method creates a text string in standard URL-encoded notation. It can act on a jQuery object that has selected individual form controls, such as <input>, <textarea>, and <select>: $( "input, textarea, select" ).serialize();
I doubt it can serialize a file.

Passing variable data between jQuery and PHP using AJAX shorthand

I'm trying to create a search feature that searches a database based on the criteria a user has entered. Right now, I'm just trying to get the jQuery variable data into PHP. I've decided to use the shorthand AJAX $.post method because this is just a demo project. I know there are numerous similar questions like mine, but I have yet to find an answer to any of them that I can use.
So what I'm trying to do is, the user will click on a drop down menu and select an option. AJAX then sends the selected value to the PHP file and the PHP will eventually perform a database search based on what was selected. The issue is, in PHP, I'm getting a string of "Search" when the data is parsed and I echo it but when I do a console log on the variable that was sent, I'm getting the correct text. Can anyone tell me where I'm going wrong?
Here's what I have so far.
AJAX
$("#search_form").on("submit", function(ev){
ev.preventDefault();
$.post("../php/test.php", $(this).serialize(), function(data){
console.log(data);
})
})
PHP
ob_start();
require("../includes/header.php");
$criteria = $_POST["search"];
ob_clean();
echo $criteria;
HTML
<form id="search_form" method="post">
<fieldset id="search_by">
<div class="select" name="searchBy" id="searchBy">
<p>Search By...</p>
<div class="arrow"></div>
<div class="option-menu">
<div class="option">Airport Identifier</div>
<div class="option">Top Rated</div>
<div class="option">Instructor</div>
<div class="option">Malfunctions/Maneuvers</div>
</div>
</div>
<input type="text" name="search" id="search" />
<input type="submit" class="button" value="Search_Now" />
</fieldset>
As Requested
Here is a fiddle of the drop down menu to show how it works.
http://jsfiddle.net/xvmxc0zo/
Your form is being submitted via default form submission; the ajax call is misplaced, it should be within the submit handler, which should prevent default form submission.
Note that I have removed both name and id attributes from the submit button; you do not need them. Just let the submit button do it's job and listen for the submit event on the form where you would then use event.preventDefault(); to make sure the form does not submit, then you can make your ajax call.
$("#searchBy").on("click", ".option", function(){
$('#search').val( $(this).text() );
});
$('form').on('submit', function(e) {
e.preventDefault();
$.post("../php/test.php", $(this).serialize(), function(data){
//jsonData = window.JSON.parse(data);
console.log( data);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
<fieldset id="search_by">
<div class="select" name="searchBy" id="searchBy">
<p>Search By...</p>
<div class="arrow"></div>
<div class="option-menu">
<div class="option">Airport Identifier</div>
<div class="option">Top Rated</div>
<div class="option">Instructor</div>
<div class="option">Malfunctions/Maneuvers</div>
</div>
</div>
<input type="hidden" name="search" id="search" />
<input type="text" name="search_text" id="search_text" />
<input type="submit" class="button" value="Search" />
</fieldset>
</form>
In your PHP use echo $criteria; instead of echo json_encode($criteria);.
I'd suggest to use the way of jQuery documentation to check changes in your drop down.
$( "select" ).change(function () {
$( "select option:selected" ).each(function() {
$.post("../php/test.php", {search: $(this).text()}, function(data){
jsonData = window.JSON.parse(data);
});
});
})
You are getting "Search" on the PHP side because that is the value of your submit button.
You want the post to occur when you click on an option? Try adjusting your selector as follows:
$("#searchBy .option").on("click", function () {
var search = $(this).text().trim();
$.post("../php/test.php", { search: search }, function (data) {
jsonData = window.JSON.parse(data);
})
});
I think your header.php is provoking the error. I created a test file myself with your code and that works perfectly fine:
<?php
if($_POST)
{
ob_start();
//require("../includes/header.php");
$criteria = $_POST["search"];
ob_clean();
echo json_encode($criteria);
exit;
}
?>
<fieldset id="search_by">
<div class="select" name="searchBy" id="searchBy">
<p>Search By...</p>
<div class="arrow"></div>
<div class="option-menu">
<div class="option">Airport Identifier</div>
<div class="option">Top Rated</div>
<div class="option">Instructor</div>
<div class="option">Malfunctions/Maneuvers</div>
</div>
</div>
<input type="text" name="search_text" id="search_text" />
<input type="submit" name="search" id="search" class="button" value="Search" />
</fieldset>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
$("#searchBy").on("click", ".option", function(){
var search = $(this).text();
$.post("<?=$_SERVER['PHP_SELF']?>", {search: search}, function(data){
jsonData = window.JSON.parse(data);
console.log(jsonData); //Prints the correct string
})
});
</script>

Show HTML for specific div on click

I have some HTML and Ajax set up so that if you click a certain image (the reply-quote class below), it initiates some Ajax to echo HTML elsewhere on the page.
As shown below, the HTML file contains the same block of divs multiple times. My problem is that, if a user clicks the image, how can I make Ajax show the HTML (within show-reply div) for that specific block and not all of them?
<!-- BLOCK ONE -->
<div class="style1">
<div class="style2">
<img src="image.png" class="reply-quote" />
<div class="style3">
<div class="style4">
<div id="show-reply"></div>
<div class="reply-box">
<form class="reply-container no-margin" method="POST" action="">
<textarea class="reply-field" name="new_comment" placeholder="Write a reply..."></textarea>
<button name="submit" class="btn" type="submit">Post</button>
</form>
</div>
</div>
</div>
</div>
</div>
<!-- BLOCK TWO -->
<div class="style1">
<div class="style2">
<img src="image.png" class="reply-quote" />
<div class="style3">
<div class="style4">
<div id="show-reply"></div>
<div class="reply-box">
<form class="reply-container no-margin" method="POST" action="">
<textarea class="reply-field" name="new_comment" placeholder="Write a reply..."></textarea>
<button name="submit" class="btn" type="submit">Post</button>
</form>
</div>
</div>
</div>
</div>
</div>
Here's the JQuery I have right now:
$(document).ready(function() {
$(".reply-quote").click(function() {
$.ajax({
url: 'assets/misc/show_reply.php', // this file simply echoes back the HTML to the `show-reply` div
type: "POST",
data: {post_id: $(this).attr('id')},
success: function(data) {
$("#show-reply").append(data); // this is where the problem lies
}
});
});
});
To my understanding, I have to somehow implement $(this), parent(), find(), etc. instead of the current line I'm using ($("#show-reply").append(data);). The question is, what should that line be so that if I click the image, it only shows the HTML for that specific block?
Please help!
First: ID should be unique in a document, use class attribute instead for show-reply and other elements where id is repeated
<div class="show-reply"></div>
then you need to find the show-reply next to the clicked reply-quote image
$(document).ready(function() {
$(".reply-quote").click(function() {
var $reply = $(this);
$.ajax({
url: 'assets/misc/show_reply.php', // this file simply echoes back the HTML to the `show-reply` div
type: "POST",
data: {post_id: $(this).attr('id')},
success: function(data) {
$reply.closest('.comment-container').find(".show-reply").append(data);
}
});
});
});
try this
$("div").click(function(e) {
if($(e.target).is('.reply-quote')){
e.preventDefault();
return;
}
alert("work ");
});
You should change the id="show-reply" to class="show-reply" in html, and then in JS change $("#show-reply").append(data); to $(this).parent(".show-reply").append(data);

Categories