Ajax submit doesn't work (can't read $_POST in php) - javascript

I am trying to submit my form using Ajax. When the button is clicked the hit() function gets called and passes the contents of the textbox back to test.php
$_POST seems to be empty, since I get the alert from ajax (form was submitted) but I don't get to see the echo (echo $_POST['textbox'])
test.php
<?php
echo "test";
if($_POST)
{
echo $_POST['textbox'];
}
?>
<html>
<body>
<form action="index.php" method="post" align="center" id="form" name="form">
<script type="text/javascript" src="test2.js"> </script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js" type="text/javascript"></script>
<input type="text" class="form-control" id="input" name="input" oninput="check();">
<input type="button" class="form-control" id="send" name="send" value="Send" onclick="hit();">
</form>
</body>
</div>
</html>
test2.js
function hit() {
var inputText = $("#input").val();
var inputTextString = "textbox=" + inputText;
$.ajax({
type: 'post',
url: 'test.php',
data: inputTextString,
success: function () {
alert('form was submitted');
}
});
}

There're more of problems here
In test.php
how can you include your js file before you include jquery .. first is first ..
After Tested Yes you can use jquery $() inside a function without getting $ undefined error while you'll run the function after include jquery .. sorry my bad
Scripts should be on the <head></head> or before </body>
while you using just button click why you're using <form>
your code should be something like that
<?php
echo "test";
if($_POST)
{
echo $_POST['textbox'];
return false;
}
?>
<html>
<head>
</head>
<body>
<input type="text" class="form-control" id="input" name="input" oninput="check();">
<input type="button" class="form-control" id="send" name="send" value="Send" onclick="hit();">
<script type="text/javascript" src="test2.js"> </script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js" type="text/javascript"></script>
</body>
</div>
</html>
On test2.js
function hit() {
var inputText = $("#input").val();
var inputTextString = {textbox : inputText}; // use this
$.ajax({
type: 'post',
url: 'test.php',
data: inputTextString,
success: function () {
alert('form was submitted');
}
});
}
Note: for me I prefer to use separated php file to use it with ajax .. it'll make it easier for outputs
If you need to use a form .. you can use your form code including my notes above and make your submit button type="submit" and remove onclick="hit()" from it then on your js file you can use
$(document).ready(function(){
$('form').on('submit',function(e){
e.preventDefault(); // to prevent form reload
var inputText = $("#input").val();
var inputTextString = {textbox : inputText}; // use this
$.ajax({
type: 'post',
url: 'test.php',
data: inputTextString,
success: function () {
alert('form was submitted');
}
});
});
});

you never test if you see the reponse from echo - hence you don't alert the response from php at all.
To see what your php script returns you have to alert (or log, or do something usefull with) the passed in parameter to the success callback:
....
success: function (response) {
alert(response);
console.log(response);
},
....
Anyway you should make sure to not send additional data (like unneeded html in your case) back to ajax, but only the value/json. So in your case an exit; after echo would help.
Also follow #Mohammed-Yousef's instructions for the other issues!!

you will get the desired results in the response.
function hit() {
var inputText = $("#input").val();
$.ajax({
type: 'post',
url: 'test.php',
data: {textbox : inputText},
success: function (res) {
alert(res);
}
});
}
And you need to change in your test.php file.
<?php
echo "test";
if($_POST)
{
echo $_POST['textbox'];exit;
}
?>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="test2.js"> </script>
</head>
<body>
<form action="index.php" method="post" align="center" id="form" name="form">
<input type="text" class="form-control" id="input" name="input" oninput="check();">
<input type="button" class="form-control" id="send" name="send" value="Send" onclick="hit();">
</form>
</body>
</div>
</html>

Related

jQuery Ajax data to same PHP page not working as INTENDED?

I have 22.php that both form and PHP script reside.
Problems;
1) when I submit, result shows below. But duplicates the form.
2) Further entering in the top (above) form, changes the result accordingly.
3) When I enter in the bottom form, then also the result changes accordingly and disappear the bottom from.
What I have tried so far as solutions;
1) removed totally - url: '',
2) replaced to the same page - url: '22.php',
3) replaced to this - var yourData = $(this).serialize();
4) Placed the PHP script just soon after body tag
None of above solve! Please help!
<html>
<head>
<title>My first PHP page</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#btn").click(function(event){
event.preventDefault();
var myname = $("#name").val();
var myage = $("#age").val();
var yourData ='name='+myname+'&age='+myage; // php is expecting name and age
$.ajax({
type:'POST',
data:yourData,//Without serialized
//url: '22.php',
success:function(data) {
if(data){
$('#testform')[0].reset();//reset the form
$('#result').html(data); // here html()
//alert('Submitted');
}else{
return false;
}
}
});
});
});
</script>
</head>
<body>
<?php
if ( isset($_POST['name']) ) { // was the form submitted?
echo "Welcome ". $_POST["name"] . "<br>";
echo "You are ". $_POST["age"] . "years old<br>";
}
?>
<form method="post" id="testform">
Name:
<input type="text" name="name" id="name" />Age:
<input type="text" name="age" id="age" />
<input type="submit" name="submit" id="btn" />
</form>
<div id='result'></div>
</body>
</html>
Just place PHP code top and put exit();. Here is your full code:
<?php
if ( isset($_POST['name']) ) { // was the form submitted?
echo "Welcome ". $_POST["name"] . "<br>";
echo "You are ". $_POST["age"] . "years old<br>";
exit;
}
?>
<html>
<head>
<title>My first PHP page</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#btn").click(function(event){
event.preventDefault();
var myname = $("#name").val();
var myage = $("#age").val();
var yourData ='name='+myname+'&age='+myage; // php is expecting name and age
$.ajax({
type:'POST',
data:yourData,//Without serialized
//url: '22.php',
success:function(data) {
if(data){
$('#testform')[0].reset();//reset the form
$('#result').html(data); // here html()
//alert('Submitted');
}else{
return false;
}
}
});
});
});
</script>
</head>
<body>
<form method="post" id="testform">
Name:
<input type="text" name="name" id="name" />Age:
<input type="text" name="age" id="age" />
<input type="submit" name="submit" id="btn" />
</form>
<div id='result'></div>
</body>
</html>

Cannot pass value to Codeigniter controller using ajax

I am having a trouble while sending a value from an input element to Codeigniter controller by using ajax.
Since I have to use WYSIWYG editor (summernote), thus I can just receive the input inside a <script>. However when I press the submit button, it just reloads the current page rather than the one in the controller.
Here is my code:
PHP view
<section id="mainContent">
<form method="post">
<input type="text" id="textbox" class="editor" name="textbox">
<input id="submit_btn" type="button" name="sutmit" value="submit" onclick="myFunction()">
</form>
</section>
<script type="text/javascript">
function myFunction() {
var markupStr = $('#textbox').summernote('code');
alert(markupStr);
$.ajax({
type : 'POST',
url : "<?= site_url().'cintern/save'; ?>",
async : false,
data : {'iDes': markupStr},
success : function(data){
alert("Success!");
}
});
return false;
};
</script>
PHP controller
public function save()
{
$session_data = $this->session->userdata('logged_in');
$data['id'] = $session_data['idlogin'];
$data['role'] = $session_data['role'];
$data['pageTitle'] = 'Success';
$data['iDes'] = $this->input->post('iDes');
$this->load->view('templates/header', $data);
$this->load->view('internship/success', $data);
$this->load->view('templates/footer');
}
Please help! Thank you in advance.
You should use onsubmit of <form> tag instead.
<section id="mainContent">
<form method="post" onsubmit="myFunction()">
<input type="text" id="textbox" class="editor" name="textbox">
<input id="submit_btn" type="button" name="sutmit" value="submit">
</form>
</section>
The reason is, if you handle the onclick of your <input type="submit">, you can't intercept request of <form> tag after submit data.
I hope this can help you.
Since you are using JQuery for the ajax I suggest you use it to capture the submit also.
Remove the inline onclick assignment. Give the form an id attribute.
<section id="mainContent">
<form method="post" id="target">
<input type="text" id="textbox" class="editor" name="textbox">
<input id="submit_btn" type="button" name="sutmit" value="submit">
</form>
</section>
Turn myfunction() into a 'submit' event handler
<script type="text/javascript">
$("#target").submit(function (event) {
var markupStr = $('#textbox').summernote('code');
//stop the normal submit from happening
event.preventDefault();
$.ajax({
type: 'POST',
url: "<?= site_url().'cintern/save'; ?>",
async: false,
data: {'iDes': markupStr},
success: function (data) {
//do stuff with data then redirect to 'after_save'
console.log(data.results, data.otherstuff);
window.location.href = "http://example.com/cintern/after_save";
}
});
});
</script>
Controller:
public function save()
{
$data = $this->input->post(NULL, TRUE);
// $data is now a semi-sanitized version of $_POST
$_SESSION['iDes'] = $data['iDes'];
//do other stuff with $data
echo json_encode(['results' => "success", 'otherstuff' => $foo]);
}
public function after_save()
{
$session_data = $this->session->userdata('logged_in');
$data['id'] = $session_data['idlogin'];
$data['role'] = $session_data['role'];
$data['pageTitle'] = 'Success';
$data['iDes'] = $session_data['iDes'];
$this->load->view('templates/header', $data);
$this->load->view('internship/success', $data);
$this->load->view('templates/footer');
}

Update data using AJAX and codeigniter failed

I want to update my data using Codeigniter and AJAX for submit response..
This is my View
<form id="form_update" action="<?php echo base_url() ?>admin/update_derap_info" method="POST" role="form">
<textarea cols="80" id="editor1" name="isi" rows="10" class="form-control" >
</textarea>
<input type="submit" value="Simpan" class="btn btn-sm btn-primary" name="update_info_pemesanan">
</form>
My Controller
$data = array
(
'isi'=> ltrim(rtrim($this->input->post('isi')))
);
$this->info_derap->update($this->input->post('id_info'),$data);
echo'<div class="alert alert-success">Terimakasih, pesan anda sudah kami terima. Pemberitahuan selanjutnya kami beritahunak lewat email.</div>';
exit;
My Model
function update($id,$data){
$this->db->where($this->id, $id);
$this->db->update($this->table, $data);
}
And here is my AJAX
<script type="text/javascript">
$("#form_update").submit(function (e){
e.preventDefault();
$("#loader").show();
var url = $(this).attr('action');
var data = $(this).serialize();
$.ajax({
url:url,
type:'POST',
data:$("#form_update").serialize(),
}).done(function (data){
$("#response").html(data);
$("#loader").hide();
fillgrid();
});
});
</script>
I can update My data if I press click submit 2 times, but when I submit just 1 time , it cannot update.
What's wrong?
You cant update with form. Use this
<form action="" method="" role="form">
<textarea cols="80" id="editor1" name="isi" rows="10" class="form-control" ></textarea>
<input type="submit" value="Simpan" class="btn btn-sm btn-primary" name="update_info_pemesanan" id="form_update">
</form>
in AJAX
<script type="text/javascript">
$(function(){
$("#form_update").click(function(event){
event.preventDefault();
$("#loader").show();
var editor1= $("#editor1").val();
$.ajax(
{
type:'post',
url:"<?php echo base_url() ?>admin/update_derap_info",
data:{editor1:editor1},
success:function($data)
{
$("#response").html(data);
$("#loader").hide();
fillgrid();
}
});
});
});
</script>
in Controller
$text_area = $this->input->post('editor1')
So in $text_area Contain text which you input in your form
You should use the following code on your controller:
$this->info_derap->update($this->input->post('id_info'),$data);
Also, make sure there's a field called id_info in the corresponding view.
what a message if you using debug, you can inspect request...
you can insert or adding some javascript function "espace" your request form for example
escape($("editor1").val());

Ajax to submit a button click to php, then to a serial device

I am trying to get button to to initiate a function on a serial device, an arduino, by means of ajax and php, but cannot seem to figure it out.
Here is my html:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
$(function() {
$('#contact_form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: '/test/SubmitFormWORefresh.php',
data: $('#contact_form').serialize(),
success: function() {
alert('form was submitted');
}
});
return false;
});
});
</script>
<meta charset="utf-8">
<title>Enroll</title>
</head>
<div id="contact_form">
<form name="contact" action="">
<fieldset>
<input type="submit" name="rcmd" class="button" id="submit_btn" value="Enroll" /><br />
</fieldset>
</form>
</div>
And here is my php:
<?php
$verz="1.0";
$comPort = "/dev/ttyACM0"; /*change to correct com port */
$PHP_SELF="index.php"; //This php file locate it from root
if (isset($_POST["rcmd"])) {
$rcmd = $_POST["rcmd"];
switch ($rcmd) {
case Stop:
$fp =fopen($comPort, "w");
sleep(2);
fwrite($fp, 1); /* this is the number that it will write */
fclose($fp);
break;
case Enroll:
$fp =fopen($comPort, "w");
sleep(2);
fwrite($fp, 3); /* this is the number that it will write */
fclose($fp);
break;
default:
die('Crap, something went wrong. The page just puked.');
}/*end switch case*/
}/*end if statement*/
?>
When I run it, I get the dialog box that says the form was submitted, but the serial device does not respond to it. Any help would be greatly appreciated.
I change listenner to detect click on button and i get the value with $(this).val()
Javascript :
<script type="text/javascript">
$(function() {
$('#contact_form').on('click', '.button',function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: '/test/SubmitFormWORefresh.php',
data: 'rcmd='+$(this).val(),
success: function() {
alert('form was submitted');
}
});
return false;
});
});
</script>
Html :
<input type="button" class="button" id="submit_btn" value="Enroll" />

How to get value from other when using ajax post?

How to get value from other when using ajax post ?
i want to get value from input type="text" class="nextpage" in demo.php
to input <input type='hidden' id='page_number' name='page' value='1'/> in index.php
i try to do like this code but not work , How can i do that ?
index.php
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<script>
$(document).ready(function(){ // onload page for load content //
document.getElementById('page_number').value = '1';
$.ajax
(
{
url: 'demo.php',
type: 'POST',
data: $('#xxx1').serialize(),
cache: false,
success: function (data) {
$("#results").append(data);
function_two();
}
}
)
});
</script>
<form method="post" id="xxx1" action="Javascript:void(0);">
<input type='hidden' id='page_number' name='page' value='1'/>
</form>
<script>
$(document).ready(function(){ // click button for load content //
$("#Button").click(function(e){
var page = $('#results').find('.nextpage').val();
document.getElementById('page_number').value = page++;
$.ajax
(
{
url: 'demo.php',
type: 'POST',
data: $('#xxx2').serialize(),
cache: false,
success: function (data) {
$("#results").append(data);
function_two();
}
}
)
});
});
</script>
<form method="post" id="xxx2" action="Javascript:void(0);">
<input type='hidden' id='page_number' name='page' value='1'/>
</form>
<div id="results" style=" width: 100%; "></div>
<input type="submit" id="Button" value="OK">
demo.php
<?PHP
$page = $_POST[page];
$nextpage = ($page+1);
?>
<input type='text' class='nextpage' value='<?PHP echo $nextpage; ?>'>
OK, i get answer , cause of issue from duplicate id name page_number
just change
document.getElementById('page_number').value = '1';
to
document.getElementById('page_number_1').value = '1';
and change
<form method="post" id="xxx1" action="Javascript:void(0);">
<input type='hidden' id='page_number' name='page' value='1'/>
</form>
to
<form method="post" id="xxx1" action="Javascript:void(0);">
<input type='hidden' id='page_number_1' name='page' value='1'/>
</form>
it's will work.......
I modified your code little bit. Instead returning entire HTML input from the PHP page, I just return the page number and append the input from the front end using jquery.
Hope this will work for you
**index.php**
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<script>
$(document).ready(function(){ // onload page for load content //
document.getElementById('page_number').value = '1';
$.ajax
(
{
url: 'demo.php',
type: 'POST',
data: $('#xxx1').serialize(),
cache: false,
dataType:'json',
success: function (data) {
$("#results").append("<input type='text' class='nextpage' value='"+data.page_number+"'>");
function_two();
}
}
)
});
</script>
<form method="post" id="xxx1" action="Javascript:void(0);">
<input type='hidden' id='page_number' name='page' value='1'/>
</form>
<script>
$(document).ready(function(){ // click button for load content //
$("#Button").click(function(e){
var page = $('#results').find('.nextpage').val();
document.getElementById('page_number').value = page++;
$.ajax
(
{
url: 'demo.php',
type: 'POST',
data: $('#xxx2').serialize(),
dataType:'json',
cache: false,
success: function (data) {
$("#results").append("<input type='text' class='nextpage' value='"+data.page_number+"'>");
function_two();
}
}
)
});
});
</script>
<form method="post" id="xxx2" action="Javascript:void(0);">
<input type='hidden' id='page_number' name='page' value='1'/>
</form>
<div id="results" style=" width: 100%; "></div>
<input type="submit" id="Button" value="OK">
**demo.php**
<?PHP
$page = $_POST[page];
$nextpage = ($page+1);
if($nextpage){
echo json_encode(array("page_number" => $nextpage));
}
?>

Categories

Resources