I have a form,
<form>
<input id="amount" type="text" placeholder="Give amount" name="myamount"/>
<button class="btn btn-lg" type="submit" id="btn1" >FirstBTN</button>
<button class="btn btn-lg" type="submit" id="btn2">SecondBTN</button>
</form>
Which needs to post data to a function inside the controller. I am trying to make two buttons, post data to two different controller functions. And this is my jquery code written in html file (view):
<script type="text/javascript">
$('#btn1').click(function() {
$.ajax({
url: 'helloworld/firstmoney',
type: 'POST',
data: {'submit' : true ,myamount: $("#amount").val()},
success: function (result) {
}
});
});
</script>
<script type="text/javascript">
$('#btn2').click(function() {
$.ajax({
url: 'helloworld/secondmoney',
type: 'POST',
data: {'submit' : true ,myamount: $("#amount").val()},
success: function (result) {
}
});
});
</script>
Here is the controller but I am not getting any values in my controller..
public function firstmoney(){
$this->load->helper('form');
$Money = $this->input->post("myamount");
$data = array(
'Money' => $Money
);
$this->load->view("page1", $data);
}
public function secondmoney(){
$this->load->helper('form');
$Money = $this->input->post("myamount");
$data = array(
'Money' => $Money
);
$this->load->view("page2", $data);
}
my controller name is helloworld and I need to assign values in $money but I cant get it working. I am a beginner programmer so please do tell me what steps I should follow.
First, your AJAX should look like this one.
$('#btn2').click(function() {
$.ajax({
url: 'helloworld/secondmoney',
method: 'POST',//not type
data: { myamount: $("#amount").val() }//no need for submit variable (although you can use it) since this will be submitted on click; no quotes over variables
})
.done(function(result)) {
//do your stuff on response
});
});
Second: no need for ajax and you should use classic form with post method because you are making redirection in controller/method where data is posted to.
AJAX requires JSON formated response, and it is not in this case. So wether change view to have form with method and action, wether change controller/method to return JSON string back to AJAX.
var base_url= '<?php echo base_url() ?>';
url: base_url+'helloworld /firstmoney',
You can try another way to do that
Try below code
form
<form action="" method="post" id="myform">
<input id="amount" type="text" placeholder="Give amount" name="myamount"/>
<button class="btn btn-lg" type="submit" id="btn1" >FirstBTN</button>
<button class="btn btn-lg" type="submit" id="btn2">SecondBTN</button>
</form>
Then you can add jquery to change the form action on submit button clicks
like below
<script type="text/javascript">
$('#btn1').click(function() {
$('#myform').attr('action', 'Your domain/Your controller/firstmoney');
});
$('#btn2').click(function() {
$('#myform').attr('action', 'Your domain/Your controller/secondmoney');
});
</script>
Now your form will call firstmoney() if you click #btn1 and it will call secondmoney() if you call #btn2
And you can get form data using
$this->input->post('myamount');
If you only want to print $_POST data then apply this code for btn1.
$(document).ready(function(){
$('#btn1').click(function() {
event.preventDefault();
$.ajax({
url: "<?php echo base_url(); ?>" + "helloworld/firstmoney",
type: 'POST',
data: {'submit' : true ,myamount: $("#amount").val()},
success: function (result) {
$("body").html(result);
}
});
});
});
In your helloworld controller
public function firstmoney(){
$Money = $this->input->post("myamount");
$data = array(
'Money' => $Money
);
$data = $this->load->view("page1", $data, TRUE); //it will return that page and save it in $data
}
In you page1.php view write the following code
<?php
echo $Money;
?>
<script type="text/javascript">
$('#btn1').click(function() {
$.ajax({
url: 'helloworld/firstmoney',
type: 'POST',
data: {'submit' : true ,myamount: $("#myamount").val()},
success: function (result) {
}
});
});
Keep the id and name value as myamount in above input tag and change in the jquery code also
Related
I am trying to submit data to the database using AJAX. I have one array and I have to pass the value of the array to PHP using AJAX to display all the related records.
<form id="search-form" method="POST">
<input value="4869" name="compare_id[]" type="hidden">
<input value="4884" name="compare_id[]" type="hidden">
<input value="5010" name="compare_id[]" type="hidden">
<input type="button" id="search-button" name="search-button" value="search">
</form>
<div id="response"></div>
AJAX
<script>
$(document).ready(function(){
$('#search-button').click(function(){
$.ajax( {
type: 'POST',
url: 'response.php',
data: $('#search-form').serialize(),
dataType: 'json',
success: function(response) {
$('#response').html(response);
//alert(response);
}
});
});
});
</script>
PHP
$sql='SELECT Name, Email FROM request WHERE Id IN (' .( is_array( $_POST['compare_id'] ) ? implode( ',', $_POST['compare_id']) : $_POST['compare_id'] ).')';
$records = array();
$query=$conn->query($sql);
if ($query->num_rows > 0) {
while($row=$query->fetch_assoc()){
$records[]=$row;
}
}
echo json_encode($records);exit();
HTML
<form id="search-form" method="POST">
<input value="4869" name="compare_id[]" type="hidden">
<input value="4884" name="compare_id[]" type="hidden">
<input value="5010" name="compare_id[]" type="hidden">
<input type="button" id="search-button" name="search-button" value="search">
</form>
<div id="response"></div>
JS
<script>
$(document).ready(function(){
$('#search-button').click(function(){
$.ajax( {
type: 'POST',
url: 'response.php',
data: $('#search-form').serialize(),
dataType: 'json',
success: function(response) {
$('#response').html(response);
}
});
});
});
</script>
PHP
var_dump($_POST['compare_id']);
// it is already an array of ids. You can do whatever you want with it.
change your script as below. Your output is in array so you cant add it in div directly
<script>
$(document).ready(function(){
$('#search-button').click(function(){
$.ajax( {
type: 'POST',
url: 'action.php',
data: $('#search-form').serialize(),
dataType: 'json',
success: function(response) {
$('#response').html();
for(data in response) //loop over your data
{
$('#response').append(response[data].Email); //add email
}
//alert(response);
}
});
});
});
</script>
There are errors in your code. A good way to debug this is to print_r your POST value in your php script.
First $_POST["All"] does not exist. It is all. (php)
Second, you send a GET request not a POST one. (jQuery)
Third, format your date into json. A good way to do this is to create a variable right after compare_id.push, it's more readable, as so :
var json_data = {"my_array" : [1,2, "bonjour", 4]};
Your problem is mostly related to "how to debug". I think you should print what's happening along the way to figure out what's happening.
As the title says, i have try many times to get it working, but without success... the alert window show always the entire source of html part.
Where am i wrong? Please, help me.
Thanks.
PHP:
<?php
if (isset($_POST['send'])) {
$file = $_POST['fblink'];
$contents = file_get_contents($file);
echo $_POST['fblink'];
exit;
}
?>
HTML:
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.8.3.min.js"></script>
<script>
$(document).ready(function() {
$("input#invia").click(function(e) {
if( !confirm('Are you sure?')) {
return false;
}
var fbvideo = $("#videolink").val();
$.ajax({
type: 'POST',
data: fbvideo ,
cache: false,
//dataType: "html",
success: function(test){
alert(test);
}
});
e.preventDefault();
});
});
</script>
</head>
<div style="position:relative; margin-top:2000px;">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input id="videolink" type="text" name="fblink" style="width:500px;">
<br>
<input id="invia" type="submit" name="send" value="Get Link!">
</form>
</div>
</html>
Your Problem is that you think, that your form fields are automatic send with ajax. But you must define each one into it.
Try this code:
<script>
$(document).ready(function() {
$("input#invia").click(function(e) {
if( !confirm('Are you sure?')) {
return false;
}
var fbvideo = $("#videolink").val();
$.ajax({
type: 'POST',
data: {
send: 1,
fblink: fbvideo
},
cache: false,
//dataType: "html",
success: function(test){
alert(test);
}
});
e.preventDefault();
});
});
</script>
Instead of define each input for itself, jQuery has the method .serialize(), with this method you can easily read all input of your form.
Look at the docs.
And maybe You use .submit() instead of click the submit button. Because the user have multiple ways the submit the form.
$("input#invia").closest('form').submit(function(e) {
You must specify the url to where you're going to send the data.
It can be manual or you can get the action attribute of your form tag.
If you need some additional as the send value, that's not as input in the form you can add it to the serialized form values with formSerializedValues += "&item" + value;' where formSerializedValues is already defined previously as formSerializedValues = <form>.serialize() (<form> is your current form).
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.8.3.min.js"></script>
<script>
$(document).ready(function() {
$("#invia").click(function(e) {
e.preventDefault();
if (!confirm('Are you sure?')) {
return false;
}
// Now you're getting the data in the form to send as object
let fbvideo = $("#videolink").parent().serialize();
// Better if you give it an id or a class to identify it
let formAction = $("#videolink").parent().attr('action');
// If you need any additional value that's not as input in the form
// fbvideo += '&item' + value;
$.ajax({
type: 'POST',
data: fbvideo ,
cache: false,
// dataType: "html",
// url optional in this case
// url: formAction,
success: function(test){
alert(test);
}
});
});
});
</script>
</head>
<body>
<div style="position:relative; margin-top:2000px;">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input id="videolink" type="text" name="fblink" style="width:500px;">
<br>
<input id="invia" type="submit" name="send" value="Get Link!">
</form>
</div>
</body>
<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've been at this for hours, and i'm at a complete loss.... I've tried everything I can but the problem is that i'm not very familiar with Jquery, this is the first time I've ever used it.... Basically, i'm attempting to pass form data to a php script, and then return a variable which will contain the source code of a webpage.
Here is the jquery:
$("button").click(function(){
hi = $("#domain").serialize();
var page;
$.ajax({
type: "POST",
url: "webcrawler.php",
data: hi,
//dataType: "text",
success: function(data){
page = data;
document.write(page);
}
});
});
Here is the html it references:
<div id="contact_form">
<form name="contact" action="">
<fieldset>
<label for="domain" id="domain_label">Name</label>
<input type="text" name="domain" id="domain" size="30" value="" class="text-input" />
<input type="submit" name="submit" class="button" id="submit_btn" value="Send" />
</fieldset>
</form>
</div>
Here is the PHP that process it:
$search = $_POST["domain"];
if(!$fp = fopen($search,"r" )) {
return false;
}
fopen($search,"r" );
$data = "";
while(!feof($fp)) {
$data .= fgets($fp, 1024);
}
fclose($fp);
return $data;
?>
I think the variable $search is blank, but is that because i'm not sending it correctly with jquery or receiving it correctly with php? Thanks!
Well, when you serialize form data using jQuery, you should serialize the <form>, not the <input> field.
So try this:
$("button").click(function() {
var formData = $('form[name="contact"]').serialize();
var page;
$.ajax({
type: "POST",
url: "webcrawler.php",
data: formData,
success: function(data) {
page = data;
document.write(page);
}
});
});
See you have to do several things:
$("form[id='contact_form']").submit(function (e) {//<---instead click submit form
e.preventDefault(); //<----------------you have to stop the submit for ajax
Data = $(this).serialize(); //<----------$(this) is form here to serialize
var page;
$.ajax({
type: "POST",
url: "webcrawler.php",
data: Data,
success: function (data) {
page = data;
document.write(page);
}
});
});
So as in comments:
Submit form instead button click
Stop the form submission otherwise page will get refreshed.
$(this).serialize() is serializing the form here because here $(this) is the form itself.
im trying to achieve the following, in php i have a form like this:
<form method="post" id="form_1" action="php.php">
<input type="submit" value="add" name="sub"/>
<input type="submit" value="envoi" name="sub"/>
</form>
the form action file is:
<?php
if( $_POST["sub"]=="add"){ ?>
<script>
alert("")
</script>
<?php echo "ZZZZZZ"; ?>
<?php } ?>
so this means if i press sub with value add an alert prompt will come up, how can i do the same thing(differentiate both submit) but using a Ajax request:
the following code so does not work:
$(function(){
$('form#form_1').submit(function(){
var _data= $(this).serialize()
$.ajax({
type: 'POST',
url: "php.php?",
data:_data,
success: function(html){
$('div#1').html(html)
}
})
})
})
</script>
</head>
<body>
<div id="1" style="width: 100px;height: 100px;border: 1px solid red"></div>
<form method="post" id="form_1" action="javascript:;">
<input type="submit" value="add" name="sub"/>
<input type="submit" value="envoi" name="sub"/>
</form>
</body>
You could put the event handler on the buttons instead of on the form. Get the parameters from the form, and then add a parameter for the button, and post the form. Make sure the handler returns "false".
$(function() {
$('input[name=sub]').click(function(){
var _data= $('#form_1').serialize() + '&sub=' + $(this).val();
$.ajax({
type: 'POST',
url: "php.php?",
data:_data,
success: function(html){
$('div#1').html(html);
}
});
return false;
});
});
You have to explicitly add the "sub" parameter because jQuery doesn't include those when you call "serialize()".
In this case you need to manually add the submit button to the posted data, like this:
$(function(){
$('form#form_1 :submit').submit(function(){
var _data = $(this).closest('form').serializeArray(); //serialize form
_data.push({ name : this.name, value: this.value }); //add this name/value
_data = $.param(_data); //convert to string
$.ajax({
type: 'POST',
url: "php.php?",
data: _data,
success: function(html){
$('div#1').html(html);
}
});
return false; //prevent default submit
});
});
We're using .serializeArray() to get a serialized version of the form (which is what .serialize() uses internally), adding our name/value pair to that array before it gets serialized to a string via $.param().
The last addition is a return false to prevent the default submit behavior which would leave the page.
Lots of semicolon missing, see below
$(function(){
$('form#form_1').submit(function(){
var _data= $(this).serialize();
$.ajax({
type: 'POST',
url: "php.php?",
data:_data,
success: function(html){
$('div#1').html(html);
}
});
});
});
jQuery Form plugin provide some advance functionalities and it has automated some tasks which we have to do manually, please have a look at it. Also it provides better way of handling form elements, serialization and you can plug pre processing functions before submitting the form.