I want to update record in the database with ajax without reloading the page.
//Here is my controller.
Public function changeid()
{
$this->view->('admin/change_id');
}
Public function ajax_changeid()
{
$old_id =$_POST[studentid];
$newid =$_POST[new_id];
If(isset($_POST[`new_id')){
$data =array(
'student_id'=>trim($newid));
$this->db->where('student_id', $old_id);
$this->db->update('student');
echo "info submited";
}
echo json_encode($data);
}
My view form change_id
<form id='formajax' method='post' name='form'>
<input type="text" id="studentid"
name="studentid" readonly="readonly"
value="<? php echo $row- >student_id; ?>" />
<input type="text" name="new_id" id="new_id" >
<input type="submit" id="btnsubmit"
value="Update" class="button success"
onclick="myFunction()" />
<\form>
// Ajax script
<script>
//ajaxForm({
//function myFunction(){
(document).ready(function(){
$("#btnsubmit").click(function(event){
event.preventDefault();
var stud_id =
document.getElementById("new_id").value;
var studentid =
document.getElementById("studentid").value;
var dataString = 'new_id1=' + new_id +
'$studentid1=' + studentid;
$.ajax({
type:"POST",
url:"<?php echo base_url()?
>"+"index.php/school_settings/ajax_changeid",
data:dataString,
cache:false,
success:function(html){
//alert(html);
alert('im working');
}
});
return false;
});
});
</script>
The challenge is the page keep reloading every time.
i click submit button without doing anything.
i want to be able to change id and get a success
message displayed without reloading d page.
You have some issues in your code, use this modified code:
Controller:
public function changeid()
{
$this->load->view('admin/change_id');
}
public function ajax_changeid()
{
$old_id = $_POST['studentid'];
$newid =$_POST['new_id'];
if(isset($_POST['new_id']))
{
$data =array(
'student_id'=>trim($newid));
$this->db->where('student_id', $old_id);
$this->db->update('student');
echo "info submited";
}
echo json_encode($data);
}
View:
<form id='formajax' method='post' name='form'>
<input type="text" id="studentid" name="studentid" readonly="readonly" value="<?php echo $row->student_id;?>"/>
<input type="text" name="new_id" id="new_id">
<input type="submit" id="btnsubmit" value="Update" class="button success" onclick="myFunction()"/>
</form>
What i have changed?
Change load view function as $this->load->view('admin/change_id'); instead of $this->view->('admin/change_id');
Change isset chekcing isset($_POST[`new_id') as isset($_POST['new_id']), you have missed the ending ] bracket and also using backticks (Dont know why)
Correct form ending tag <\form> as </form>
Remove onclick="myFunction()" event from button, because you are using button id for onclick event in ajax.
Related
I have a php function:
<?php
function send_message($userid, $projectid, $message) {
//some code
}
$userid = '1';
$projectid = '2';
$message = 'hello';
?>
<form id="myform" method="post" action="">
<textarea name="message" id="project-message"></textarea>
<input type="submit" name="send" value="send message">
</form>
I want the submit button to do jQuery Ajax so my page won't refresh:
js:
$('#myform').on('submit',function(e) {
e.preventDefault();
$.ajax({
url: //my valid url,
type: 'post',
dataType : 'json',
data: {
action: 'send_message', //this is the PHP function
projectid: projectid //how do I write this?,
userid: userid //how do I write this?,
message: message//how do I write this?'
},
})
.done(function(data) { console.dir(data);; })
.fail(function(jqXHR) { alert('You are fail. ' + jqXHR); });
});
On my error.log, I get NULL for the 3 parameters because I'm not sure how to access them from my PHP. How do you access the PHP variables from jQuery?
Put your PHP variables into hidden inputs so they'll be automatically sent when it is submitted.
For example : <input type="hidden" name="userid" value="1">
Serialize the form data : var formData = $(form).serialize();
On submit attach your form data :
$.ajax({
url: admin_ajax.ajax_url,
type: 'POST',
data: formData
})
Access it from PHP with a classic way : $_POST['userid']
<form id="insert_form">
<textarea name="message" id="project-message"></textarea>
<input type="submit" name="send" id="send" value="send message">
<input type="hidden" name="userid" id="userid" value="<?php echo $userid= '1'; ?>">
<input type="hidden" name="projectid" id="projectid" value="<?php echo $projectid='2'; ?>">
<input type="hidden" name="message" id="message" value="<?php echo $message=
'hello'; ?>">
</form>
var project-message=document.getElementById('project-message').value;
var send=document.getElementById('send').value;
var userid=document.getElementById('userid').value;
var projectid=document.getElementById('projectid').value;
var message=document.getElementById('message').value;
$.ajax({
url:"your_url.php",
type:"POST",
data:$('#insert_form').serialize(),
success:function(data)
{
}
})
You can get all the values of the form, and submit it.
Also you can set other the values in the form as hidden.
<form id="myform" method="post" action="" id='form1'>
<textarea name="projectMessage" id="project-message"></textarea>
<input type="submit" name="send" value="send message">
<?php print "<input type='hidden' value='$userid' > "; name='userid' ?>
<?php print "<input type='hidden' value='$projectid' > "; name='projectid' ?>
<?php print "<input type='hidden' value='$message' > "; name='message' ?>
</form>
$('#myform').on('submit',function(e) {
e.preventDefault();
$.ajax({
url: admin_ajax.ajax_url,
type: 'post',
dataType:'json',
data: $("#form1").serialize(),
})
.done(function(data) { console.dir(data);; })
.fail(function(jqXHR) { alert('You are fail. ' + jqXHR); });
});
I like this approach because I can reuse the ajax multiple times or even create a generic function to submit the form on the background with ajax. Also I can fill the form using a for each loop in php, having all the values in an array (like a database result)
ex.
<?php
foreach($values as $k=>$v}{
print "<input name='$key' value='$v'>\n";
}
?>
I have a page with a POST form, when I submit the form the details are updated in a database.
And I have another page where I use AJAX TAB, which means I load the first page with AJAX, when I do this and use the Form, the details are not updated in the database.
I would appreciate help.
<?php
if( isset($_POST['newcst']) )
{
/*client add*/
//getting post from user add form
$c_name = $_POST['c_name'];
$c_adress = $_POST['c_adress'];
$c_idnum = $_POST['c_idnum'];
$c_phone = $_POST['c_phone'];
$c_mail = $_POST['c_mail'];
echo $c_num;
//insert client into SQL
$wpdb->insert('se_clients',array(
'c_name' => $c_name,
'c_adress' => $c_adress,
'user_id'=>$cur_id,
'c_num'=>$c_idnum,
'c_phone'=>$c_phone,
'c_mail'=>$c_mail,
));
}
?>
<html>
</head>
<body>
<div id="newcst">
<form action="" method="post">
<label>Full name:</label>
<input type='text' name='c_name' /><br><br>
<label>ID: </label>
<input type='text' name='c_idnum' /><br><br>
<label>PHONE:</label>
<input type='text' name='c_phone' /><br><br>
<label>ADRESS: </label>
<input type='text' name='c_adress' /><br><br>
<label>EMAIL: </label>
<input type='text' name='c_mail' /><br><br>
<input name="newcst" type="submit" value="create">
</form>
</div>
</body>
</html>
Ajax tab:
$(document).ready(function() {
$("#nav li a").click(function() {
$("#ajax-content").empty().append("<div id='loading'><img src='http://wigot.net/project/wp-content/themes/projthem/vendor/images/loader.gif' alt='Loading' /></div>");
$("#nav li a").removeClass('current');
$(this).addClass('current');
$.ajax({ url: this.href, success: function(html) {
$("#ajax-content").empty().append(html);
}
});
return false;
});
$("#ajax-content").empty().append("<div id='loading'><img src='http://wigot.net/project/wp-content/themes/projthem/vendor/images/loader.gif' alt='Loading' /></div>");
$.ajax({ url: 'invoice', success: function(html) {
$("#ajax-content").empty().append(html);
}
});
});
hover(), click(), bind(), on() and others works only after reloading page.
So you can use live()
or
$(document).on('click', 'element', function () {
...
});
I found the solution, you need to add the PHP code that is responsible for entering data to the database on the main page that contains the AJAX and not the page with the form itself.
I have an admin panel where I have an option to add a user into database. I made a script so when you click the Add User link it will load the form where you can introduce the user infos. The thing is, I want to load in the same page the code that is run when the form is submited.
Here's the js function that loads the file:
$( ".add" ).on( "click", function() {
$(".add-user-content").load("add-user-form.php")
});
and here's the php form
<form id="formID" action="add-user-form.php" method="post">
<p>Add Blog Administrator:</p>
<input type="text" name="admin-user" value="" placeholder="username" id="username"><br>
<input type="password" name="admin-pass" value="" placeholder="password" id="password"><br>
<input type="email" name="admin-email" value="" placeholder="email" id="email"><br>
<input type="submit" name="add-user" value="Add User">
</form>
<?php
include '../config.php';
$tbl_name="blog_members"; // Table name
if(isset($_POST['add-user'])){
$adminuser = $_POST['admin-user'];
$adminpass = $_POST['admin-pass'];
$adminemail = $_POST['admin-email'];
$sql="INSERT INTO $tbl_name (username,password,email) VALUES('$adminuser','$adminpass','$adminemail')";
$result=mysqli_query($link,$sql);
if($result){
echo '<p class="user-added">User has been added successfully!</p>';
echo '<a class="view-users" href="view-users.php">View Users</a>';
}else {
echo "Error: ".$sql."<br>".mysqli_error($link);
}
}
?>
Maybe I was not that clear, I want this code
if($result){
echo '<p class="user-added">User has been added successfully!</p>';
echo '<a class="view-users" href="view-users.php">View Users</a>';
}else {
echo "Error: ".$sql."<br>".mysqli_error($link);
}
to be outputted in the same page where I loaded the form because right now it takes me to the add-user-form.php when I click the submit button.
Thanks for your help!
if you do this the code will be redirected on post to your page:
<form name="formID" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" >
you should add a validation so it doest show the form if you receive $_POST['add-user']
You have to submit your for via ajax.
Alternatively you don't need to load form html, just hide the form and on add user button click show the form.
Check this code. Hope that helps you :-
// Add User Button
<div class="color-quantity not-selected-inputs">
<button class="add_user">Add User</button>
</div>
// Append form here
<div class="add_user_form"></div>
// for posting response here
<div class="result"></div>
Script for processing form and appending user form
<script>
$(function(){
$( ".add_user" ).on( "click", function() {
$(".add_user_form").load("form.php")
});
$(document).on("submit","#formID", function(ev){
var data = $(this).serialize();
console.log(data);
$.post('handler.php',data,function(resposne){
$('.result').html(resposne);
});
ev.preventDefault();
});
});
</script>
form.php
<form id="formID" action="" method="post">
<p>Add Blog Administrator:</p>
<input type="text" name="admin-user" value="" placeholder="username" id="username"><br>
<input type="password" name="admin-pass" value="" placeholder="password" id="password"><br>
<input type="email" name="admin-email" value="" placeholder="email" id="email"><br>
<input type="submit" name="add-user" value="Add User">
</form>
handler.php
<?php
include '../config.php';
$tbl_name="blog_members"; // Table name
if(isset($_POST['add-user'])){
$adminuser = $_POST['admin-user'];
$adminpass = $_POST['admin-pass'];
$adminemail = $_POST['admin-email'];
$sql="INSERT INTO $tbl_name (username,password,email) VALUES('$adminuser','$adminpass','$adminemail')";
$result=mysqli_query($link,$sql);
if($result){
echo '<p class="user-added">User has been added successfully!</p>';
echo '<a class="view-users" href="view-users.php">View Users</a>';
}else {
echo "Error: ".$sql."<br>".mysqli_error($link);
}
die;
}
?>
What you are looking for is to submit the form using AJAX rather than HTML.
Using the answer Submit a form using jQuery by tvanfosson
I would replace your
<input type="submit" name="add-user" value="Add User">
with
<button id="add-user-submit">Add User</button>
and then register an onClick-handler with
$( "#add-user-submit" ).on( "click", function() {
$.ajax({
url: 'add-user-form.php',
type: 'post',
data: $('form#formID').serialize(),
success: function(data) {
$(".add-user-content").append(data);
}
});
});
to add the actual submit functionality.
I have a bunch of records from a database that I am displaying on a page. Each record has their own form with an update and delete button. I'm using JQuery ajax to send the data to a PHP page to process the form.
The script works fine the first time I push any one of the buttons on any of the forms, but when I push another button on any of the forms (or even the same button on the same form) the ajax request doesn't send any of the data to the PHP page.
Code I'm using to output data on page:
<?php
foreach($records as $data) {
?>
<form>
<input type="number" name="et" step="0.01" value="<?php echo $data->et; ?>" />
<input type="hidden" name="token" value="<?php echo $token; ?>" />
<input type="hidden" name="id" value="<?php echo $data->et_id; ?>"/>
<input type="submit" name="update" value="Update" />
<input type="submit" name="delete" value="Delete" />
</form>
<?php
}
Javascript:
$(document).ready(function() {
var buttonName;
$('input[type=submit]').click('click', function() {
buttonName = $(this).attr('name');
});
$('form').on('submit', function(e) {
e.preventDefault();
var values = $(this).serializeArray();
console.log(values);
if(buttonName == 'delete') {
var message = confirm('Are you sure you want to delete this record?\n\n You can\'t get it back once you do.');
} else {
message = true;
}
if(message) {
$.post('submit/raw_et.php', {et: values[0].value, token: values[1].value, id: values[2].value, button: buttonName}, function(r) {
console.log(r);
});
}
});
});
PHP Snippet:
echo $_POST['button'];
echo $_POST['et'];
echo $_POST['id'];
The "values" variable in the javascript always has the correct data, but the ajax fails to send any data after the first time a button is pushed and the results return blank.
I don't understand why it won't send the data. Am I missing something really easy, or is it something more complicated?
Edit:
I've taken out the tables in the html, but still get the same results.
you are developing in a completely wrong pattern, instead of defining form inside tr, use record id and register event for clicking buttons:
<?php
foreach($records as $data) {
?>
<tr>
<td><input type="number" name="et" step="0.01" value="<?php echo $data->et; ?>" /></td>
<input type="hidden" name="token" value="<?php echo $token; ?>" />
<input type="hidden" name="id" value="<?php echo $data->et_id; ?>"/>
<td><a class='edit' meta-id="<?php echo $record; ?>">edit</a></td>
<td><a class='delete' meta-id="<?php echo $record; ?>">delete</a></td>
</tr>
<?php
}
?>
And now, try to register all buttons onclick for delete and edit.
$(".edit").click(function() {
var record = $(this).attr("meta-id");
$.post("edit uri" , {record : record , otherparam: valueofit} , function(result) {
alert(result);
});
});
$(".delete").click(function() {
var record = $(this).attr("meta-id");
$.post("delte uri" , {record : record} , function(result) {
alert(result);
});
});
You can expand the concept as you want, for less adding class to buttons or so on.
Hey Friends
i am having one forms and two button, and some text fields,what i need it if i click button 1 then the details in the text box should be POST to Page1.php if i click Button2 the details in the text box should be POST to Page2.php, i am having 8 text boxes to do the in form, how can i do that?
Let's suppose your button one id is btn1 and second has btn2 and form name is frm, you can do something like this:
var btn1 = document.getElementById('btn1');
var btn2 = document.getElementById('btn2');
btn1.onclick = function(){
document.forms['frm'].action = 'page1.php'
document.forms['frm'].submit(); // submit the form
};
btn2.onclick = function(){
document.forms['frm'].action = 'page2.php'
document.forms['frm'].submit(); // submit the form
};
A PHP solution would be:
<form action='' method='post'>
<input name='inputText' /><br />
<button value='1' name='whichOption'></button><br />
<button value='2' name='whichOption'></button><br />
</form>
At the top of the page this form is in, put this:
<?php
if(isset($_POST['whichOption']) {
switch($_POST['whichOption']) {
case 1: /* do something */ break;
case 2: /* do something else */ break;
}
}
?>
"something" is an include, a session variable set, or whatever you like.
Try this:
<input type="button" value="page1" onclick="this.form.action='Page1.php'; this.form.submit();" />
<input type="button" value="page2" onclick="this.form.action='Page2.php'; this.form.submit();" />
Why not just use the same page? When I need multiple submit alternatives I simply use submit buttons with different names:
<input type="submit" name="submit-save" value="Save" />
<input type="submit" name="submit-delete" value="Delete" />
When I need to know what action it is, I just check which data is sent:
if(isset($_POST['submit-save']))
{
//Do something
}
elseif(isset($_POST['submit-delete']))
{
//Do something else
}
Html:
<input id="Button1" value="Button1" type="button" /><br />
<input id="Button2" value="Button2" type="button" /><br />
<textarea id="TextBox1" cols="40" rows="5"><br />
<textarea id="TextBox2" cols="40" rows="5">
jQuery:
function PostToPage(DOOMid,uri) {
var vDOOMEl = $("#" + DOOMid);
$.ajax({
type: 'POST',
url: uri,
data: ({text : vDOOMEl.innerHTML}),
success: function() {},
dataType: "html"
});
}
function init() {
$('#Button1').click(function(e){
PostToPage('TextBox1','Page1.php');
});
$('#Button2').click(function(e){
PostToPage('TextBox2','Page2.php');
});
}
window.onload=init;
PHP:
<?php
//do something with $_POST['text'];
?>
You must download jQuery, and use it for this solution