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>
Related
I am building a simple sign up form using ajax when I creating a data object and pass to PHP file.It shows variables and doesn't show values of that PHP variable.
The code of HTML of form is
<form id="myForm" name="myForm" action="" method="POST" class="register">
<p>
<label>Name *</label>
<input name="name" type="text" class="long"/>
</p>
<p>
<label>Institute Name *</label>
<input name="iname" type="text" maxlength="10"/>
</p>
<div>
<button id="button" class="button" name="register">Register »</button>
</div>
</form>
The code of js is
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var form=$("#myForm").serialize();
$("#button").click(function(){
$.ajax({
type:"POST",
url: "mainlogic.php",
data:form,
success: function(result){
alert(result);
}
});
});
})
</script>
The code of PHP is
(mainlogic.php)
if(isset($_POST)) {
print_r($_POST);//////varaibles having null values if it is set
$name=trim($_POST['name']);
echo $name;
}
You are serializing your form on document load. At this stage, the form isn't filled yet. You should serialize your form inside your button click event handler instead.
$(document).ready(function(){
$("#button").click(function(){
var form=$("#myForm").serialize();
$.ajax({
type:"POST",
url: "mainlogic.php",
data:form,
success: function(result){
alert(result);
}
});
});
})
In this code you serialize blank form, just after document is ready:
<script>
$(document).ready(function(){
var form=$("#myForm").serialize();
$("#button").click(function(){
$.ajax({
type:"POST",
url: "mainlogic.php",
data:form,
success: function(result){
alert(result);
}
});
});
})
</script>
Valid click function should begins like:
$("#button").click(function(){
var form=$("#myForm").serialize();
$.ajax({...
It means - serialize form right after button clicked.
var form = $("#myForm").serialize();
That is the line that collects the data from the form.
You have it immediately after $(document).ready(function() { so you will collect the data as soon as the DOM is ready. This won't work because it is before the user has had a chance to fill in the form.
You need to collect the data from the form when the button is clicked. Move that line inside the click event handler function.
The problem is that you calculate the form values at the beginning when loading the page when they have no value yet. You have to move the variable form calculation inside the button binding.
<script>
$(document).ready(function(){
$("#button").click(function(){
var form=$("#myForm").serialize();
$.ajax({
type:"POST",
url: "mainlogic.php",
data:form,
success: function(result){
alert(result);
}
});
});
})
</script>
Alpadev got the right answer, but here are a few leads that can help you in the future:
ajax
You should add the below error coding in your Ajax call, to display information if the request got a problem:
$.ajax({
[…]
error: function(jqXHR, textStatus, errorThrown){
// Error handling
console.log(form); // where “form” is your variable
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
}
});
$_POST
$_POST refers to all the variables that are passed by the page to the server.
You need to use a variable name to access it in your php.
See there for details about $_POST:
http://php.net/manual/en/reserved.variables.post.php
print_r($_POST); should output the array of all the posted variables on your page.
Make sure that:
⋅ The Ajax request ended correctly,
⋅ The print_r instruction is not conditioned by something else that evaluates to false,
⋅ The array is displayed in the page, not hidden by other elements. (You could take a look at the html source code instead of the output page to be sure about it.)
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.
<form role="form" method="post" action="test.php">
<label for="contact">Mobile No:</label><br>
<input type="tel" class="form-control" name="contact" title="Mobile number should not contain alphabets. Maxlength 10" placeholder="Enter your phone no" maxlength="15" required id='contact_no'>
<br><br>
<button type="submit" class="btn btn-success" name="submit" id="submit">Submit</button>
<button type="reset" class="btn btn-default" id='reset'>Reset</button>
</form>
Ajax and Javascript Code
script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(){
var dialcode = $(".country-list .active").data().dialCode;
var contact = $("#contact_no").val().replace(" ","");
var countrycode = $('.country-list .active').data().countryCode;
var cn;
var cc;
var dc;
$.ajax({
url: "test.php",
type: "POST",
data: {'cc' : contact},
success: function(data)
{
alert("success");
}
});
});
});
</script>
The variables show the values if displayed by alert message but are not passed on to the test.php page. It shows undefined index error at the following statement
test.php is as follows
<?php
if(isset($_POST['submit'])){
$contact = $_POST['cc']; //it shows the error here
}
echo $contact;
I had referred to many websites which show the same thing. It dosent work for me. I think the syntz of ajax is correct and have tried all possibilities but still dosent work. Please help
You're posting {cc: contact}, but you're checking for $_POST['submit'] which isn't being sent. The callback also doesn't stop the event, so you might want to return false (stops default and propagation). Something like this should do the trick:
$('#submit').on('click', function()
{
//do stuff
$.ajax({
data: {cc: contact},
method: 'post',
success: function()
{
//handle response here
}
});
return false;
});
Then, in PHP:
if (isset($_POST['cc']))
{
//ajax request with cc data
}
Also not that this:
$("#contact_no").val().replace(" ","");
Will only replace 1 space, not all of them, for that you'll need to use a regex with a g (for global) flag:
$("#contact_no").val().replace(/\s+/g,"");
You are using ajax to form submit
and you use $_POST['submit'] to check it would be $_POST['cc']
test.php
<?php
if(isset($_POST['cc'])){// change submit to cc
$contact = $_POST['cc'];//it shows the error here
}
echo $contact;
#Saty answer worked for me, but my code on ajax was a bit different. I had multiple form data wrapped up into a form variable, that was passed to the php page.
const form = new FormData();
form.append('keywords', keywords);
form.append('timescale', timescale);
form.append('pricing_entered', pricing_entered);
$.ajax({
url: "../config/save_status.php",
data: form,
method: "POST",
datatype: "text",
success: function (response, data) {
}
Then my php was:
if (isset($_POST['data'])) {
// all code about database uploading
}
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.)
How do I serialize a form in jquery that is generated by php output?
$qrform = '<form action="" method="post" id="qrgen">
<p><strong>Bookmark a Website</strong></p>
Title<input type="text" name="title"><br />
Url<input type="text" name="url"><br />
<input type="submit" value="Generate"></form>';
echo $qrform ;
Now this data is displayed by an AJAX request. A php function outputs the data and then shows the form in the browser window.
How do I serialize this form in jquery, when the form is submitted?
what you need is
jQuery('#qrgen').serialize();
Updated code if your getting the form via ajax you will need to bind the submit button like this:
$(function () {
$(document).on('submit', '#qrgen', function (e) {
e.preventDefault(); //Prevent normal form submittion
var $form = $(this);
$.ajax({
url: $form.attr('action'),
data : $form.serialize(),
success: function(data) {
alert('Ajax was successful');
},
type : 'POST' //'POST' or 'GET'
});
});
});