How to get value from other when using ajax post? - javascript

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));
}
?>

Related

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

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>

Insert Data into MySQL without reloading the page (Jquery)

Here is my code:
HTML Code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action='insert.php' method='post' class='myform' >
<input type='hidden' name='tmdb_id'/>
<button class='insert'>Insert</button>
<p class='result'></p>
</form>
<form action='insert.php' method='post' class='myform' >
<input type='hidden' name='tmdb_id'/>
<button class='insert'>Insert</button>
<p class='result'></p>
</form>
<form action='insert.php' method='post' class='myform' >
<input type='hidden' name='tmdb_id'/>
<button class='insert'>Insert</button>
<p class='result'></p>
</form>
<script src='insert.js'></script>
Insert.JS file code:
$('.myform').submit(function(){
return false;
});
$('.insert').click(function(){
$.post(
$('#.yform').attr('action'),
$('.myform :input').serializeArray(),
function(result){
$('.result').html(result);
}
);
});
Expected Result: When user clicks on Insert button, the code runs insert.php file in the background (No reloading of the page), and display the result inside this <p id='result'></p>
Original Result: Only the first insert button code works. The other insert button redirects the user to insert.php.
I know, This is probably because of some same classes. But I do not know, how to fix it. I would like to make changes only in my Jquery code. I do not want to add different classes for each form.
Instead of dealing with click events, you could override default forms' submit behavior and use $(this) to work only with form being submitted.
$(".myform").submit(function(e) {
var data = $(this).serialize();
var url = $(this).attr("action");
var resultDiv = $(this).find(".result");
$.post(url, data, function(result) {
resultDiv.html(result);
});
return false;
});
grab the forms and override their submit function
get the data from the form that is being submitted
get the url to post to from this very form
grab immediate child result (instead of all of them)
pass your own success function to do whatever you need, in this case append the result
Modify this code if you want to post data from all the forms at once.
Sir I think You need to try Just Ajax code like this.
$.ajax({
url: 'URL_OF_YOUR_PAGE',
data: $('.myform :input').serializeArray(),
type: 'POST',
dataType: 'json',
success: function (r) {
//SUCCESS CODE
}
});
There is an error in your js code. change like this:
$('.insert').click(function(){
$.post(
$('.myform').attr('action'),
$('.myform :input').serializeArray(),
function(result){
$('.result').html(result);
}
);
});
jquery selector error
You can use jQquery AJAX method with multiple options and you need to disable the button after click, this will avoid multiple request to the server.
//button click
$(".insert").click(function(e){
//get the form data and serialize
var dataString = $(".myform").serialize();
//make the AJAX request, dataType is set to json
$.ajax({
type: "POST",
url: "SERVER_URL",
data: dataString,
dataType: "json",
//response from the server
success: function(data) {
console.log("SUCCESS");
},
//No response from the server
error: function(xhr){
console.log("ERROR :" + xhr.statusText);
},
//capture the request before it was sent to server
beforeSend: function(){
// disable the button
$(this).attr("disabled", true);
},
//after the response
complete: function(){
//enable the button
$(this).attr("disabled", false);
}
});
});
You can get a reference to the form in your click handler using closest
var theForm = $(this).closest('form');
Then you can read that form's action and serialize that forms data:
$('.insert').click(function(){
var theForm = $(this).closest('form');
$.post(
theForm.attr('action'),
theForm.serializeArray(),
function(result){
$('.result').html(result);
}
);
return false;
});
Here's a mock that outputs the forms data into a text box using the same approach:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action='insert.php' method='post' class='myform' >
<input type='hidden' name='tmdb_id0'/>
<button class='insert'>Insert</button>
<p class='result'></p>
</form>
<form action='insert.php' method='post' class='myform' >
<input type='hidden' name='tmdb_id1'/>
<button class='insert'>Insert</button>
<p class='result'></p>
</form>
<form action='insert.php' method='post' class='myform' >
<input type='hidden' name='tmdb_id2'/>
<button class='insert'>Insert</button>
<p class='result'></p>
</form>
<textarea id='out' style="width:600px;height:250px"></textarea>
<script src='insert.js'></script>
<script>
$('.myform').submit(function(){
return false;
});
$('.insert').click(function(){
var theForm = $(this).closest('form');
var mockData= {};
mockData["action"] = theForm.attr('action');
mockData["data"] = theForm.serializeArray();
$('#out').val(JSON.stringify(mockData));
/* $.post(
theForm.attr('action'),
theForm.serializeArray(),
function(result){
$('.result').html(result);
}
return false;
);
*/
});
</script>
If you want to submit of your second form then attached an id to that form, and submit your form data by that id. If your provided code fine then this code should be worked. If your three forms have same class then you can not catch that form uniquely from jquery side only.
$('.myform').on('submit',function(e){
e.preventDefault();
});
$('.insert').click(function(){
$.post(
$('.myform').attr('action'),
$('#secondForm').serializeArray(),
function(result){
$('.result').html(result);
}
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action='insert.php' method='post' id="firstForm" class='myform' >
<input type='hidden' name='tmdb_id'/>
<button class='insert'>Insert</button>
<p class='result'></p>
</form>
<form action='insert.php' method='post' id="secondForm" class='myform' >
<input type='hidden' name='tmdb_id'/>
<button class='insert'>Insert</button>
<p class='result'></p>
</form>
<form action='insert.php' method='post' id="thirdForm" class='myform' >
<input type='hidden' name='tmdb_id'/>
<button class='insert'>Insert</button>
<p class='result'></p>
</form>
Try this
HTML code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action='insert.php' method='post' class='myform' >
<input type='hidden' name='tmdb_id' value='2'/>
<button class='insert'>Insert</button>
<p class='result'></p>
</form>
<form action='insert.php' method='post' class='myform' >
<input type='hidden' name='tmdb_id' value='3'/>
<button class='insert'>Insert</button>
<p class='result'></p>
</form>
<form action='insert.php' method='post' class='myform' >
<input type='hidden' name='tmdb_id' value='6'/>
<button class='insert'>Insert</button>
<p class='result'></p>
</form>
<script src='insert.js'></script>
insert.js code:
$('.myform').submit(function(){
return false;
});
var elements = document.getElementsByClassName("insert");
$('.insert').click(function(){
for (var i = 0, len = elements.length; i < len; i++) {
if(elements[i]===this){
var j=i;
$.post(
$(document.getElementsByClassName("myform")[j]).attr('action'),
$(document.getElementsByClassName("myform")[j]).serializeArray(),
function(data){
$(document.getElementsByClassName("result")[j]).html(data);
}
);
}
}
});
insert.php code:
var_dump($_POST);

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');
}

Ajax - How to submit one by one input value - Codeigniter

Sorry for my english is not so good. And i'm newbie :)
I want to update one-by-one input value with ajax in Codeigniter, but it not work right.. only one save button (one form) work, others form not work .. please help me edit below code
Here's the demo code:
View:
<script>
$(function(){
$(".submit45").click(function(){
dataString = $("#prod_upd").serialize();
$.ajax({
type: "POST",
url: "<?=PREFIX?>admin/update/change_ppx3/",
data: dataString,
success: function(data){
console.log(data);
document.getElementById('dd').innerHTML=data;
}
});
return false;
});
});
</script>
<?$i=0;if(count($PPX) > 0)foreach($PPX as $item){$i++;?>
<form name="prod_upd" id="prod_upd" method="post" >
<input type="text" name="p_ppx" id="p_ppx" size="8" value="<?= number_format($item['p_ppx'],0,'','')?>" class="i_ppx">
<input type="hidden" name="ids_p" id="ids_p" size="8" value="<?=$item['id']?>" class="i_ppx">
<input type="button" name="sub" id="sub" class="submit45" value="Save4" />
<div id="dd" style="float: left;">hello</div>
</form>
<?}else{?>
<div class="no_data">Nothing here</div>
<?}?>
Controller:
function change_ppx3(){
$id_p = $_POST['ids_p'];
$rs = $this->ppx->get_ppx_by_id($id_p);
$ppx_value = $_POST['p_ppx'];
$this->ppx->update_ppx(array("id"=>$id_p),array("ppx_r"=>$ppx_value));
if($_POST['p_ppx']):
echo "done: ";
print_r($_POST['ids_p']);
echo "-";
print_r($_POST['p_ppx']);
return true;
endif;
}
because every form has the same id="prod_upd".
test this
<script>
$(function(){
$(".prod_upd").submit(function(){
var $this = $(this), dataString = $this.serialize();
$.ajax({
type: "POST",
url: "<?=PREFIX?>admin/update/change_ppx3/",
data: dataString,
success: function(data){
console.log(data);
$this.find('.dd').html(data);
}
});
return false;
});
});
</script>
<?$i=0;if(count($PPX) > 0)foreach($PPX as $item){$i++;?>
<form name="prod_upd" class="prod_upd" method="post" >
<input type="text" name="p_ppx" size="8" value="<?= number_format($item['p_ppx'],0,'','')?>" class="i_ppx">
<input type="hidden" name="ids_p" size="8" value="<?=$item['id']?>" class="i_ppx">
<input type="submit" class="submit45" value="Save4" />
<div class="dd" style="float: left;">hello</div>
</form>
<?}else{?>
<div class="no_data">Nothing here</div>
<?}?>

Categories

Resources