Passing variable data between jQuery and PHP using AJAX shorthand - php

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>

Related

Submit a Form via a Reveal Modal

I am trying to submit a form and open a modal with the forms post data on it.
Modal works fine but the form post is not passed through.
I have tried jquery/ajax but no luck.
<form id="frmTractors" method="post" action='process.php'>
<select id="tractor" name="tractor_number">
<options...>
</select>
<input type="submit" value="Submit" data-reveal-id="myModal" data-reveal-ajax="process.php" />
</form>
<!-- ### MODAL ### -->
<div id="myModal" class="reveal-modal" data-reveal></div>
I am running something similar on a site:
HTML
<input type="hidden" id="processURL" value="process.php">
<select id="tractor" name="tractor_number">
<options...>
</select>
JQUERY
$(function() {
$( "#tractor" ).change(function(){
var url = $('#processURL').val();
var tractor_number = $(this).val();
var postit = $.post( url, {tractor_number:tractor_number});
postit.done(function( data ) {
$('#myModal').foundation('reveal', 'open');
});
});
});
You don't need a form, just a hidden input to hold your process file URL.

jQuery form plugin , how to submit only visible fields

Using the jQuery form plugin, I just want to submit the visible fields (not the hidden ones ) of the form.
HTML:
<div class="result"></div>
<form id="myForm" action="comment.php" method="post">
Name: <input type="text" name="name" />
Comment: <textarea name="comment"></textarea>
<div style="display:none;">
<input type="text" value="" name="name_1" />
</div>
<input type="submit" value="Submit Comment" />
</form>
I cannot find a way to submit only the visible fields using any of the methods below:
ajaxForm:
// wait for the DOM to be loaded
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#myForm').ajaxForm(function() {
alert("Thank you for your comment!");
});
});
ajaxSubmit:
$('#myForm').ajaxSubmit({
target: '.result',
success: function(response) {
alert("Thank you for your comment!");
}
});
There is another method formSerialize but found no way to use it with the 2 methods mentioned above (usable with $.ajax however).
How to submit only the visible fields using any of the two methods ?
$("#myForm").on("submit", function() {
var visibleData = $('#myForm input:visible,textarea:visible,select:visible').fieldSerialize();
$.post(this.action, visibleData, function(result) {
alert('Thank you for your comment!');
});
// this is needed to prevent a non-ajax submit
return false;
});

How do I prevent AJAX from sending me to the top of the page?

I have the following signup form near the bottom of a new website. As soon as the AJAX response loads, the page skips to the top of the page. As far as I can tell, I have included "return false" correctly. What am I missing? Thank you!
## index.php ##
<script type="text/javascript" src="mailing-list.js"></script>
<div class="signup container">
<form id="signup-form" action="<?=$_SERVER['PHP_SELF']; ?>" method="get">
<fieldset>
<legend><h2 style="align:center;">Enter Your Email Address</h2></legend>
<div class="row">
<div class="offset4 span3">
<input class="email" type="text" name="email" id="email" />
</div>
<div class="span1">
<input type="submit" name="submit" value="Join" class="btn btn-large btn-primary" />
</div>
</div>
<div id="response">
<? require_once('inc/store-address.php'); if($_GET['submit']){ echo storeAddress(); } ?>
</div>
</fieldset>
</form>
</div>
## and mailing-list.js ##
$(document).ready(function() {
$('#signup-form').submit(function() {
// update user interface
$('#response').html('Adding email address');
// Prepare query string and send AJAX request
$.ajax({
url: 'inc/store-address.php',
data: 'ajax=true&email=' + escape($('#email').val()),
success: function(msg) {
$('#response').html(msg);
}
});
return false;
});
});
$(document).ready(function() {
$('#signup-form').submit(function(e) {
e.preventDefault();
// update user interface
$('#response').html('Adding email address');
// Prepare query string and send AJAX request
$.ajax({
url: 'inc/store-address.php',
data: 'ajax=true&email=' + escape($('#email').val()),
success: function(msg) {
$('#response').html(msg);
}
});
return false;
});
});
I doubt it is executing the default form submit behavior. Prevent it byt using the preventDefault method.
$(function(){
$('#signup-form').submit(function(e) {
e.preventDefault();
//your existing code goes here
});
});
You need to prevent the form from submitting the data (even if it is to the same file). Otherwise the page will reload before your ajax call is done. You do this with .preventDefault();
Try
...
$('#signup-form').submit(function(event) {
event.preventDefault();
// update user interface
...

Submit multiple forms with jQuery php mysql

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({ ... });
});
});
})

hiding login form with Jquery

I created login from that when clicking submit button sends variables to login_success.php page.but I want to make that when I click submit button login form will be close. I can close form using Jquery
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$(".loginform").hide();
});
});
</script>
But this time form does not sends request to .php file. I made it like addin script to .php file and then redirected to index.html site.It also good but I can see reflection.How can I combine them?
this is my form
<div class="loginform">
<form action="php/login.php" method="post" id="login">
<fieldset class="loginfield">
<div>
<label for="username">User Name</label> <input type="text" id="username" name="username">
</div>
<div>
<label for="password">Password</label> <input type="password" id="password" name="password">
</div>
</fieldset>
<button type="submit" id="submit-go" ></button>
</form>
</div>
Edit
I used function as NAVEED sad .I installed FireBug in firefox and I can see that my form validation works normal.It sends and request to login.php But I cant make any change on my form.It does not close or $arr values not shown on div tags.
You should use JSON/AJAX combination:
Downlod jQuery
If your form look like this:
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript" src="ajax.js"></script>
<div id='errors'></div>
<div class='loginform' id='loginform'>
<form action="php/login.php" method="post" id="login">
Username:<input type="text" id="username" name="username">
Password:<input type="password" id="password" name="password">
<button type="submit" id="submit-go" value='Login'></button>
</form>
</div>
Your jQuery Code in ajax.js file to submit the form and then get data from 'php/login.php' in JSON and fill the required DIVs. If login is id of the form.
jQuery('#login').live('submit',function(event) {
$.ajax({
url: 'php/login.php',
type: 'POST',
dataType: 'json',
data: $('#login').serialize(),
success: function( data ) {
for(var id in data) {
jQuery('#' + id).html(data[id]);
}
}
});
return false;
});
your login.php file as described in form action attribute:
$username = $_POST['username'];
$password = $_POST['password'];
if( $username and $password found in database ) {
// It will replace only id='loginform' DIV content
// and login form will disappear
$arr = array ( "loginform" => "you are logged in" );
} else {
// It will replace only id='errors' DIV content
$arr = array ( "errors" => "You are not authenticated. Please try again" );
}
echo json_encode( $arr );
More Detail:
How to submit a form in ajax/json:
General jquery function for all forms
Try submit method
$("button").click(function(){
$("form.loginform").submit().hide();
});
PS You do know that applying onclick handler to all <button> elements on the page is bad idea, right?
$(document).ready(function(){
$("button").click(function(){
$(".loginform").hide();
return false;
});
});

Categories