I am trying to build a form where the user fills information in and clicks submit. Upon clicking, the page will never refresh. Form processing and data handling will happen after the user clicks.
I am trying to use jQuery and Ajax to accomplish this, so far this is what I have:
HTML
<form class="article_information_form" action="" method="POST">
<label>Title </label>
<input type="text" name="articleTitle"> <br>
<label>Article URL: </label>
<input type="text" name="articleUrl"> <br>
<p>Number of pages</p>
<select name="numPages">
<option value="" selected></option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
</select>
<br>
<?php echo $message;?> //For Debugging
<input type="submit" name="article_info_btn" value="Submit">
</form>
PHP
if (isset($_POST["articleTitle"], $_POST["articleUrl"], $_POST["numPages"])) {
$message = "Success!"; //For debugging
}
Ajax
$(document).on('submit', '.article_information_form', function(e) {
e.preventDefault();
$.ajax({
type : 'POST',
url : '',
success : function(data) {
alert("Success!");
}
})
})
Upon clicking the submit button, the success window popup alert is shown.
Though, the $message variable never prints out "success!" This means that its not processing the PHP $_POST.
How do I make it so that Ajax sends the information to the PHP $_POST?
$( ".article_information_form" ).on( "submit", function( event ) {
event.preventDefault();
$.post(window.location , $( this ).serialize() , function(result){
alert(result);
});
});
You didnt attach the data payload!!
Since you wanted the entire thing to be on a single page, this would be a possible way:
Full code for easy understanding:
<?php
//exececuted only if POST request as in the ajax below.
if($_SERVER[ 'REQUEST_METHOD']==='POST' ){
//your processing here
header( 'Content-Type: application/json');
//lets set the receivedToServer property to what data we got
$data = array();
$data['receivedToServer'] = $_POST;
//output data as json
echo json_encode($data);
//kill the page once the data is displayed
die();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>TEST</title>
</head>
<body>
<form class="article_information_form" action="" method="POST">
<label>Title </label>
<input type="text" name="articleTitle">
<br>
<label>Article URL: </label>
<input type="text" name="articleUrl">
<br>
<p>Number of pages</p>
<select name="numPages">
<option value="" selected></option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
</select>
<br>
<input type="submit" name="article_info_btn" value="Submit">
</form>
</body>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script>
$('.article_information_form').on('submit', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '',
data: $(this).serialize(),
success: function(data) {
//the processed data available as data variable.
//lets log the data received at server property we set before
console.log(data.receivedToServer);
alert(data.receivedToServer.articleTitle);
}
});
})
</script>
</html>
You are not pass data to your method so it is not working. So first you will check how many argument have in method, then you send same number of string in params.
You should note one thing about argument are same name as use in method argument name.
$(document).on('submit', '.article_information_form', function(e)
{
e.preventDefault();
$.ajax({
type : 'POST',
url : '',
params : {articleTitle: 'Titlename', articleUrl : 'URLName',numPages : 'PagesNo'}
success : function(data)
{
alert("Success!");
}
})
});
On your form add an ID, in our case I put an id="form_submit" and action="action.php", you need to replace it with your own path where the action should do.
<form id="form_submit" class="article_information_form" action="action.php" method="POST">
also this line of the form,
<input type="button" id="submit" name="article_info_btn" value="Submit">
change the type type="bumit" to type="button" to prevent default submission.
and the jquery,
$('#submit').click(function() {
var submit_url = $(this).parent('form').attr('action');
$.ajax({
type : 'POST',
url : submit_url,
data : $('#form_submit').serialize(),
dataType : 'json',
success : function(data) {
alert("Success!");
}
})
})
This line var submit_url = $(this).parent('form').attr('action'); get the path on the action="" and use that path to passed data.
You need to add data to your ajax call:
$(document).on('submit', '.article_information_form', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
//url: '', by default is the current page url.
data: $('.article_information_form').serialize(),//This line
success: function(data) {
$('.article_information_form type["submit"]').before("<div>"+data+"</div>")
}
})
})
PHP:
if (isset($_POST["articleTitle"], $_POST["articleUrl"], $_POST["numPages"])) {
echo "Success!"; //For debugging
exit();
}
Like the others have said, you need to add a data parameter to your $.ajax() call.
Your other question - reading the comments - is about how you can get the PHP $message variable to show up without a page load.
That is, unfortunately, impossible without a page-refresh because PHP is rendered on the server side.
What I would suggest, is creating another PHP file that handles the logic that you're trying to create, and then using AJAX to throw the response back onto the current page. Achieving what I believe you want to do.
So! Example time.
first.php
<!doctype html>
<html>
<head><title>First</title></head>
<body>
<form id="myForm">
<input name="email" type="email" />
<button>Go!</button>
</form>
<div id="message"></div>
<script>
$('#myForm').on('submit', function(event){
event.preventDefault();
$.ajax({
type: 'POST',
data: $().serialize(); // send the form data to..
url: 'second.php', // your new PHP page
complete: function(xhr, status){
console.log('xhr', xhr);
console.log('status', status);
$('#message').text(status);
}
});
});
</script>
<body>
</html>
second.php
<?php
if (isset($_POST["email"]) {
echo "Success!";
} else {
echo "Error!";
}
?>
1- Your Ajax Code :-
<script>
$(function() {
$(".article_information_form").on("submit", function(event) {
event.preventDefault();
$.ajax({
url: "process_page.php",
type: "post",
data: $(this).serialize(),
success: function(html) {
$('#msg').html(html);
}
});
});
});
</script>
2- To print AJAX response add the following "div" under the "body" tag :-
##<div id='msg' ></div>
3- Create a PHP page "process_page.php" to receive the submitted data and then send the result
<?php
$numPages = $_POST['numPages'];
echo $numPages; //anything you echo here will be displayed in the <div id='msg'> at the main page
?>
good luck
I want to make dropdown where I select the value and it can fetch data from database without submit button.
I paste my code here I am student and making project I shall be very thankful to you please help...
My controller is
public function find($id)
{
$product=$this->user_model->find($id);
echo "ID ".$product->email;
}
Model is
public function find($id)
{
$this->db->where('id',$id);
return $this->db->get('users')->row();
}
View file:
<script type="text/javascript">
$(document).ready(function() {
$('#slt').change(function(){
var country_id = $('#slt').val();
$.ajax({
type: 'GET',
url: "<?php echo base_url('index.php/main/find/')?>"+country_id,
success: function(result)
{
$('#result').html(result);
}
});
});
});
</script>
<form>
<input type="button" value="find" id="btnfind"/>
<select name="opt" id="slt">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">one</option>
<option value="4">two</option>
</select>
<br/>
<div id="result"></div>
</form>
<script type="text/javascript">
$(document).ready(function(){
$('#slt').change(function(){
var country_id = $('#slt').val();
$.ajax({
type:'GET',
data:country_id,
url:"<?php echo base_url('index.php/main/find/')?>",
success:function(result)
{
$('#result').html(result);
}
});
});
});
</script>
Change $('#result').html(result) to $('#result').text(result)
What I'm trying to do is create a chained select boxes and display the information when selects. How I can connect my first dropdown to my second dropdown? When I try to add this <select name="customers" id="customers" onchange="showUser(this.value)"> it also not working.
This like the function is http://www.w3schools.com/ajax/ajax_database.asp
What I need to do is like this http://www.melco-crown.com/eng/careerpop_js.php
What I have right now is this
<script>
function showUser(str,ids) {
var $txtHint = $('#txtHint');
if (str=="" || ids=="") {
$txtHint.html('');
return;
}
$txtHint.load('list.php?q='+str+'&id='+ids)
}
</script>
I don't have problem in list.php, what I can't do is the ajax function. Any help will appreciate.
Here's my full script
Script Loads the Information from database display in HTML table.
<script>
function showUser(str) {
var $txtHint = $('#txtHint');
if (str=="") {
$txtHint.html('');
return;
}
$txtHint.load('list.php?q='+str)
}
</script>
HTML FORM and SELECT BOXES
<form action="">
<select name="customers" id="customers" onchange="showUser(this.value)">
<option value="">Select a customer:</option>
<option value="ALFKI">Alfreds Futterkiste</option>
<option value="NORTS ">North/South</option>
<option value="WOLZA">Wolski Zajazd</option>
</select>
</form>
<br>
<select name="city" class="city">
<option selected="selected">--Select City--</option>
</select>
<div id="txtHint">Customer info will be listed here...</div>
Ajax Script for Chained Select box
<script type="text/javascript">
$(document).ready(function()
{
$("#customers").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "ajax_city.php",
data: dataString,
cache: false,
success: function(html)
{
$(".city").html(html);
}
});
});
});
</script>
How do i pass the selected value in a SELECT tag with serializeArray?I tried the followng code but when i click post it empties the select tag option.
html
<form action="" name="frm" id="frm" method="post">
<input type="text" name="title_val" value="abc" id="title_val"/>
<select name="test" id="test">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
post
</form>
JS
$( document ).ready(function() {
$('#save').click(function() {
var form = $('#frm');
$.ajax({
url: 'topic.php',
type:'post',
data: form.serializeArray(),
success: function(response) {
$('#test').html(response);
}
});
});
});
php
<?php
echo $_POST['test'];
?>
following code works for me,
data: form.serialize();
How to pass country name in html page to php page using ajax.
demo.php
<html>
<head>
<title>Dynamic Form</title>
<script src="http://code.jquery.com/jquery-1.10.1.min.js" ></script>
<script>
$(document).ready(function(){
$("form").on('submit',function(event){
event.preventDefault();
data = $(this).serialize();
$.ajax({
type: "GET",
url: "post.php",
data: data
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
});
</script>
</head>
<body>
<form>
<table>
<tr>
<td>
<select name="one" onchange="if (this.value=='other'){this.form['other'].style.visibility='visible';this.form['submit'].style.visibility='visible'}else {this.form['other'].style.visibility='hidden';this.form['submit'].style.visibility='hidden'};"
<option value="" selected="selected">Select...</option>
<option value="India">India</option>
<option value="Pakistan">Pakistan</option>
<option value="Us">Us</option>
<option value="other">Other</option>
</select>
<input type="textbox" name="other" id="other" style="visibility:hidden;"/>
<input type="submit" name="submit" value="Add Country" style="visibility:hidden;"/>
</td>
</tr>
</table>
</form>
</body>
post.php
<?php
if(isset($_POST['submit']))
{
$Country = $_POST['other'];
echo $Country;
}
?>
When user select other from drop down list at that time display one
textbox and one submit button.when user click on submit button at that
time pass country name of demo.php to post.php using ajax.
You have a few errors. $_POST['submit'] is never posted with the data = $(this).serialize();. So you need to check something else.
Also, you define GET as your method in AJAX but check $_POST in PHP. So change one of the two.
Something like:
HTML / JavaScript:
<html>
<head>
<title>Dynamic Form</title>
<script src="http://code.jquery.com/jquery-1.10.1.min.js" ></script>
<script>
$(document).ready(function(){
$("form").on('submit',function(event){
event.preventDefault();
data = $(this).serialize();
$.ajax({
type: "POST",
url: "post.php",
data: data
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
});
</script>
</head>
<body>
<form>
<table>
<tr>
<td>
<select name="one" onchange="if (this.value=='other'){this.form['other'].style.visibility='visible';this.form['submit'].style.visibility='visible'}else {this.form['other'].style.visibility='hidden';this.form['submit'].style.visibility='hidden'};">
<option value="" selected="selected">Select...</option>
<option value="India">India</option>
<option value="Pakistan">Pakistan</option>
<option value="Us">Us</option>
<option value="other">Other</option>
</select>
<input type="textbox" name="other" id="other" style="visibility:hidden;"/>
<input type="submit" name="submit" value="Add Country" style="visibility:hidden;"/>
</td>
</tr>
</table>
</form>
</body>
PHP:
<?php
if(isset($_POST['other'])) {
$Country = $_POST['other'];
echo $Country;
}
?>
you can try this
$(document).ready(function(){
$("form").on('submit',function(event){
var country = $("select[name=one]").val();
$.ajax({
type: 'POST',
dataType: 'json',
url: "post.php",
data: { country:country},
success: function(json) {
}
});
});