Passing form data to controller using AJAX and jquery with Codeigniter - php

I am trying to post the data from this form into the database. I have tried some tutorials with no success. Here is my code. Any ideas?
View:
<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>
AJAX (in the view, right below the form)
<script type='text/javascript' language='javascript'>
$("#submitbutton").click(function(){
$.ajax({
url:'http://localhost:8888/index.php/trial/insert_into_db',
type: 'POST',
data: $("#myForm1").serialize(),
success: function(){
alert("success");
},
error: function(){
alert("Fail")
}
});
e.preventDefault();
});
</script>
Controller
function insert_into_db(){
$this->load->model('insert_db');
$this->insert_db->insertQ();
}
Model
class Insert_db extends CI_Model{
function insertQ(){
$email = $_POST['email'];
$qText = $_POST['qText'];
$this->db->query("INSERT INTO questions VALUES('','$email','$qText','','')");
}
}

As #David Knipe already said, you should wait for the DOM to be ready before trying to access one of its elements. Moreover, you likely have an e is undefined error, since you're not passing the event reference to the click handler:
<script> //no need to specify the language
$(function(){
$("#submitbutton").click(function(e){ // passing down the event
$.ajax({
url:'http://localhost:8888/index.php/trial/insert_into_db',
type: 'POST',
data: $("#myForm1").serialize(),
success: function(){
alert("success");
$('#email').val('');
$('#qText').val('');
},
error: function(){
alert("Fail")
}
});
e.preventDefault(); // could also use: return false;
});
});
</script>
To be more complete, your query is vulnerable, and you might be getting an error there. Make use of the advantage of having a framework beneath you:
function insertQ(){
$email = $this->input->post('email');
$qText = $this->input->post('qText');
$this->db->insert('questions', array('email' =>$email, 'text' => $text));
}
^_ I'm guessing the column names since you didn't specify them

Looks like you've forgotten to use $.ready. As it is, the javascript runs before the page has loaded, which means it can't find the page element from $("#submitbutton"). Try this:
$(document).ready(function() {
$("#submitbutton").click(function(){
....
....
});

Related

How to prevent page reload while bookmarking it?

I am making a book library site using laravel. I am trying to add bookmark functionality. I have tried doing something like that on click of bookmark button, page no is being send to database and it is working. Issue is that on return from controller page is getting reload causing book to back on page no 1. Is there is any way that data sends to database without page reload??
I know a bit that ajax do this, but I am using JavaScript in my application and I tried to deploy ajax with it but no luck.
I am showing up my code. Any good suggestions would be highly appreciated.
My javascript function:
function bookmark()
{
book = '<?php echo $book->id ?>';
$.ajax({
type: "post",
url: "save_bookmark",
data: {b_id:book, p_no:count},
success: function(response){
console.log(response);
},
error: function(error){
console.log(error);
}
});
});
}
count is defined up in script.
My route:
Route::post("save_bookmark/{b_id}/{p_no}",'BookmarkController#create')->name('save_bookmark');
My controller:
public function create($b_id, $p_no)
{
$b=new bookmark;
$b->u_id=Auth::user()->id;
$b->book_id=$b_id;
$b->p_no=$p_no;
$b->save();
return response()->json([
'status' => 'success']);
}
My html:
<li><a id="bookmark" onclick="bookmark()" >Bookmark</a></li>
Note: There is a navbar of which bookmark is a part. There is no form submission.
try this: use javascript to get the book id
$("#btnClick").change(function(e){
//console.log(e);
var book_id= e.target.value;
//$token = $("input[name='_token']").val();
//ajax
$.get('save_bookmark?book_id='+book_id, function(data){
//console.log(data);
})
});
//route
Route::get("/save_bookmark",'BookmarkController#create');
you need add event to function and add preventDefault
<button class="..." onclick="bookmark(event)">action</button>
in js:
function bookmark(e)
{
e.preventDefault();
book = '<?php echo $book->id ?>';
$.ajax({
type: "post",
url: "save_bookmark",
data: {b_id:book, p_no:count},
success: function(response){
console.log(response);
},
error: function(error){
console.log(error);
}
});
});
}
in controller you ned use it:
use Illuminate\Http\Request;
...
...
public function create(Request $request)
{
$b=new bookmark();
$b->u_id=Auth::user()->id;
$b->book_id=$request->get('b_id');
$b->p_no=$request->get('p_no');
$b->save();
return response()->json([
'status' => 'success']);
}
in route use it:
Route::post("save_bookmark/",'BookmarkController#create')->name('save_bookmark');
Well, assuming your bookmark() JavaScript function is being called on a form submit, I guess you only have to prevent the form to be submitted. So your HTML code would looks like this:
<form onsubmit="event.preventDefault(); bookmark();">
Obviously, if you're handling events in your script.js it would rather looks like this:
HTML
<form id="bookmark" method="POST">
<input type="number" hidden="hidden" name="bookmark-input" id="bookmark-input" value="{{ $book->id }}"/>
<input type="submit" value="Bookmark this page" />
</form>
JavaScript
function bookmark(book_id, count) {
$.ajax({
type: "post",
url: "save_bookmark",
data: {
b_id: book_id,
p_no: count
},
success: function (response) {
console.log(response);
},
error: function (error) {
console.log(error);
}
});
}
let form = document.getElementById('bookmark');
let count = 1;
console.log(form); //I check I got the right element
form.addEventListener('submit', function(event) {
console.log('Form is being submitted');
let book_id = document.getElementById("bookmark-input").value;
bookmark(book_id, count);
event.preventDefault();
});
Also I would recommend you to avoid as much as possible to insert PHP code inside your JavaScript code. It makes it hard to maintain, it does not make it clear to read neither... It can seems to be a good idea at first but it is not. You should always find a better alternative :)
For example you also have the data-* to pass data to an HTML tag via PHP (more about data-* attributes).

ajax post method in php

I am trying to send ajax post javascript variable to php. My code php will only be executed if I press submit in another form.
My code is in one index.php file.
The console shows that this value has been sent, but my php code does not want to pick it up and does not execute the query. Why?
<?php
if (isset($_POST['imie2'])) {
...
if(isset($_POST['item_id']) && !empty($_POST['item_id'])){
$value = $_POST['item_id'];
if ($polaczenie->query("INSERT INTO zamowienia VALUES ('$value')")) {
...
?>
<form method="post">
<input type="text" name="imie2">
...
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$(document).ready(function () {
var value = localStorage.getItem('sumalist');
console.log(value);
$.ajax({
url:"index.php",
method:"POST",
data:{
item_id: value,
},
success:function(response) {
console.log('ok'); // console shows ok
},
error:function(){
alert("error");
}
});
});
</script>
You said:
if (isset($_POST['imie2'])) {
but your data looks like this:
data:{
item_id: value,
},
There's no imie2 field so your test will always fail.

Insert data with jQuery

I am trying to make a form to insert data to database with jQuery, but there's no action happen and want to know where the problem is.
Here's the code I wrote, and I hope someone will help me find where the mistake is, and why there's no action on it.
index.html:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="insert.js"></script>
</head>
<body>
<form id="form-search" method="post" action="index.html">
<input name="gov" id="gov" type="text" class="textinput required" maxlength="80" required><br>
<input name="area" id="area" type="text" class="textinput required" maxlength="80" required><br>
<button id="submit" type="button">insert</button>
</form>
</body>
</html>
insert.js code
$(document).ready(function(e) {
$('#submit').click(function() {
var gov =$('#gov').val() ;
var area =$('#area').val() ;
$.ajex({
type :'post' ,
data :{gov:gov,area:area},
url :"insert.php",
success :function(result) {
alert(result);
}
})
});
});
insert.php code
<?php
$con = mysqli_connect('localhost','user','pass','db');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
if($_REQUEST['gov']) {
$gov=$_REQUEST['gov'];
$area=$_REQUEST['area'];
$q="inser into gov values ('','$gov','$area')";
$query=mysqli_query($con,$q);
if($query){
echo "data insert " ;
}
}
?>
Look at the Networks' tab using the Developer Tools. Check if there's something happening when you press the submit button. Check for a status code.
This script (with your html) will submit the data (with console logs to the browser) to 'insert.php'. Please read the comments for explanations. If it still doesn't work, the problem probably lies in your PHP code (I don't work with PHP). The ajax is sending the data to 'insert.php', which should be coded to accept the data variables and return a json response back to the ajax function in the script.
// Remove the 'e' from .ready and place in the 'click' function - this is the 'event'
$(document).ready(function () {
$('#submit').click(function (e) {
// Stops the form from being submitted 'normally' (to index.html)
e.preventDefault();
// Check console in your browser (this can be removed when it works)
console.log('submit clicked');
// Define the data to be submitted with the ajax form
var submitData = { gov: $('#gov').val(), area: $('#area').val() };
$.ajax({
// Make sure your path to insert.php is complete - check console in browser to see if there is an error
url: 'insert.php',
// Make sure 'insert.php' accepts 'post' transactions
type: 'POST',
// This could be changed (when it works) to - data: { gov: $('#gov').val(), area: $('#area').val() },
data: submitData,
// Make sure 'insert.php' returns a json result
dataType: 'json',
success: function (result) {
// This can be removed when it works
console.log('ajax success');
},
beforeSend: function () {
// This can be removed when it works
console.log('ajax beforeSend');
// This can be removed when it works - this lists out the data submitted with the form
$.each(submitData, function (index, value) {
console.log('index: ' + index + ' value: ' + value);
});
},
complete: function () {
// This can be removed when it works
console.log('ajax complete');
},
error: function () {
// This can be removed when it works
console.log('ajax error');
}
});
});
});

Posting a sub-form with jQuery

I'll start off by saying I'm new to jQuery but I am really enjoying it. I'm also new to stackoverflow and really loving it!!
The problem:
I've created a sub-form with jQuery so that a user may add, then select this information from a dropdown list if it is not already available. I'm unable to POST this data with .ajax(), so that the user can continue to fill out other information on the main form without having to start over.
Sub-Form:
$(function() {
$("#add").live('click', function(event) {
$(this).addClass("selected").parent().append('<div class="messagepop"><p id="close"><img src="img/close.png"></p></img><form id="addgroup" method="POST" action="add_group.php"><p><label for="group">New Group Description:</label><input type="text" size="30" name="grouping" id="grouping" /></p><p><label for="asset_type">Asset Type:</label><select name="asset" id="asset" ><option>Building</option><option>Equipment</option></select></p><p><input type="submit" value="Add Group" name="group_submit" class="group_submit"/></form><div id="result"></div></div>');
$(".messagepop").show()
$("#group").focus();
return false;
});
$("#close").live('click', function() {
$(".messagepop").hide();
$("#add").removeClass("selected");
return false;
});
});
And here is where I'm attempting to process it:
$(function () {
$('#addgroup').submit(function() {
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(responseText) {
$('#result').html(responseText);
}
});
return false;
});
});
I've even attempted to create a simple alert instead of processing the information and this also does not work. Instead the form sumbits and refreshes the page as normal. Can anyone help me understand what I am missing or doing wrong? Thank you!
New attempt:
$("#add").live('click', function(event) {
var form = $("<form>").html("<input type='submit' value='Submit'/>").submit(function(){
$.post("add_group.php", {grouping: "Building, asset: "STUFF"});
$(".newgroup").append(form);
return false;
});
Final code
$(function() {
var id = 1
$("#add").live('click', function(event){
if($(".addgroup,").length == 0){
$("#test").append('<div class="addgroup"><label for="newGroup">New Group:</label><input type="text" class="newgroup" id="' + ++id + '" /><input type="submit" value="Add Group" name="group_submit" class="group_submit"/></div>');
$("#add").attr("src","img/add_close.png");
}else{
$("#add").attr("src","img/add.png");
$(".addgroup").remove();}
return false;
});
});
$(function(){
$(".group_submit").live('click',function(event){
$.ajax({
type: "POST",
url: "add_group.php",
data: {new_group: $(".newgroup").val(), asset: $("#group option:selected").text()},
success: function(){}
});
$(".addgroup").remove();
$('#subgroup').load('group.php', {'asset': $("#group option:selected").text()});
return false;
});
});
If the form is submitting and refreshing as normal, the jquery isn't kicking in (the refresh means it's posting the form normally).
I for some reason (maybe others haven't) found that $(document).ready(function() { works much better than $(function() { ...
Also, the groups that you're adding should have a definitive id:
on #add click, count up a counter (form++) and add that to the id (#addGroup_+form) and then target that straight away in the function that added it:
$("#group").focus();
$("#addGroup_"+form).submit(function() {
try using .live()
$(function () {
$('#addgroup').live('submit',function() {
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(responseText) {
$('#result').html(responseText);
}
});
return false;
});
});
and make sure addgroup has no duplicate id... you may use it as class if it has to be duplicated...

Loading data from form using jquery to php file returns null

When ever I pass a value from a form using submit to a php file using load, $.get or post and try to receive data or load it in general as shown below, I just get ruturned a null or undefined value. Anyone know what im doing wrong ?
iNDEX.HTML
`
<script type = "text/javascript">
$(document).ready(function(){
$("#NewOrgForm").submit(function(){
var name = $("#companyname").val();
$(".content").load("NewEntry.php",{Name: name});
});
});
</script>
<form id="NewOrgForm">
<p> Name: <input type="text" id="companyname" value="" /> </p>
<p> <input type="submit" value="Submit New Entry" id="submit" /> </p>
</form>
NEWENTRY.PHP
<?php
$companyname = $_POST['Name'];
echo $companyname;
?>
`
From some of the comments you posted it looks to me like you are incorrectly collecting data from the form. Have you tried making an alert to see if the name variable is actually set? Also try using firebug or something to see the exact URL you're loading.
Perhaps try using a directly passed event reference to the function and fetch the fields from there instead of using an absolute selector. Might help.
Is there actually an element in your HTML that has the class "content"?
Try making use of the callback function so that you are aware that the load actually ran:
$('#result').load('ajax/test.html', function() {
alert('Load was performed.');
});
The above code is taken from the jquery site (http://api.jquery.com/load/)
UPDATE: The more I look at this, the more I think that you are probably better going w/.post (http://api.jquery.com/jQuery.post/)
UPDATE2: What happens if you try this:
$(document).ready(function(){
runOnLoad('content');
});
function runOnLoad(className){
var name="peter";
var ajaxData = {"Name": name};
var url="NewEntry.php";
var contentToReturn="";
$.ajax({
type: "POST",
url: url,
data: ajaxData,
datatype: "html",
success: function(html) {
contentToReturn="Success! It returned "+html+"<br>";
$('div.'+className).html(contentToReturn);
},
error: function(html) {
contentToReturn="Failure! It returned "+html+"<br>";
$('div.'+className).html(contentToReturn);
}
});
return;
}
If you're just doing a POST, it should look something like:
<script type = "text/javascript">
$(document).ready(function(){
$("#NewOrgForm").attr({
"method": "POST",
"action": "NewEntry.php"
}).submit();
});
</script>
although why even use jquery for this, then...just set method and action attribs on your form element...

Categories