I have index.php with a form. When it gets submitted I want the result from process.php to be displayed inside the result div on index.php. Pretty sure I need some kind of AJAX but I'm not sure...
index.php
<div id="result"></div>
<form action="" id="form" method="get">
<input type="text" id="q" name="q" maxlength="16">
</form>
process.php
<?php
$result = $_GET['q'];
if($result == "Pancakes") {
echo 'Result is Pancakes';
}
else {
echo 'Result is something else';
}
?>
You really don't "need" AJAX for this because you can submit it to itself and include the process file:
index.php
<div id="result">
<?php include('process.php'); ?>
</div>
<form action="index.php" id="form" method="get">
<input type="text" id="q" name="q" maxlength="16">
<input type="submit" name="submit" value="Submit">
</form>
process.php
<?php
// Check if form was submitted
if(isset($_GET['submit'])){
$result = $_GET['q'];
if($result == "Pancakes") {
echo 'Result is Pancakes';
}
else {
echo 'Result is something else';
}
}
?>
Implementing AJAX will make things more user-friendly but it definitely complicates your code. So good luck with whatever route you take!
This is a jquery Ajax example,
<script>
//wait for page load to initialize script
$(document).ready(function(){
//listen for form submission
$('form').on('submit', function(e){
//prevent form from submitting and leaving page
e.preventDefault();
// AJAX goodness!
$.ajax({
type: "GET", //type of submit
cache: false, //important or else you might get wrong data returned to you
url: "process.php", //destination
datatype: "html", //expected data format from process.php
data: $('form').serialize(), //target your form's data and serialize for a POST
success: function(data) { // data is the var which holds the output of your process.php
// locate the div with #result and fill it with returned data from process.php
$('#result').html(data);
}
});
});
});
</script>
this is jquery Ajax example,
$.ajax({
type: "POST",
url: "somescript.php",
datatype: "html",
data: dataString,
success: function(data) {
doSomething(data);
}
});
How about doing this in your index.php:
<div id="result"><?php include "process.php"?></div>
Two ways to do it.
Either use ajax to call your process.php (I'd recommend jQuery -- it's very easy to send ajax calls and do stuff based on the results.) and then use javascript to change the form.
Or have the php code that creates the form be the same php code that form submits to, and then output different things based on if there are get parameters. (Edit: MonkeyZeus gave you specifics on how to do this.)
Related
After following the example and answers by the following threads
jQuery AJAX submit form
submitting a form via AJAX
I have built a similar test form to get to learn the ajax request on submit. Your guess was right, it doesn't work for me (no alert popping up).
My testajax.php with the form:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="../test.js"></script>
<form name="feedback" id="idForm" action="(myurl)/testajax.php" method="post">
<input id="name" type="text">
<input type="submit" name="feedbacksent" value="Send" />
</p>
</form>
My test.js:
// this is the id of the form
$("#idForm").submit(function(e) {
var url = "(myurl)/testajaxinput.php"; // the script where you handle the form input.
e.preventDefault(); // avoid to execute the actual submit of the form.
alert("bla"); // does not work either
$.ajax({
type: "POST",
url: url,
data: $("#idForm").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
});
My testajaxinput.php that should handle the input:
if (isset($_POST['feedbacksent'])){
echo "<h1>".WORKS."</h1>";
}
Try this :
if (isset($_POST['feedbacksent'])){
echo "<h1>".WORKS."</h1>";
return true;
}
Then try your alert and also check have you got any error in console.
I have the following code:
$(document).on('submit', function (event) {
event.preventDefault();
console.log('submitting');
hostingURL = '/<?echo $this->CI->uri->uri_string();?>';
$('form').attr('action', hostingURL);
var form = $(this);
$.ajax({
type: "POST",
url: hostingURL,
data: form.serialize()
}).done(function (data) {
$(document).unbind("submit");
$("#maincenter").html(data);
console.log('posted');
}).fail(function (data) {
alert('failed');
});
});
this is getting the requested url, and change the form to the action needed, then posting it to the server, and returning data.
server sided i have:
echo print_r($_POST);
echo "<br> type: ".$_SERVER['REQUEST_METHOD']." <br>";
It seems like whatever i do in my form wont acually submit it. The data back is correct, but from the server side code response i do get: Array ( ) 1 type: GET no matter what im doing.
So my question is: How can i acually make the form submit the post data?
The jquery function will be used on all my forms, so i need to get every field in the form to be submitted to.
Below is one example form.
example form:
<form method="POST">
<textarea class="textarea col-12" style="height:150px;" id="messageholder" name="profiltekst" placeholder="Profiltekst">
<? echo $userprofile->profiletext ?>
</textarea>
<div class="bottomform">
<input type="submit" class="makecenter" name="updateprofile" value="Endre profiltekst">
</div>
</form>
Can't figure out what's wrong but all that happens is the URL changes to "http://localhost/?search=test" if I enter "test" for instance.
index.php
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">
</script>
<script>
$("#Form").submit(function(e) {
$.ajax({
type: "POST",
url: "search.php",
data: $("#Form").serialize(),
success: function(data)
{
alert(data);
}
});
e.preventDefault();
});
</script>
</head>
<body>
<form id=Form>
Search: <input type="text" name="search" id="search" /><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
search.php
<?php
echo 'The search is '. $_POST['search'];
?>
You're missing the action and method on your form, which are necessary for the form to generate a submit event.
<form id="Form" method="post" action="search.php" />
Now that we have the action and method defined, why not just take it from the form instead of re-writing it in Javascript? That would be better for re-usability. Also note that you have to assign event handlers when the DOM is ready. At the time you're assigning the event, the DOM element doesn't exist, so it will do nothing:
<script type="text/javascript">
$(document).ready(function() { // Here, after DOM is ready
$('#Form').submit(function(e) {
e.preventDefault();
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(data) {
// At this point, we already have the response from the server (we got it asynchronously)
// Lets update a div, for example <div id="response_message"></div>
$('#response_message').text( data );
// Div already has data, show it.
$('#response_message').show();
// Another option (same as before but with a function): Pass the response data to another function already defined: processData() in this case
// Use one or another, they're the same
processData( data );
},
error: function(err) {
alert('An error just happened...');
}
});
});
});
// This functions only receives data when the asynchronous call is finished
function processData( data )
{
$('#response_message').text( data );
// Div already has data, show it.
$('#response_message').show();
}
</script>
Note that in asynchronous calls you DO NOT expect a return. It simply doesn't exist by design (because the script would be blocked until the data is ready, and that's called synchronous). What you do in asynchronous calls is to define a function/method that will be called at any time when the data is ready (that's the success handler function). You don't know at what time it will be called, you only know that it will be called when data has been fetched and the argument will be the actual response from the server.
1st you forget " Form id and good to add method=""
<form method="post" action="#" id="Form">
2nd try to use e.preventDefault(); in the beginning not the end
3rd try to rearrange the code
<body>
<form method="post" action="#" id="Form">
Search: <input type="text" name="search" id="search" /><br />
<input type="submit" value="Submit" />
</form>
<script>
$("#Form").on('submit',function(e) {
e.preventDefault(); // use it here
$.ajax({
type: "POST",
url: "search.php",
data: $("#Form").serialize(),
success: function(data)
{
alert(data);
}
});
});
</script>
PHP/Ajax newbie here...I am trying to save the contents of a textarea into MySQL via Ajax. Although the data IS being saved correctly, Ajax isn't quite working. Basically, the page is "reloaded/refreshed" after the data is saved, unlike Ajax. Can you please tell me what is that I am doing wrong?
index.html:
<form action="save.php" method="post" id="source-form">
<span><input type="submit" value="Save" /></span>
<div>
<textarea id="editor" name="editor" >
</textarea>
</div>
</form>
javascript:
$(document).ready(function() {
$("#source-form").submit(function(){
$.ajax({
url:"save.php",
type:"post",
data:$(this).serialize(),
success: alert('saved');
});
});
save.php
<?php
// connect to the database
include('connect-db.php');
// get form data, making sure it is valid
$submit_date = date('Y-m-d H:i:s');
$content = mysql_real_escape_string(htmlspecialchars($_POST['editor']));
//build query
mysql_query("INSERT source SET submit_date='$submit_date',content='$content'")
or die(mysql_error());
header('Location: index.html');
?>
Any help on this is appreciated. Thank you.
EDIT:
For folks running into the same issue or something similar...here's a great solution from:
http://jquery.malsup.com/form/#getting-started
change your <form action="save.php" method="post" id="source-form">
to <form method="post" id="source-form">
remove the action you already declared your url in the ajax
remove header('Location: index.html'); since your should not redirect since your are using ajax. remember that if you are using ajax you dont need to refresh the page just let it receive a confirmation that the result was successful
Add a return false; to forum submit so that the form submit is cancelled:
$("#source-form").submit(function(){
$.ajax({
url:"save.php",
type:"post",
data:$(this).serialize(),
success: alert('saved');
});
return false;
});
You have to stop the default behavior of the submit button (form posting).Otherwise the form will be submitted again and you will see the page loading again. You use the preventDefault function
$("#source-form").submit(function(e){
e.preventDefault();
$.ajax({
url:"save.php",
type:"post",
data:$(this).serialize(),
success: alert('saved');
});
});
If you're only using the form for a ajax submit, I would suggest removing the form from the HTML completely and using a click event. I've stripped things down to a minimum in the HTML:
HTML
<input id="save-text" type="submit" value="Save" />
<textarea id="editor" name="editor" ></textarea>
JavaScript
$(document).ready(function() {
$("#save-text").click(function(){
$.ajax({
url:"save.php",
type:"post",
data: $("#editor").serialize(),
success: alert('saved');
});
});
I have an insert and load record (jQuery & PHP) script working fine without using AJAX. but after the AJAX call, insert (jQuery) doesn't work.
This is my code:-
$(".insert").live("click",function() {
var boxval = $("#content").val();
var dataString = 'content='+ boxval;
if(boxval==''){
alert("Please Enter Some Text");
}
else{
$.ajax({
type: "POST",
url: "demo.php",
data: dataString,
cache: false,
success: function(html){
$("table#update tbody").prepend(html);
$("table#update tbody tr").slideDown("slow");
document.getElementById('content').value='';
}
});
}
return false;
});
$(".load").live("click",function() {
$.ajax({
type: "POST",
url: "test.php",
success: function(msg){
$("#container").ajaxComplete(function(event, request, settings){
$("#container").html(msg);
});
}
});
});
});
Definitely recommend using your browsers dev tools to examine the exact request that is submitted and see if there is a problem there first.
You might also want to change the way you pass the dataString to the ajax request.
If your boxval has a "&" in it then you'll end up with an incorrectly formatted string. So, try initialising data instead as:
var data = {};
data.content = boxval;
This will ask jQuery to escape the values for you.
I'd be curious to see your form markup and your back-end PHP code; it may provide a clue.
Often I'll have a form variable called 'action', just to tell the PHP code what I want it to do (especially if that PHP script is a controller for many different actions on an object). Something like <input type="hidden" name="action" value="insert"/> or even multiple <input type="submit" name="action"/> buttons, each with a different value. In the PHP code I'll have something like:
switch ($_POST['action']) {
case 'insert':
// insert record and send HTML
break;
// other actions
}
If you've done something like this, perhaps the PHP is looking for the presence of a variable that doesn't exist.
Without being able to look at your code, I'd highly recommend the incredibly handy jQuery Form Plugin http://jquery.malsup.com/form/ . It allows you to turn a form into an AJAX form, formats your data properly, and doesn't forget the data from any of your form elements (except <input type="submit"/> buttons that weren't clicked on, which is the same behaviour that a non-AJAX form exhibits). It works just like the standard $.ajax() method.
I solved the problem
I replaced this code
$("#container").ajaxComplete(function(event, request, settings){
$("#container").html(msg);
});
with
$("#container").html(msg);
Thank you very much for your answers
<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.clicker').click(function(){
var fname = $('.fname').val();
var lname = $('.lname').val();
var message=$('.message').val();
$.ajax({
type:"POST",
url: "submit.php",
cache:false,
data: "fname="+fname+"&lname="+lname+"&message="+message,
success: function(data){
$(".result").empty();
$(".result").html(data);
}
});
return(false);
});
});
</script>
</head>
<body>
<div>Data Form</div>
<form id="form1" name="form1" method="post" action="">
<input name="fname" type="text" class="fname" size="20"/><br />
<input name="lname" type="text" class="lname" size="20"/><br />
<div class="result"><textarea name="message" rows="10" cols="50" class="message"> </textarea></div>
<input type="button" value="calculate" class="clicker" />
</form>
</body>
</html>
submit.php
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("ajaxdb",$con);
$fname=$_REQUEST['fname'];
$lname=$_REQUEST['lname'];
$message=$_REQUEST['message'];
$sql="insert into person(fname,lname,message) values('$fname','$lname','$message')";
mysql_query($sql) or die(mysql_error());
echo "The data has been submitted successfully.";
?>