I'm trying to create filters using a Select2 dropdown and I do not know why the Select2:select event stop working after updating the html with the data that comes via Ajax.
Please help - My PHP is:
<div class="select-yellow fecha-container">
<select id="fecha" class="select2 fecha-addon" data-minimum-results-for-search="Infinity">
<?php foreach($fechas as $fecha): ?>
<option value="<?php echo $fecha; ?>"><?php echo formatDate($fecha); ?></option>
<?php endforeach; ?>
</select>
</div>
The JS file:
$('#fecha').on("select2:select", function(e) {
// here it's working
var fecha = $('#fecha').val();
var provincia = $('#provincia').val();
var request = $.ajax({
url: app.base_url + "/ajax-gallery/",
method: "GET",
data: {
provincia: provincia,
fecha: fecha,
tag: provincia
},
dataType: "html"
});
request.done(function (msg) {
if($.trim(msg).length) {
$('.gallery-container').html(msg);
var $filter = $('.gallery-container').find('.fecha-addon');
$('.fecha-container').html($filter);
$("#fecha option").each(function(){
if($(this).val()==fecha){
$(this).attr("selected","selected");
}
});
$('#fecha').select2({
minimumResultsForSearch: -1
});
//after rebind the event doesn't work
}else{
$('#gallery-notices').html('<strong>No hay más imagenes con esta fecha</strong>');
}
});
request.fail(function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
});
Related
I want to update meta_key with ajax in wordpress i use this form
this is my code but not work for me
<?php
add_action( 'wp_head', 'ajax_the_clike' );
function ajax_the_clike() {
?>
<script>
var ajaxurl = 'http://'+window.location.host+'/wp-admin/admin-ajax.php';
var formd = "#like";
$(formd).submit(function(event) {
event.preventDefault();
$.ajax({
url: $(formd).attr('action'),
type: $(formd).attr('method'),
data: $(formd).serialize(),
success: function(data) {
console.log("SUCCESS!");
},
error: function(data) {
console.log("FAILURE");
}
});
});
</script>
<?php
}
add_action('wp_ajax_the_clike', 'the_clike'); // wp_ajax_{ACTION HERE}
add_action('wp_ajax_nopriv_the_clike', 'the_clike');
function the_clike() {
echo '<form action="'.site_url() .'/wp-admin/admin-ajax.php" method="post" id="like">';
echo '<input type="submit" value="VoteUp" id="submit" name="submits">';
if(isset($_POST['submits'])){
$postsid = get_the_ID();
$addone = get_field('like');
$addone++;
update_field('field_5f009fe6d7067' ,$addone, $postsid);
}
echo '</form><p> Like : '; if(get_field('like')) { the_field('like');}else{echo '0';} echo '</p>';
}
?>
I using a Advanced custom field plugin
Where is wrong? How do I solve this problem?
Thanks for any help
Hi all i am trying to delete my record from datatable with out page refresh in codeigniter i have used ajax i don't know where i have done mistake its not deleting the record
Below is the my view:
<tbody>
<?php
if (!empty($employees)) {
foreach ($employees as $emp) {
?>
<tr>
<td><?php echo $emp->emp_name; ?></td>
<td><?php echo $emp->salary; ?></td>
<td class='text-center'>
<button type="submit" class="btn btn-info btn-xs confirmation" name="login"><i class='fas fa-edit'></i></button>
</td>
<td class='text-center'>
<button type="submit" onClick="return ConfirmDelete()" class="btn btn-danger btn-xs confirmation empdelete" id="<?php echo $emp->id;?>"><i class='fas fa-times'></i></button>
</td>
</tr>
<?php
}
}
?>
</tbody>
<script>
$(document).ready(function(){
$(".empdelete").click(function(e){
alert();
e.preventDefault();
$.ajax({
alert();
type: "POST",
url: "<?=site_url('Employee/delete');?>",
cache: false,
data: {id:$(this).attr("id")}, // since, you need to delete post of particular id
success: function(data) {
if (data){
alert("Success");
} else {
alert("ERROR");
}
return false;
}
});
});
});
</script>
Here is the my controller:
function delete()
{
$id = $this->input->post('id'); // get the post data
$empdelete=$this->Emp_model->delete($id);
if($empdelete){
echo true;
} else {
echo false;
}
}
Here is my model's method delete:
function delete($id)
{
$sql = "DELETE FROM employees WHERE id=?";
return $this->db->query($sql,array($id));
}
Can any one help me how can i do that with out page refresh i want to delete my record.
Thanks in advance.
Try this:
$(document).ready(function () {
function ConfirmDelete() {
var x = confirm("Are you sure you want to delete?");
if (x)
return true;
else
return false;
}
$(".empdelete").click(function (e) {
var obj = $(this);
e.preventDefault();
//alert(); what's this do?
if (ConfirmDelete() == false) {
return false;
}
$.ajax({
//alert(); this can't go here
type: "POST",
url: "<?php echo site_url('Employee/delete'); ?>",
cache: false,
data: {id: $(this).attr("id")},
success: function (data) {
console.log('ajax returned: ');
console.log(data);
if (data) {
obj.closest('tr').remove();
alert("Success");
} else {
alert("ERROR");
}
return false;
}
});
});
});
and remove HTML onClick:
<button type="submit" class="btn btn-danger btn-xs confirmation empdelete" id="<?php echo $emp->id;?>"><i class='fas fa-times'></i></button>
Hope this will help you :
Your button should be like this :
<button type="button" onClick="return ConfirmDelete(this)" class="btn btn-danger btn-xs confirmation empdelete" data-id="<?=$emp->id;?>"><i class='fas fa-times'></i></button>
Your ajax code should be like this :
function ConfirmDelete(obj)
{
var x = confirm("Are you sure you want to delete?");
if (x == true)
{
var id = $(obj).data('id');
alert(id);
if (id != '')
{
//do you ajax here
$.ajax({
type: "POST",
url: "<php echo site_url('Employee/delete'); ?>",
cache: false,
data: {'id': id},
success: function (data) {
console.log('ajax returned: ');
console.log(data);
if (data) {
alert("Success");
} else {
alert("ERROR");
}
return false;
}
});
}
}
else
{
return false;
}
}
Your controller should be like this :
function delete()
{
$id = $this->input->post('id'); // get the post data
$empdelete = $this->Emp_model->delete($id);
if($empdelete)
{
echo true;
} else
{
echo false;
}
exit;
}
Your delete method should be like this :
function delete($id)
{
$this->db->where('id',$id);
$this->db->delete('employees');
return $this->db->affected_rows();
}
I'm trying to post form data to a php file that will then handle a mysql request. But before I do the mysql, I'm trying to connect to the php file.
The request is Cross-Domain.
When i submit the form, i get the error: {"readyState":4,"status":200,"statusText":"success"}
You can see the test page here: http://jonathan-tapia.mybigcommerce.com/store-locator/
form code:
<div class="map-search">
<h1>Give us your zip code. We'll tell you where to find us.</h1>
<div id="map-form">
<form id="lookup-form" action="http://dev.visioncourse.com/customers/baldguy/index.php" method="post">
<p>Within
<select id="distance" name="distance">
<option value="10">10</option>
<option selected="selected" value="25">25</option>
<option value="50">50</option>
<option value="100">100</option>
</select>
miles of
<input id="zipcode" type="text" name="postalcode" value="" size="8" />
<input id="lookup" type="submit" value="Look Up" />
</p>
</form>
</div>
</div>
<div class="map-results"> </div>
updated JS:
<script type="text/javascript">// <![CDATA[
//submit form
$('#lookup-form').submit(function(event) {
event.preventDefault();
var formdata = $(this);
var link = formdata.attr('action');
var distance = $('#distance').val();
var zipcode = $('#zipcode').val();
console.log('.\n..\n...\n....\nSubmitting Form\n....\n...\n..\n.');
$.ajax({
crossDomain: true,
type: 'POST',
url: link,
data: {
'distance': distance,
'postalcode': zipcode
},
dataType: 'jsonp',
error: function(data) {
console.log('error: ' + data);
},
success: function(data) {
console.log('success: ' + data);
},
xhrFields: {
withCredentials: true
}
});
});
// ]]>
updated php file:
<?php
$arr = array();
$distance = $_POST['distance']
$zip = $_POST['postalcode'];
if(isset($distance) && isset($zip)) {
array_push($arrr, {'d': $distance, 'z': $zip});
}
echo json_encode($arr);
?>
error i'm receiving from console:
GET http://dev.visioncourse.com/customers/baldguy/index.php?callback=jQuery17203092896034941077_1451698154204&distance=25&postalcode=85251 jquery.min.js:4
EDIT:
The php file will get the distance and zip code from the form and connect to a mysql database for a google maps store locator. so when a person submits the radius and the zip code it will display results. but all of this will be on the php file.
The file doing the form submission will submit the form, wait for the php to do it's work, then display the php file with the results
Try it with data: {"distance": distance, "zipcode": zipcode},.
In your code you insert the value of the variables twice instead of a name and a value.
Also, you need to send the zipcode with the name of 'postalcode'. Otherwise your phpscript wouldn't find it.
you can try this way:
javascript:
<script>
var formdata = $(this);
var link = formdata.attr('action');
var distance = $('#distance').val();
var zipcode = $('#zipcode').val();
$.ajax({
type: 'GET',
url: link,
data: {"distance": distance,"postalcode": zipcode},
async: false,
jsonpCallback: 'jsonp_callback',//name of function returned from php
contentType: "application/json",
dataType: 'jsonp',
success: function(r) {
console.log(r);
},
error: function(e) {
alert(e.message);
}
});
</script>
php:
<?php
$arr = array();
$distance = $_GET['distance'];//sample 123
$zip = $_GET['postalcode'];//sample 65455
if(isset($distance) && isset($zip)) {
$arr = array('d'=> $distance, 'z'=> $zip);
}
$json = 'jsonp_callback(';
$json .= json_encode($arr);
$json .= ');';
echo $json;
?>
response:
jsonp_callback({"d":123,"z":65455});
Please help i can't update the status by use the checked box.
When i selected the check box and select delete button, status will change to 'deleted' but now i can't update the data.
This is my view
<a href="javascript:;" id="delete" class="myButton" >Delete</a>
<div>
<input type="checkbox" class="cb_invoice" id="<?php echo $r->INVOICENUMBER;?>" value="<?php echo $r->INVOICENUMBER;?>">
</div>
This my script
<script>
$('#delete').click(function() {
var _url = "<?php echo site_url('commission/delete_invoices');?>";
var d_obj = $(".cb_invoice");
var d_val = [];
for (var i = 0; i < d_obj.length; i++){
if(d_obj[i].checked){
d_val.push(d_obj[i].value);
}
}
$.ajax({
url: _url,
data: {data: d_val},
type: 'post',
success: function(data) {
//console.log(data);
location.reload();
}
});
});
</script>
This my controller
function delete_invoices(){
$invoice = $this->input->post('data');
foreach ($invoice as $invoice) {
$this->m_commission->delete_invoice($invoice);
}
}
This is my model
function delete_invoice($invoice){
$this->db->update('salesinvoiceheader');
$this->db->set('STATUS','deleted');
$this->db->where('INVOICENUMBER', $invoice);
}
Change the order of update as follows in your modal:-
function delete_invoice($invoice){
$this->db->set('STATUS','deleted');
$this->db->where('INVOICENUMBER', $invoice);
$this->db->update('salesinvoiceheader');
}
My drop down is not working in ajax form submit but its working on normal form.
When i do ajax submit i get error in firebug
"NetworkError: 404 Not Found - http://example.com/yii/def/state/create"
But when i do the normal submission the form works.
Please help me to solve this issue
My ajax view is _ajax_create_form.php. Code:
<div class="form">
<?php
$form=$this->beginWidget('bootstrap.widgets.TbActiveForm',array(
'id'=>'state-create-form',
'enableAjaxValidation'=>true,
'enableClientValidation'=>true,
'method'=>'post',
'action'=>array("state/create"),
'type'=>'horizontal',
'htmlOptions'=>array(
'onsubmit'=>"return false;",/* Disable normal form submit */
),
'clientOptions'=>array(
'validateOnType'=>true,
'validateOnSubmit'=>true,
'afterValidate'=>'js:function(form, data, hasError) {
if (!hasError)
{
create();
}
}'
),
)); ?>
div class="row"> <?php echo $form->labelEx($model,'country_id'); ?> <?php echo $form->dropDownList($model,'country_id',
CHtml::listData(Country::model()->findAll(),'id','name')); ?> <?php echo $form->error($model,'country_id'); ?> </div>
<div class="modal-footer">
<div class="form-actions">
<?php
$this->widget('bootstrap.widgets.TbButton', array(
'buttonType'=>'submit',
'type'=>'primary',
'icon'=>'ok white',
'label'=>$model->isNewRecord ? 'Create' : 'Save',
));
?>
</div>
</div>
<?php
$this->endWidget(); ?>
</div>
Scipt for ajax submit
<script type="text/javascript">
function create()
{
var data=$("#state-create-form").serialize();
jQuery.ajax({
type: 'POST',
url: '<?php
echo Yii::app()->createAbsoluteUrl("state/create"); ?>',
data:data,
success:function(data){
//alert("succes:"+data);
if(data!="false")
{
$('#state-create-modal').modal('hide');
renderView(data);
$.fn.yiiGridView.update('state-grid', {
});
}
},
error: function(data) { // if error occured
alert("Error occured.please try again");
alert(data);
},
dataType:'html'
});
}
function renderCreateForm()
{
$('#state-create-form').each (function(){
this.reset();
});
$('#state-view-modal').modal('hide');
$('#state-create-modal').modal({
show:true,
});
}
</script>
My Controller code is
public function actionCreate()
{
$model=new State;
// Uncomment the following line if AJAX validation is needed
$this->performAjaxValidation($model,"state-create-form");
if(Yii::app()->request->isAjaxRequest)
{
print_r($_POST['State']);
if(isset($_POST['State']))
{
$model->attributes=$_POST['State'];
if($model->save())
{
echo $model->id;
}
else
{
echo "false";
}
return;
}
}
else
{
if(isset($_POST['State']))
{
$model->attributes=$_POST['State'];
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$this->render('create',array(
'model'=>$model,
));
}
}
Chnage your AJAX url
try by this
var href = window.localion.href.split('/');
var SITE_URL = href[0] + '//' + href[2] + '/';
$.ajax({
url: SITE_URL + 'controller/action',
........
........
});