How to create jQuery + ajax form without refresh?
This is my controller and views:
http://pastebin.com/GL5xVXFZ
In "clear" PHP I create something like this:
$(document).ready(function(){
$("form#submit").submit(function() {
var note = $('#note').attr('value');
$.ajax({
type: "POST",
url: "add.php",
data: "note="+ note,
success: function(){
$('form#submit').hide(function(){$('div.success').fadeIn();});
}
});
return false;
});
});
in add.php file is INSERT to Database.
There are more complicated ways of doing this for example detecting an ajax request in your action and then if detected print out a javascript response. The way you would do this is
JAVASCRIPT
function postForm(note){
$.ajax({
url : '/controller/action',
type : 'POST',
data : 'note='+note,
success : function(jsn){
var json = $.parseJSON(jsn);
if(json.status == 200)
alert('Completed Successfully');
else
alert('Not Completed Successfully');
},
error : function(xhr){
//Debugging
console.log(xhr);
}
});
}
PHP
<?php
Class Controller_ControllerName extends Controller_Template{
public $template = 'template';
public function action_index(){}
public function action_form(){
$this->auto_render = false; // <-EDITED
$array = array();
//PROCESSING FORM CODE HERE
if($success){
$array['status'] = 200;
}else{
$array['status'] = 500;
}
print json_encode($array);
}
}
?>
this is an example i have done without testing but this surely should be enough for you to work on
Related
when submitting the form using ajax codeigniter validation not working please resolve this issue i am facing this problem from last week
jQuery code that i am using for submitting form
$(function() {
$("#registratiom_form").on('submit', function(e) {
e.preventDefault();
var contactForm = $(this);
$.ajax({
url: contactForm.attr('action'),
type: 'POST',
data: contactForm.serialize(),
success: function(response){
}
});
});
});
Controller
public function add_account() {
if($this->form_validation->run('add_account')) {
$post = $this->input->post();
unset($post['create_account_submit']);
$this->load->model('Frontendmodel', 'front');
if($this->front->add_user($post)){
$this->session->set_flashdata('message', 'Account Created Successfully !');
$this->session->set_flashdata('message_class', 'green');
}
return redirect('Frontend/login');
} else {
$this->login();
}
}
Here is just the concept. I have not tried codeigniter but am php professional.
You will need to retrieve records as json and pass it to ajax. At codeigniter
header('Content-Type: application/x-json; charset=utf-8');
$result = array("message" =>'Account Created Successfully !');
echo json_encode($result);
hence the code might look like below
public function add_account(){
if($this->form_validation->run('add_account')){
$post = $this->input->post();
unset($post['create_account_submit']);
$this->load->model('Frontendmodel', 'front');
if($this->front->add_user($post)){
header('Content-Type: application/x-json; charset=utf-8');
$result = array("message" =>'ok');
echo json_encode($result);
//$this->session->set_flashdata('message', 'Account Created Successfully !');
$this->session->set_flashdata('message_class', 'green');
}
return redirect('Frontend/login');
}else{
$this->login();
}
}
in ajax you can set datatype to json to ensure that you can get response from the server and then let ajax handle the response....
$(function() {
$("#registratiom_form").on('submit', function(e) {
e.preventDefault();
var contactForm = $(this);
$.ajax({
url: contactForm.attr('action'),
type: 'POST',
dataType: 'json',
data: contactForm.serialize(),
success: function(response){
alert(response.message);
console.log(response.message);
//display success message if submission is successful
if(response.message =='ok'){
alert('message submited successfully');
}
}
});
});
});
You have a misunderstanding about what an ajax responder can and cannot do. One thing it cannot do is use PHP to make the browser redirect to a new page. You will have to send a clue back to the success function and then react appropriately.
A few minor changes to the answer from #Nancy and you should be good.
public function add_account()
{
if($this->form_validation->run('add_account'))
{
$post = $this->input->post();
unset($post['create_account_submit']);
$this->load->model('Frontendmodel', 'front');
if($this->front->add_user($post))
{
$this->session->set_flashdata('message', 'Account Created Successfully !');
$this->session->set_flashdata('message_class', 'green');
echo json_encode(array("result" => 'ok'));
return;
}
$message = '<span class="error">Account Not Created!</span>';
}
else
{
$message = validation_errors('<span class="error">', '</span>');
}
echo json_encode(array("result" => 'invalid', 'message' => $message));
}
In the Javascript, handle the various responses in the success function of $.ajax
$(function () {
$("#registratiom_form").on('submit', function (e) {
var contactForm = $(this);
e.preventDefault();
$.ajax({
url: contactForm.attr('action'),
type: 'POST',
dataType: 'json',
data: contactForm.serialize(),
success: function (response) {
console.log(response); // so you can examine what was "echo"ed from the server
if (response.message=='ok') {
// Simulate an HTTP redirect: to the right page after successful login
window.location.replace( "https://example.com/frontend/somepage");
} else {
//stay on the same page but show the message in some predefined spot
$('#message').html(response.message);
}
}
});
});
});
So, i have a following ajax code and controller code, my problem is i want to insert comment withouth refreshing the page and not redirecting to another page, and it seems that whenever i hit btnCommentSubmit it is redirecting me to my controller page, how to prevent that?
Ps. The insertion is working
//AJAX CODE
$('#btnComment').click(function(e){
var comment_identifier = $(this).data("value");
var comment_by = $(this).data("id");
$('#formAddComment').attr('action', '<?php echo base_url() ?>Discussion/addComment/'+comment_identifier+"/"+comment_by);
});
$('#btnCommentSubmit').click(function(){
var url = $('#formAddComment').attr('action');
var addCommentTxt = $('#addCommentTxt').val();
$.ajax({
type: 'post',
url: url,
data: {addCommentTxt:addCommentTxt},
success: function(){
alert('success');
},
error: function(){
console.log(data);
alert('Could not add data');
}
});
});
});
//Controller code
public function addComment(){
$cIden = $this->uri->segment(3);
$cBy = $this->uri->segment(4);
$data = array(
"comment_identifier" => $cIden,
"comment_by" => preg_replace('/[^a-zA-Z-]/', ' ', $cBy),
"comment" => $this->input->post('addCommentTxt'),
"comment_at" => time()
);
if ($this->Crud_model->insert('comments',$data)) {
return true;
}else{
return false;
}
}
Add e.preventDefault() in the beginning of your function:
$('#btnCommentSubmit').click(function(e){
e.preventDefault();
...
}
You may want to use jQuery form plugin. It submit form to our controller without any page refresh/redirect. I use it all the time.
https://jquery-form.github.io/form/
Example usage:
$('#form').ajaxForm({
beforeSubmit: function() {
//just optional confirmation
if (!confirm('Are you sure want to submit this comment?')) return false;
show_loading();
},
success: function(status) {
hide_loading();
if (status == true) {
alert('success');
} else {
alert('Could not add data');
}
}
});
You can use javascript:void(0); like href="javascript:void(0);"
How can I get the serialized data in the Controller?
For example i have this data...
var str = $('#edit-form-data').serialize(); //string
I pass it inro the function like this...
editDosage(urlEdit,str);
My function is like this...
function editDosage(url,res)
{
console.log(url);
$.ajax({
url: url,
method: 'POST',
data: res,
success:function(data){},
error: function(data){}
});
}
How do I get the input value of the serialized data in the Controller in Laravel?
For example, I have included in the edit-form-data the name of the 'store_id' and I want to access it in the controller. Can I do something like?
$store_id = Input::get('store_id');
dd($store_id);
you may also use,
$(document).ready(function() {
$('#edit-form-data').ajaxForm();
});
checkthis out: http://malsup.com/jquery/form/
Or check this one:
$(document).ready( function(){
$(document).on('click','#submitButton', function(){
var _this = this;
var request = $.ajax({
url: url,
type: "POST",
data: jQuery("#form").serialize(),
dataType: "json"
});
request.done(function( msg ) {
});
request.fail(function( jqXHR, textStatus ){
});
});
});
And in php
try {
// input code
if($_REQUEST){
echo json_encode("success");
} else {
echo json_encode("checkinput");
}
}catch (Exception $e){
echo $e->getMessage();
echo json_encode("error");
}
You can use a few different ways to get the input.
From the Request
If your function has a Request parameter, it you can get the input from it.
public function methodA(Request $request) {
$data = $request->all();
}
You can view the documentation on Requests here.
Input Facade
Similar to requests you can use the Input Facade to get the inputted data.
public function methodB() {
$data = Input::all();
}
You can view the API docs for the Input Facade here.
Jquery code
$.post('/ajax', {'_token': $token,data: $this.serialize()}, function(resp) {
/*optional stuff to do after success */
});
controller function##
public function CreateBill()
{
parse_str($_POST['data'], $data);
return $data;
}
i really struggle to get the POST value in the controller .i am really new to this..Please someone share me some light..being in the dark for long hours now.
i had a checkboxes and need to pass all the ids that had been checked to the controller and use that ids to update my database.i don't know what did i did wrong, tried everything and some examples too like here:
sending data via ajax in Cakephp
found some question about same problem too , but not much helping me( or maybe too dumb to understand) . i keep getting array();
please help me..with my codes or any link i can refer to .here my codes:
my view script :
<script type="text/javascript">
$(document).ready(function(){
$('.checkall:button').toggle(function(){
$('input:checkbox').attr('checked','checked');
$('#button').click( function (event) {
var memoData = [];
$.each($("input[name='memo']:checked"), function(){
memoData.push($(this).val());
});
var value = memoData.join(", ")
//alert("value are: " + value);
//start
$.ajax({
type:"POST",
traditional:true;
data:{value_to_send:data_to_send},
url:"../My/deleteAll/",
success : function(data) {
alert(value);// will alert "ok"
},
error : function() {
alert("false submission fail");
}
});
//end
} ); //end of button click
},function(){//uncheck
$('input:checkbox').removeAttr('checked');
});
});
my controller :
public function deleteAll(){
if( $this->request->is('POST') ) {
// echo $_POST['value_to_send'];
//echo $value = $this->request->data('value_to_send');
//or
debug($this->request->data);exit;
}
}
and result of this debug is:
\app\Controller\MyController.php (line 73)
array()
Please help me.Thank you so much
How about this:
Jquery:
$(document).ready(function() {
$('.checkall:button').toggle(function() {
$('input:checkbox').attr('checked','checked');
$('#button').click(function(event) {
var memoData = [];
$.each($("input[name='memo']:checked"), function(){
memoData.push($(this).val());
});
//start
$.ajax({
type: 'POST',
url: '../My/deleteAll/',
data: {value_to_send: memoData},
success : function(data) {
alert(data);// will alert "ok"
},
error : function() {
alert("false submission fail");
}
});//end ajax
}); //end of button click
},function(){//uncheck
$('input:checkbox').removeAttr('checked');
});
});
In controller:
public function deleteAll()
{
$this->autoRender = false;
if($this->request->is('Ajax')) { //<!-- Ajax Detection
$elements = explode(",", $_POST['value_to_send']);
foreach($elements as $element)
{
//find and delete
}
}
}
You need to set the data type as json in ajax call
JQUERY CODE:
$.ajax({
url: "../My/deleteAll/",
type: "POST",
dataType:'json',
data:{value_to_send:data_to_send},
success: function(data){
}
});
I am validating a form with ajax and jquery in WordPress post comments textarea for regex. But there is an issue when i want to alert a error message with return false. Its working fine with invalid data and showing alert and is not submitting. But when i put valid data then form is not submit. May be issue with return false.
I tried making variable and store true & false and apply condition out the ajax success block but did not work for me.
Its working fine when i do it with core php, ajax, jquery but not working in WordPress .
Here is my ajax, jquery code.
require 'nmp_process.php';
add_action('wp_ajax_nmp_process_ajax', 'nmp_process_func');
add_action('wp_ajax_nopriv_nmp_process_ajax', 'nmp_process_func');
add_action('wp_head', 'no_markup');
function no_markup() {
?>
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery('form').submit(function (e) {
var comment = jQuery('#comment').val();
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: 'action=nmp_process_ajax&comment=' + comment,
success: function (res) {
count = res;
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
return false;
}
}
});
return false;
});
});
</script>
<?php
}
And i'm using wordpress wp_ajax hook.
And here is my php code.
<?php
function nmp_process_func (){
$comment = $_REQUEST['comment'];
preg_match_all("/(->|;|=|<|>|{|})/", $comment, $matches, PREG_SET_ORDER);
$count = 0;
foreach ($matches as $val) {
$count++;
}
echo $count;
wp_die();
}
?>
Thanks in advance.
Finally, I just figured it out by myself.
Just put async: false in ajax call. And now it is working fine. Plus create an empty variable and store Boolean values in it and then after ajax call return that variable.
Here is my previous code:
require 'nmp_process.php';
add_action('wp_ajax_nmp_process_ajax', 'nmp_process_func');
add_action('wp_ajax_nopriv_nmp_process_ajax', 'nmp_process_func');
add_action('wp_head', 'no_markup');
function no_markup() {
?>
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery('form').submit(function (e) {
var comment = jQuery('#comment').val();
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: 'action=nmp_process_ajax&comment=' + comment,
success: function (res) {
count = res;
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
return false;
}
}
});
return false;
});
});
</script>
<?php
}
And the issue that i resolved is,
New code
var returnval = false;
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
async: false, // Add this
data: 'action=nmp_process_ajax&comment=' + comment,
Why i use it
Async:False will hold the execution of rest code. Once you get response of ajax, only then, rest of the code will execute.
And Then simply store Boolean in variable like this ,
success: function (res) {
count = res;
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
returnval = false;
} else {
returnval = true;
}
}
});
// Prevent Default Submission Form
return returnval; });
That's it.
Thanks for the answers by the way.
Try doing a ajax call with a click event and if the fields are valid you submit the form:
jQuery(document).ready(function () {
jQuery("input[type=submit]").click(function (e) {
var form = $(this).closest('form');
e.preventDefault();
var comment = jQuery('#comment').val();
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: {'action':'nmp_process_ajax','comment':comment},
success: function (res) {
var count = parseInt(res);
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
} else {
form.submit();
}
}
});
});
});
note : you call need to call that function in php and return only the count!
Instead of submitting the form bind the submit button to a click event.
jQuery("input[type=submit]").on("click",function(){
//ajax call here
var comment = jQuery('#comment').val();
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: 'action=nmp_process_ajax&comment=' + comment,
success: function (res) {
count = res;
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
return false;
}else{
jQuery("form").submit();
}
}
});
return false;
})
Plus also its a good idea to put return type to you ajax request.
Let me know if this works.