I am submitting this form using ajax and i want all form post data in controller to submit form in database.But its not working.
$('#myForm').on('submit', function(e){
$.ajax({
url : controllerUrl,
type : 'POST',
data : $(this).serialize(),
success : function(data) {
}
});
});
Hope it helps you :
use site_url or base_url instead of controllerUrl
Note : replace controller_name and method_name with your controller and method
$('#myForm').on('submit', function(e){
$.ajax({
url : "<?php echo site_url('controller_name/method_name');?>",
type : 'POST',
data : $(this).serialize(),
success : function(data) {
alert(data);
}
});
});
Your controller structure should be like this :
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Controller_name extends CI_Controller {
public function __construtct()
{
parent::__construtct();
$this->load->helper('url');
}
public function method_name()
{
print_r($this->input->post());
die;
}
}
Better try to give it a name for the value you are passing to the next page
$('#myForm').on('submit', function(e){
$.ajax({
url : controllerurl,
type : 'POST',
data : {values:$(this).serialize()},
success : function(data) {
alert(data);
}
});
});
var your_data = "your data";
var url = "<?php echo base_url('my_controller/my_method') ?>";
$.post( url, { data: your_data}, function(response) {
alert(response);
});
for my_controller
public function my_method() {
$data = $this->input->post('data');
echo 'Found: ' . $data;
}
Suppose this is your form
<form name="form1" id="form1">
<input type="text" name="t1">
<input type="text" name="t2">
<input type="submit" name="sbtn" id="sbtn">
</form>
Put this in your footer
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
var BASE_URL ="<?= base_url(); ?>";
$( "#form1" ).submit(function( event ) {
event.preventDefault();
$.ajax({
type: 'POST',
url: BASE_URL + "controller/methodName",
data: =$("#form1").serialize(),
success: function (data) {
data = JSON.parse(data);
}
});
});
</script>
And finally put this in your controller
function methodName()
{
echo $t1=$this->input->post('t1');
echo $t2=$this->input->post('t2');
}
Suppose this is your form
html
<form name="form" id="form1">
<input type="text" name="name">
<input type="text" name="email">
<a class="adddata">send</a>
</form>
AddCategories is controller name and addProductsCategories is method
name.
js
$(".adddata").on('click',function(){
var addCat= new FormData($("#form1")[0]);
$.ajax({
url : baseurl+"AddCategories/addProductsCategories",
type :"POST",
data :addCat,
contentType:false,
processData:false,
success:function(res)
{
alert("Good job!");
window.location.reload();
}
});
});
controller
public function addProductsCategories()
{
$result=array
(
"name"=>$_POST["name"],
"email"=>$_POST["email"],
);
$this->db->insert("tbl_name",$result);
}
Related
I'm new to Yii and would appreciate any help.
I render the view with form:
public function actionCreate()
{
return $this->render('create');
}
view:
<form id="myform" action="/test/web/index.php?r=form/preorder" method="post">
<input type="text" id="form-firstname" name="Form[firstName]" required maxlength="50">
<input type="text" id="form-lastname" name="Form[lastName]" required maxlength="50">
<input name="send" type="submit" value="Отправить">
</form>
Im using plain html instead of Yii extensions in form, because I need to have a frontend with html/javascript only. On backend I can use Yii.
Now, I try to submit the form using ajax:
$(document).ready(function(){
$("body").on('beforeSubmit', 'form#myform', function(e){
var form = $(this);
$.ajax({
url : form.attr('action'),
type : 'POST',
data : form.serialize(),
success: function (response)
{
console.log(response);
},
error : function ()
{
console.log('internal server error');
}
});
return false;
});
});
FormController:
public function actionPreorder(){
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = Response::FORMAT_JSON;
$res = array(
'body' => $_POST,
'success' => true,
);
//also I need to save to db
return $res;
}
}
The problem is when I submit the form, it redirects to the new page preorder, and I can't see my posted data. Im not sure what Im doing wrong.
Ok, so the solution is to remove action from form:
<form id="myform" action="" method="post">
js:
$("#myform").submit( function(e){
var form = $(this);
$.ajax({
url : '/megogo/web/index.php?r=form/preorder',
type : 'POST',
data : form.serialize(),
success: function (response)
{
console.log(response);
},
error : function (e)
{
console.log(e);
}
});
return false;
})
Been looking at some tutorials, since I'm not quite sure how this works (which is the reason to why I'm here: my script is not working as it should). Anyway, what I'm trying to do is to insert data into my database using a PHP file called shoutboxform.php BUT since I plan to use it as some sort of a chat/shoutbox, I don't want it to reload the page when it submits the form.
jQuery:
$(document).ready(function() {
$(document).on('submit', 'form#shoutboxform', function () {
$.ajax({
type: 'POST',
url: 'shoutboxform.php',
data: form.serialize(),
dataType:'html',
success: function(data) {alert('yes');},
error: function(data) {
alert('no');
}
});
return false;
});
});
PHP:
<?php
require_once("core/global.php");
if(isset($_POST["subsbox"])) {
$sboxmsg = $kunaiDB->real_escape_string($_POST["shtbox_msg"]);
if(!empty($sboxmsg)) {
$addmsg = $kunaiDB->query("INSERT INTO kunai_shoutbox (poster, message, date) VALUES('".$_SESSION['username']."', '".$sboxmsg."'. '".date('Y-m-d H:i:s')."')");
}
}
And HTML:
<form method="post" id="shoutboxform" action="">
<input type="text" class="as-input" style="width: 100%;margin-bottom:-10px;" id="shbox_field" name="shtbox_msg" placeholder="Insert a message here..." maxlength="155">
<input type="submit" name="subsbox" id="shbox_button" value="Post">
</form>
When I submit anything, it just reloads the page and nothing is added to the database.
Prevent the default submit behavior
$(document).on('submit', 'form#shoutboxform', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'shoutboxform.php',
data: $(this).serialize(),
dataType: 'html',
success: function(data) {
alert('yes');
},
error: function(data) {
alert('no');
}
});
return false;
});
Use the following structure:
$('form#shoutboxform').on('submit', function(e) {
e.preventDefault();
// your ajax
}
Or https://api.jquery.com/submit/ :
$("form#shoutboxform").submit(function(e) {
e.preventDefault();
// your ajax
});
I am trying to submit a form using ajax post.Before that i am checking that all the form data are correct, if so the form will be submitted.Can any body tell me why the form is not submitting ?
HTML:
<form id="formElem" name="formElem" action="" method="post">
<fieldset class="step">
<legend>Account</legend>
<p>
<label for="password">Password</label>
<input type="password" name="uPassword" id="uPassword" value="<?=$uPassword;?>" AUTOCOMPLETE=OFF />
</p>
<p>
<label for="password">Verify Password</label>
<input type="password" name="uVPassword" id="uVPassword" value="<?=$uVPassword;?>" />
</p>
<p class="submit">
<button id="registerButton" type="submit">Register</button>
</p>
</fieldset>
</form>
jQuery code :
$('#registerButton').bind('click', function () {
if ($('#formElem').data('errors')) {
alert('Please correct the errors in the Form');
return false;
} else {
$(function () {
$("#formElem").on("submit", function (event) {
event.preventDefault();
$.ajax({
url: "somefile.php",
type: "post",
data: $(this).serialize(),
success: function (d) {
alert(d);
}
});
});
}); ///end of func
return true;
}
});
Why do you have event.preventDefault(); in the beginning of your submit function? It seems that that's the problem.
You don't need the click handler, in the submit handler you can check for the validity
jQuery(function ($) {
$("#formElem").on("submit", function (event) {
event.preventDefault();
if ($(this).data('errors')) {
return;
}
$.ajax({
url: "somefile.php",
type: "post",
data: $(this).serialize(),
success: function (d) {
alert(d);
}
});
});
})
You can call ajax on click of button. For any error it will go in to the if condition otherwise submit the form successfully..
$('#registerButton').bind('click', function () {
if ($('#formElem').data('errors')) {
alert('Please correct the errors in the Form');
return false;
}
$.ajax({
url: "somefile.php",
type: "post",
data: $(this).serialize(),
success: function (d) {
alert(d);
}
});
return true;
}); ///end of func
$(function() { /*code here */ }); That execute the function when the DOM is ready to be used. This means that this function is assigned to the event onDocumentReady that occurs only once (when the page loads), and you assign a function after this event, so never execute.
It's the same with this function $("#formElem").on("submit", function (event) {}); Do not tell her immediately but do you create a handle to the event onSubbmit.
here is my view
<html>
<body>
<form method="post" name="myForm1" id="myForm1" enctype="multipart/form-data" >
Email: <input type="text" name="email" id="email">
Question: <input type="text" name="qText" id="qText">
<input id="submitbutton" type="submit">
</form>
<div id="abc"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script> //no need to specify the language
$(document).ready(function() {
$('#myForm1').on("submit",function(e) {
//var form = $(this);
//dataString = $("#myForm1").serialize();
e.preventDefault();
$.ajax({
type: "POST",
url: "<?php echo site_url('form_controller/insert_into_db'); ?>",
data: $(this).serialize(),
//dataType: "json",
success: function(data){
// top.location.href = "<?php echo site_url('form_controller/callform'); ?>";
//$.each(data.results, function(){
// $("#abc").append('<div><b>' + id.id + '</b></div><hr />');
//});
/*var site_url = "<?php// echo site_url('form_controller/callform/') ?>";
site_url = site_url +"/" + id;
$("#abc").load(site_url);*/
<?php //foreach(): ?>
var site_url = "<?php echo site_url('form_controller/callform'); ?>";
var mydata=window.JSON.stringify(data.trim());
alert(mydata);
//site_url = site_url +"/" +data.id;
alert(site_url);
$("#abc").load(site_url);
//$('#abc').html(data);
var item = data;
alert(item.id);
}//,
//error: function() { alert("Error posting feed."); }
});
});
});
</script>
</body>
</html>
controller
function index(){
$this->load->view('submit_form');
}
function callform($id){
$this->load->view('view_form',$id);
}
public function insert_into_db(){
$this->load->helper('url');
$this->load->model('form_model');
$data= $this->form_model->insertQ();
$this->output->set_output(json_encode($data));
}
}
model
<?php
class Form_model extends CI_Model{
function insertQ(){
$email = $this->input->post('email');
$text = $this->input->post('qText');
$this->db->query("insert into form (email,text) values('$email','$text')");
$this->load->database();
$query = $this->db->query("SELECT MAX(id) AS id FROM form");
return $query->result();
}
}
when insert record into database there is a auto increment id. I need to get that particular id
from database and return it to the success function in ajax. then I need to load another page
into a div and print that id on newly loaded content.here the problem is
in view I couldn't get data into variable.for site_url
You can get the inserted id
$id = $this->db->insert_id();
I'm having trouble getting ajax to work with jquery and codeigniter. I've followed multiple tutorials but nothing seems to work. I'm trying to implement an upvote button that sends post data using ajax to be inserted into a db. Any help is much appreciated.
The code from my view:
<pre>
<?php foreach($query->result() as $row): ?>
<div>
<form action="" method="post">
<input type="hidden" name="story_id" value=<?php echo $row->id; ?>>
<input type="submit" name="story_id" class="button" id="submit_btn" value=<?php echo $row->id;?>>
</form>
</div>
<?php endforeach; ?>
</pre>
The jquery script I'm using:
<pre>
<script type="text/javascript">
$(document).ready(function(){
$(".button").click(function(){
var form_data = {
story_id: $(this).val()
};
$.ajax({
url: "<?php echo base_url('cyoa/upvote'); ?>",
type: 'POST',
data: form_data,
success: function()
{
$("#upvote").hide();
}
});
return false;
});
});
</script>
</pre>
Best way is to serialize your form data and send that to the server:
<script type="text/javascript">
$(document).ready(function(){
$(".button").click(function(){
var form_data = $("#myform").serialize();
$.ajax({
url: "<?php echo base_url('cyoa/upvote'); ?>",
type: 'POST',
data: form_data,
success: function()
{
$("#upvote").hide();
}
});
return false;
});
});
</script>
To access the form, give it a id:
<form id="myform" action="" method="post">
I strongly suggest to look at this plugin (and use it) :
JQuery Form Plugin
You can use form serialization to pass on data to php as below
First Give ID "storyform" to your form tag
$.ajax({
url: "<?php echo base_url('cyoa/upvote'); ?>",
type: 'POST',
data: $("#storyform").serialize(),
success: function()
{
$("#upvote").hide();
}
});
try using json objects,
view....
<pre>
<?php foreach($query->result() as $row): ?>
<div>
<form action=" controller_name/upvote" method="post">
<input type="hidden" name="story_id" id = "story_id" value=<?php echo $row->id; ?>>
<input type="submit" name="story_id" class="button" id="submit_btn" value=<?php echo $row->id;?>>
</form>
</div>
<?php endforeach; ?>
</pre>
Then your controller,
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Controller_name extends CI_Controller {
function __construct()
{
parent::__construct();
//loading libraries
$this->load->helper(array('form','url'));
$this->load->library('form_validation');
}
//##############################################################################
function upvote(){
//setting validation rules
$this->form_validation->set_rules('story_id', 'story Id', 'required|xss_clean');
if ($this->form_validation->run() == true){
//if validations ok, send the data to database
$this->load->model('your_model');
$params = ($this->input->post('story_id');
$query = 'INSERT INTO table_name (story_id) VALUES(?)';
$result = $this->your_model_name->method_name($query,$params);
echo '{"validation_result": "passed"}';
}
else{
$output = '{"story_id":"'.form_error('story_id').'"}';
echo $output;
}
}
}
?>
Then Your java script file
$(document).ready(function(){
$('#submit_btn').live('click',function(){
var form_data = {
$story_id: $('#story_id').val()
};
$.ajax({
type: "POST",
url: baseurl+"controller_name/upvote",
dataType: "json",
data : form_data,
success:
function(data){
if(data.validation_result == "passed"){
$("#upvote").hide();
}
else{
//form_validation errors
}
}
});
return false;
});
});