I am building an app in CakePHP and I have a jquery dialog window and every time the user opens it I want to perform a jquery request that will populate the content with the result of the request.
I have an js file that is in the webroot/js folder, with the following script:
$.ajax({
url:'/projects/getAssets',
type:"POST",
data:assetData,
//dataType:'text',
update: '#assetManagerContent'
});
In my controller file (ProjectsController) I have the following function:
function getAssets($id = null) {
// Fill select form field after Ajax request.
if(!empty($this->data)){
$this->set('assetsFilter',
$this->Project->Asset->find('list',
array(
'conditions' => array(
'Asset.project_id' => '23'
)
)
)
);
$this->render('elements/assets', 'ajax');
}
}
And finally I have the view (elements/assets):
<?php $assetsFilter = $this->requestAction('projects/getAssets'); ?>
<?php foreach($assetsFilter as $assetFilter): ?>
<div class="assetManager-asset">
<div class="thumb"></div>
<div class="label-name"><?php echo $assetFilter['AssetType']['type'] ?></div>
<div class="label-date"><?php echo $assetFilter['Asset']['layer'] ?></div>
<?php //echo $assetFilter['Asset']['id'] ?>
</div>
<?php endforeach; ?>
When the user opens the dialog the ajax request is triggered but nothing seems to happen in the #assetManagerContent div.
I hope someone can tell me what I am doing wrong
As far as I know, there is no update option in the jQuery ajax api. Instead, you should add the success callback and populate the data there:
$.ajax({
url:'/projects/getAssets',
type:"POST",
data:assetData,
//dataType:'text',
success: function(data) {
$('#assetManagerContent').html(data);
}
});
There is no update-option, just as jeremyharris already pointed out.
If you only want to fill an element with HTML loaded via AJAX, you can also use $.load():
$('#assetManagerContent').load('/projects/getAssets', assetData);
It's basically a shorthand for the corresponding $.ajax() call, and will automatically issue a POST request if the data parameter is present.
See: http://api.jquery.com/load/
to make your action faster, cleaner and reusable you could write it this way.
function getAssets($id = null) {
// Fill select form field after Ajax request.
if(!empty($this->data)){
return $this->Project->Asset->find('list',
array(
'conditions' => array(
'Asset.project_id' => '23'
)
)
);
}
}
Ajax
$.ajax({
url:'/projects/getAssets/'+id,
type:"POST",
success: function(data) {
$('#assetManagerContent').html(data);
}
});
OR
$('#assetManagerContent').load('/projects/getAssets/'+id);
It works but shows result in text mode.
e.g.
<form action="/amit/tour-writer/derivedItineraries/getHotelDetail/1230"
id="DerivedItineraryGetHotelDetailForm" method="post" accept-charset="utf-8">
<div style="display:none;"><input type="hidden" name="_method" value="POST"/>
</div>
<div class="required"><label for="DerivedItineraryInclusion">Inclusion</label>
<textarea name="data[DerivedItinerary][inclusion]" class="ckeditor"
required="required" style="width:200px;" cols="30" rows="6"
id="DerivedItineraryInclusion">Test data</textarea></div></td></tr>
</form>
Related
My form html code, where i set action and the attribute name.
<div class="search_form">
<form action="<?php esc_url( home_url( '/' ) ); ?>" method="POST">
<input type="text" name="s" value="<?php get_search_query(); ?>" placeholder="Search...">
<input type="submit" value="Send">
</form>
</div>
I use localize scripts to connect ajax-search.
wp_enqueue_script( 'wc-estore-ajax-search-js', get_template_directory_uri() . '/assets/js/ajax-search.js', array( 'jquery' ), _S_VERSION, true );
wp_localize_script( 'wc-estore-ajax-search-js', 'search_form', array(
'url' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( 'search-nonce' )
) );
In ajax-search got nonce, set action and set url.
jQuery(function ($) {
$('.search_form input[name="s"]').on('keyup', function () {
let search = $('.search_form input[name="s"]').val();
if (search.length < 4) {
return false;
}
let data = {
s: search,
action: 'search_action',
nonce: search_form.nonce
};
$.ajax({
url: search_form.url,
data: data,
type: 'POST',
dataType: 'json',
beforeSend: function (xhr) {
},
success: function (data) {
console.log(data);
}
});
});
});
And in functions.php i want to see, what is in $_POST.
The action is the same as in the search-ajax.js.
add_action( 'wp_ajax_search_action', 'esp_search_ajax_action_callback' );
add_action( 'wp_ajax_nopriv_search_action', 'esp_search_ajax_action_callback' );
function esp_search_ajax_action_callback() {
/**
* Проверяем нонсе из массива пости и из wp_localize script
*/
if(!wp_verify_nonce($_POST['nonce'], 'search-nonce')){
wp_die('Данные пришли с левого адреса');
}
$_POST = filter_input_array( INPUT_POST, FILTER_SANITIZE_STRING );
$args = [
'post_type' => ['post', 'product'],
'post_status' => 'public',
's' => $_POST['s'],
];
$query_ajax = new WP_Query($args);
?>
<?php if($query_ajax->have_posts()): ?>
<?php while($query_ajax->have_posts()): ?>
<?php $query_ajax->the_post(); ?>
<h3 class="title-search"><?php the_title(); ?></h3>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
<?php endif; ?>
<?php
}
But the console is clear?
Where is my mistake?
Thanks for help.
Looks like you have a few things going on. Try these:
dataType is the type of data you're expecting back. You're not passing valid JSON back, so it is failing with a parse error (i.e. no success, no console.log).
vardump probably should be var_dump unless you've defined it elsewhere. If not, that's probably causing an error and sending back the error string (which again would not be valid JSON)
Although not necessarily the issue you're asking about, but you should also finish your callback with wp_die(); and pass whatever parameters you need for your situation.
If you want, while you're testing you can switch dataType to html.
You can also add in error (to see what the error is) and complete (to see that it actually came back) callbacks.
And just to be safe, you might want to filter your $_POST data with something like this:
$_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
or whatever filters fit your situation.
I need to connect codeigniter with a ajax post
the first problem was the use of jquery.min.js, if you use ajax you cannot use this version of jquery, you need to use the full version.
Then I tried to do all the jquery code in parts to go testing its functionality.
I think the problem is in the url of the ajax call or in the controller
this is my view (very simple)
<form action="#" id="form">
<label for="">nombre</label>
<input type="text" name="nombre" id="nombre">
<label for="">apellido</label>
<input type="text" name="apellido" id="apellido">
<label for="">cedula</label>
<input type="text" name="cedula" id="cedula">
<label for="">direccion</label>
<input type="text" name="direccion" id="direccion"><br>
<button class="btn btn-info" id="btn" type="submit">enviar</button>
</form>
jquery code
$(document).ready(function () {
$("#btn").on('click', function (e) {
// var data = $("#form").serialize();
// alert("datos:" + data);
$.ajax({
url: '<?php echo base_url('myController/formAjaxCrear')?>',
type: 'POST',
data: $("#form").serialize(),
dataType: 'json',
success: function (data) {
alert(data.nombre);
},
error: function () {
alert("something is wrong");
}
});
});
});
my controller in the file myController
public function formAjaxCrear(){
$data = [
'nombre' => $this -> input -> post('nombre'),
'apellido' => $this -> input -> post('apellido'),
'cedula' => $this -> input -> post('cedula'),
'direccion' => $this -> input -> post('cedula'),
];
echo json_encode($data);
}
I expected to receive in the browser popup window: Jessica, if I fill the input nombre with that information. Why do I only receive the error message?
Make following changes to your code
You have button type as submit, this is actually submitting the form. You can change this in 2 ways. Either change the JS Method
a)
$("#btn").on('click', function (e) {
e.preventDefault(); //This will prevent submitting of form.
b) You can also do this by changing the type of button from submit to just button
<button class="btn btn-info" id="btn" type="submit">enviar</button>
change above to
<button class="btn btn-info" id="btn" type="button">enviar</button>
For better standards, you should explicitly tell CodeIgnitor to return AJAX Data.
You can do this by making following changes in formAjaxCrear method.
header('Content-Type: application/json'); //This sends Headers and make sure that data type returned is JSON.
echo json_encode($data);
So, here is my codes:
form-checkout.php
<form id="rh_checkout_ajax" name="checkout" method="post" class="checkout woocommerce-checkout" enctype="multipart/form-data">
<?php if ( sizeof( $checkout->checkout_fields ) > 0 ) : ?>
<?php do_action( 'woocommerce_checkout_before_customer_details' ); ?>
<div class="col2-set" id="customer_details">
<div class="col-1">
<?php do_action( 'woocommerce_checkout_billing' ); ?>
</div>
<div class="col-2">
<?php do_action( 'woocommerce_checkout_shipping' ); ?>
</div>
</div>
<?php do_action( 'woocommerce_checkout_after_customer_details' ); ?>
<?php endif; ?>
<?php do_action( 'woocommerce_checkout_before_order_review' ); ?>
<div id="order_review" class="woocommerce-checkout-review-order">
<?php do_action( 'woocommerce_checkout_order_review' ); ?>
</div>
<?php do_action( 'woocommerce_checkout_after_order_review' ); ?>
<input value="send" type="submit" name="buy_product" style="display:none;" id="rh_product_add_done_click"></input>
</form>
my_js.js
//Ajax checkout submit
jQuery('#rh_checkout_ajax').submit(function(e){
var name = jQuery(this).attr('name');
jQuery.ajax({
data: {action: 'contact_form', name:name},
type: 'post',
url: ajaxurl,
success: function(data) {
alert(data);
}
});
});
functions.php
//Ajax submit callback
add_action('wp_ajax_contact_form', 'contact_form');
add_action('wp_ajax_nopriv_contact_form', 'contact_form');
function contact_form()
{
echo $_POST['name'];
}
What happens normally
So, when a product is purchased, then the user is redirected to order-detail page which shows what he/she just bought.
What I want it to happen:
I am trying to make it so that the form is submitted via ajax and the user is NOT redirected to the order-detail page, but rather stays in the product page (so, no refresh nor redirect).
I attempted to submit the form via ajax as above but not much of luck.
Could someone help me out with this?
Thanks!
You have to prevent the form from submitting normally. In your js file, add e.preventDefault(). Something like this:
jQuery('#rh_checkout_ajax').submit(function(e){
e.preventDefault();
var name = jQuery(this).attr('name');
jQuery.ajax({
data: {action: 'contact_form', name:name},
type: 'post',
url: ajaxurl,
success: function(data) {
alert(data);
}
});
});
I am trying to add data in cakephp by ajax without using ajax helper.Here insertion is working fine but problem is after insert data I have failed to see the success massage.Here is my effort.
<script>
$(document).ready(function(){
$('#submit').click(function(){
x=$("#rform").serializeArray();
$.post($("#rform").attr("action"),
x,
function(data)
{
$("#success").html(data);
$("#success").fadeIn();
$("#success").fadeOut(2800);
$("input").val('');
});
$("#rform").submit(function(){
return false;
});
});
});
</script>
Here is the add.ctp code
<?php
echo $this->Form->create('Info',array(
'id' => 'rform'
)); ?>
<fieldset>
<legend><?php echo __('Add Info'); ?></legend>
<?php
echo $this->Form->input('name');
echo $this->Form->input('email');
?>
</fieldset>
<?php
$options = array
(
'label' => 'Add',
'value' => 'Add',
'id' => 'submit'
);
echo $this->Form->end($options);
?>
</div>
<div style="color:green;" id="success">
</div>
Here after add it is repeating insertion page again in bellow.Here I need to show only success massage.If I remove $("#success").html(data); nothing is happening but after insert button name making disappear.How can I add success massage in here ?
I have solved it by little bit change
$("#success").html(data);
to
$("#success").html("Insert Success");
and here I have changed input button tag, I have use direct button here
<button id="submit">Submit </button>
I am new to MVC and currently working on a basic website setup. I am trying to have a modal window open where one can input some data and then press submit to submit it back to the database.
Using CodeIgniter and this Jquery Modal (doesn't necessary have to be this one thou).
Again I am very new to MVC so having some trouble visualizing the flow of data.
The modal opens correctly, but I'm trying to display the validation/errors in the same modal without opening a new window. What would I place near echo("error-ajax");, opening a view seems to result in opening a new window.
View -- Opens Modal:
...
...
View -- Actual Form:
<?php echo validation_errors(); ?>
<?php echo form_open('form'); ?>
<h3>New</h3>
<p>
<label>ID: <input class="pull-right" type="text" name="idnumber" value="<?php echo set_value('idnumber'); ?>" size="9"/></label>
</p>
<div><input type="submit" value="Submit" /></div>
</form>
<script>
$(function(){
$('form').submit(function(e){
e.preventDefault();
$.ajax({
type: "POST",
async: false,
url: "<?php echo site_url("bondform/save_form"); ?>",
success: function(){alert('Succes');},
error: function(){alert('Error');}
});
});
});
</script>
Controller:
<?php
class Bondform extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$config = array(
array(
'field' => 'idnumber',
'label' => 'Id Number',
'rules' => 'trim|required|min_length[9]|max_length[9]|xss_clean'
)
);
$this->form_validation->set_rules($config);
}
public function view_form()
{
$this->load->view('bond/form');
}
public function save_form()
{
if ($this->form_validation->run() == FALSE)
{
if ($this->input->is_ajax_request())
{
echo("error-ajax"); //placeholder, debug
}
else
{
echo("error-noajax"); //placeholder, debug
}
}
else
{
echo("succes-close"); //placeholder, debug
}
}
}
Thank you very much,
To start, move your ajax function from the modal view to the view that opens it, then you can control the contents of the modal without losing your form view.
Opens Modal:
<script>
$(function(){
$('body').on('submit', 'form', function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "<?php echo site_url("bondform/save_form"); ?>",
data: $(this).serialize();
success: function(response){ $('#form_container').html(response); alert('Succes');},
error: function(){alert('Error');}
});
});
});
</script>
Actual Form:
<div id="form_container">
<?php echo validation_errors(); ?>
<?php echo form_open('bondform/save_form'); ?>
<h3>New</h3>
<p>
<label>ID: <input class="pull-right" type="text" name="idnumber" value="<?php echo set_value('idnumber'); ?>" size="9"/></label>
</p>
<div><input type="submit" value="Submit" /></div>
</form>
</div>
Should get you started in the right direction.