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;
});
});
Related
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);
}
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>
I have a form in a modal window. When I submit the form through ajax I don't get the success message. My aim is to see the message created in the php file in the modal after submitting the form. Here is the code:
<p><a class='activate_modal' name='modal_window' href='#'>Sign Up</a></p>
<div id='mask' class='close_modal'></div>
<div id='modal_window' class='modal_window'>
<form name="field" method="post" id="form">
<label for="username">Username:</label><br>
<input name="username" id="username" type="text"/><span id="gif"><span>
<span id="user_error"></span><br><br>
<label for="email">Email:</label><br>
<input name="email" id="email" type="text"/><span id="gif3"></span>
<span id="email_error"></span><br><br>
<input name="submit" type="submit" value="Register" id="submit"/>
</form>
</div>
The modal.js
$('.activate_modal').click(function(){
var modal_id = $(this).attr('name');
show_modal(modal_id);
});
$('.close_modal').click(function(){
close_modal();
});
$(document).keydown(function(e){
if (e.keyCode == 27){
close_modal();
}
});
function close_modal(){
$('#mask').fadeOut(500);
$('.modal_window').fadeOut(500);
}
function show_modal(modal_id){
$('#mask').css({ 'display' : 'block', opacity : 0});
$('#mask').fadeTo(500,0.7);
$('#'+modal_id).fadeIn(500);
}
The test.js for the registration of the user
$(function() {
$('#form').submit(function() {
$.ajax({
type: "POST",
url: "test.php",
data: $("#form").serialize(),
success: function(data) {
$('#form').replaceWith(data);
}
});
});
});
And the PHP FILE
<?php
$mysqli = new mysqli('127.0.0.1', 'root', '', 'project');
$username = $_POST['username'];
$email = $_POST['email'];
$mysqli->query("INSERT INTO `project`.`registration` (`username`,`email`) VALUES ('$username','$email')");
$result = $mysqli->affected_rows;
if($result > 0) {
echo 'Welcome';
} else {
echo 'ERROR!';
}
?>
Try putting the returncode from your AJAX call into
$('#modal_window')
instead of in the form
$('#form')
BTW: Why not use the POST or GET method of jQuery? They're incredibly easy to use...
Try something like this.
First write ajax code using jquery.
<script type="text/javascript">
function submitForm()
{
var str = jQuery( "form" ).serialize();
jQuery.ajax({
type: "POST",
url: '<?php echo BaseUrl()."myurl/"; ?>',
data: str,
format: "json",
success: function(data) {
var obj = JSON.parse(data);
if( obj[0] === 'error')
{
jQuery("#error").html(obj[1]);
}else{
jQuery("#success").html(obj[1]);
setTimeout(function () {
jQuery.fancybox.close();
}, 2500);
}
}
});
}
</script>
while in php write code for error and success messages like this :
if(//condition true){
echo json_encode(array("success"," successfully Done.."));
}else{
echo json_encode(array("error","Some error.."));
}
Hopes this help you.
I am warking in phalcon framework, and i am trying to call controller's method to get simple string using jquery-ajax. When i placed my ajax call inside $(document).ready(function() ajax call worked, but when i placed same code inside $('#dugme').click(function() ajax call reported error. I am confused. Here is my view code:
<script type="text/javascript">
$(document).ready(function(){
//alert($("#nesto").val());
//atr = $(".klasa").attr("id");
//alert("Id je: " + atr)
$.ajax({
url: '<?php echo $this->url->get("xml/posalji");?>',
type: 'POST',
dataType: 'json',
success: function(data){
alert(data);
},
error: function(){
alert("Neuspjesan JSON zahtjev!");
}
});
$('#dugme').click(function(){
$.ajax({
url: '<?php echo $this->url->get("xml/posalji");?>',
type: 'POST',
dataType: 'json',
success: function(data){
alert(data);
},
error: function(){
alert("Neuspjesan JSON zahtjev!");
}
});
}) ;
});
</script>
<h2>Basic example</h2>
<?php echo Tag::form("xml/pretraga"); ?>
<p>
<label for="name">Title</label>
<?php $opt = array('title', 'id'=>'nesto', 'size'=>'10');
$buttopt = array('Show', 'id'=>'dugme','class'=>'klasa');
?>
<?php echo Tag::textField($opt) ?>
</p>
<p>
<?php echo Tag::SubmitButton($buttopt) ?>
</p>
</form>
and here is my action code:
public function posaljiAction(){
$this->view->disable();
$data = "My name is Nedimo";
echo json_encode($data);
}
Please, can anyone tell me what is wrong in my code.
I have a form that will insert into table 'tags' using ajax. I was able to add manually but not without reloading the page.
This is my controller Controller (tags.php)
class Tags extends CI_Controller{
function __construct(){
parent:: __construct();
$this->load->model('tags_model');
$this->load->helper('form');
$this->load->helper('url');
}
function index(){
$data['tags']=$this->tags_model->get();
$this->load->view('tags/index',$data);
}
function add()
{
$this->tags_model->save();
return true;
}
}
?>
This is my view('index.php')
<script src="<?php echo base_url('assets/js/jquery.js');?>"></script>
<?php
foreach ($tags as $t){
echo '<span>';
echo $t['id'].':';
echo $t['title'];
echo '-';
echo '</span>';
}
?>
<form id="comment" method="post">
<?php echo form_input('title','text is here....');?>
<label> </label><input type="submit" value="Submit" />
</form>
<!-- here is the script that will do the ajax. It is triggered when the form is submitted -->
<script>
$(function(){
$("#comment").submit(function(){
dataString = $("#comment").serialize();
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>tags/add",
data: dataString,
return false; //stop the actual form post !important!
success: function(data)
{
alert('Successful!');
}
});
return false; //stop the actual form post !important!
});
});
</script>
Model
<?php
class Tags_model extends CI_Model{
function __construct()
{
parent:: __construct();
$this->load->database();
}
function save()
{
$title=$this->input->post('title');
$data=array(
'title'=>$title
);
$this->db->insert('tags',$data);
}
function get(){
$query=$this->db->get('tags');
return $query->result_array();
}
}
?>
code seem to be okay to me. I can insert normally but not in ajax . Any help is welcome.
Remove the return false that is inside your jquery ajax call.
$(function(){
$("#comment").submit(function(){
dataString = $("#comment").serialize();
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>tags/add",
data: dataString
success: function(data)
{
alert('Successful!');
}
});
return false; //stop the actual form post !important!
});
});
I did like in this tutorials and now workings
http://net.tutsplus.com/tutorials/php/codeigniter-from-scratch-day-8-ajax/
now my view is like that
<script src="<?php echo base_url('assets/js/jquery.js');?>"></script>
<?php
foreach ($tags as $t){
echo '<span>';
echo $t['id'].':';
echo $t['title'];
echo '-';
echo '</span>';
}
?>
<?php echo form_open('tags/add');?>
<?php echo form_input('title','text is here....','id="title"');?>
<?php echo form_submit('submit', 'Submit', 'id="submit"'); ?>
<?php echo form_close();?>
<!-- here is the script that will do the ajax. It is triggered when the form is submitted -->
<script type="text/javascript">
$('#submit').click(function() {
//var title = $('#title').val();
var form_data = {
title: $('#title').val(),
ajax: '1'
};
$.ajax({
url: "<?php echo site_url('tags/add'); ?>",
type: 'POST',
data: form_data,
success: function() {
alert('added Successfully');
}
});
return false;
});
</script>
instead of
url: "<?php echo base_url('tags/add'); ?>",
I also had to switch to
url: "<?php echo site_url('tags/add'); ?>",
Controller
public function added()
{
$data['name']=$this->input->post('name');
$data['address']=$this->input->post('address');
$re=$this->model->add('aa',$data);
if($re)
{
?>
<script> alert("inserted");</script>
<?php
}
else
{
?>
<script> alert("not insert");</script>
<?php
}
//redirect('Myconn/insert');
}
JS Code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function (e) {
$("#form1").on('submit',(function(e) {
var name = $("#name").val();
var address = $("#address").val();
e.preventDefault();
// document.getElementById("submit").value="Sending.....";
$.ajax({
url: "<?php echo base_url(); ?>Myconn/added",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(html)
{
$("#feed_m").after(html);
//document.getElementById("submit").value="submit.";
document.getElementById('name').value='';
document.getElementById('address').value='';
}
});
}));
});
</script>
HTML Code
<div id="feed_m"></div>
<form method="post" id="form1" action="">
<table >
<tr>
<td>name</td>
<td><input type="text" id="name" name="name"></td>
</tr>
<tr>
<td>address</td>
<td><input type="text" id="address" name="address"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" id="submit" name="submit" value="submit"></td>
</tr>
</table>
</form>
Controller
public function added()
{
$data['name']=$this->input->post('name');
$data['address']=$this->input->post('address');
$re=$this->model->add('aa',$data);
if($re)
{
?>
<script> alert("inserted");</script>
<?php
}
else
{
?>
<script> alert("not insert");</script>
<?php
}
}
Model
public function add($table,$data)
{
return $this->db->insert($table,$data);
}