CodeIgniter, Ajax... How to use insert_id() - php

Excuse my English, I hope you can understand my question...
In my program, when you submit a new record to the database (MySQL) using a modal+form, it is drawn in a data table without refreshing or recharging the actual page, it's appended dynamically.
What I need to do is, in every new record, draw/append the data AND 2 buttons (1 for deleting that record and 1 for updating it) with the ID of the new data.
I read I can use insert_id() to get the last inserted id, but I don't know how to use it and how to work with the result in my Ajax call.
Any hint, please? I'm pretty new to programming.
Thanks for your time.
EDIT
I need the data I introduced in the modal/form (for that I was using .serialize()) AND the ID generated in the DB...
I don't know how to use the model/controller returned ID info.
I have this in my controller:
public function nuevo_elemento_diccionario()
{
$this->load->helper('form');
$this->load->library('form_validation');
// Validation rules that I deleted for this post
if ($this->form_validation->run() === FALSE)
{
$this->load->view("header");
$this->load->view("section-aside");
$this->load->view("vista_nuevo_elemento_diccionario", $datos);
$this->load->view("footer");
}
else
{
$last_id = $this->mod_diccionarios->nuevo_elemento_diccionario();
echo json_encode(array('last_id' => $last_id));
redirect('/diccionarios/lista_diccionarios');
}
}
Model:
public function nuevo_elemento_diccionario()
{
$datos = array(
'ELDI_Key' => $this->input->post('eldi_key'),
'ELDI_Display' => $this->input->post('eldi_display'),
'ELDI_SuDiccionario' => $this->input->post('eldi_sudiccionario'),
);
$this->db->insert('elementos_diccionario', $datos);
/* $ultima_id = $this->db->insert_id();*/
$last_id = $this->db->insert_id();
return $last_id;
}
Javascript/Ajax (where you see var key = $('input[name="eldi_key"]').val(); and using it, is where I need to use the ID to use the new ID for delete and update clicking the generated buttons):
function nuevo_elemento()
{
var id =$('input[name="eldi_id"]').val();
var display = $('input[name="eldi_display"]').val();
var key = $('input[name="eldi_key"]').val();
key = key.split(" ").join("_").toLowerCase();
swal({
title: 'Añadir elemento',
text: "¿Quieres añadir este elemento?",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Sí',
cancelButtonText: 'No'
}).then((result) => {
if (result.value) {
$.ajax({
type: "POST",
url: $("#base_url").attr("valor") +
"diccionarios/nuevo_elemento_diccionario",
data: $("#formNuevoElementoDiccionario").serialize(),
success: function(data) {
console.log(data);
$('#Modal_Add').modal('hide');
$("#formNuevoElementoDiccionario").trigger("reset");
var html =
'<tr>'+
'<td>' + key + '</td>' +
'<td>'+ display +'</td>'+
'<td>'+
'<span class="btn btn-default editar_elemento"
id=' + key + ' value="' + key + '">' +
'<a href="'+$("#base_url").attr("valor") +
"diccionarios/elemento_diccionario/"+key+'" title="Editar">' +
'<i class="material-icons">edit</i>' +
'</a>' +
'</span>' +
'</td>' +
'<td>' +
'<span class="btn btn-default borrar_elemento"
id="'+ key +'" value="'+ key +'">'+
'<i class="material-
icons">delete_outline</i>'+
'</span>'+
'</td>'+
'</tr>'
$('#tabla-diccionarios').append(html);
swal("Añadido", "Elemento añadido correctamente",
"success");
$(".borrar_elemento").off();
evento_borrar_elemento();
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("Error: " + textStatus);
}
});
}
})
}

You can use insert_id() only after inserting data to DB. If you need user last id in controller or js try this:
public function nuevo_elemento_diccionario()
{
$datos = array(
'ELDI_Key' => $this->input->post('eldi_key'),
'ELDI_Display' => $this->input->post('eldi_display'),
'ELDI_SuDiccionario' => $this->input->post('eldi_sudiccionario'),
);
$this->db->insert('elementos_diccionario', $datos);
$ultima_id = $this->db->insert_id();
return $ultima_id;
}
Then you can use json_encode() for return data to js in Controller:
public function nuevo_elemento_diccionario()
{
$this->load->helper('form');
$this->load->library('form_validation');
// Validation rules that I deleted for this post
if ($this->form_validation->run() === FALSE)
{
$this->load->view("header");
$this->load->view("section-aside");
$this->load->view("vista_nuevo_elemento_diccionario", $datos);
$this->load->view("footer");
}
else
{
$last_id = $this->mod_diccionarios->nuevo_elemento_diccionario();
echo json_encode(array('last_id' => $last_id));
// i`m not sure that you need to use redirect
redirect('/diccionarios/lista_diccionarios');
}
}
In you js edit success function:
success: function(data) {
var result = JSON.parse(data);
var insert_id = result.insert_id;

Related

Why Ajax successful response is not accessible

I have a simple jQuery Ajax post call that works. A product is generated & added to cart.
I did find many answers but none seem to apply here.
But I cannot access the response content (post id) itself in my JS code.
In the code below - in comments - few more trials that I tried to no avail.
What am I missing??
Ajax post request:
jQuery.post(
ts_woo.ajax_url,
{'action': 'do_ts_woo',
'order': orderfilename,
'tilesize': globalTileSize,
'board': urlAtts,
'table': table
},
function(data) {
console.log("type of response="+ typeof data + " string=" + data); // data is a string but does not display it.
var response = jQuery.parseJSON(JSON.stringify(data));
console.log("do_ts_woo. Got id="+response); // undefined & so is response.id
pid = response;
if(pid>0){
//pid = response['id'];
console.log("do_ts_woo. SUCCESS response="+pid);
alert('Add to cart: ' + response.id);
ts_iframe(shopdomain + "/cart/?add-to-cart="+pid);
} else {
// ALWAYS end up here while all was successful...
console.log("do_ts_woo. FAILURE response="+response.id);
}
return false;
}
).done(function(response) {/* alert( "done:"+response );*/})
.fail(function(msg) {alert( "error msg="+msg );})
.always(function(response) {
//console.log("do_ts_woo. ALWAYS respone.id="+response.id); SAME PROBLEM HERE
});
Here is the PHP code
$pid = generate_woo_product("ts-".date("Ymd_His"), $product_price[1], $pimage, $allTable); // PRODUCT is GENERATED
error_log("pid =". $pid);
if ($pid > 0){
error_log ("product pid=".$pid." generated successfully");
echo $pid;
//tried wp_send_json_success($pid);
//tried wp_send_json_success(array('success' => true, 'id' => $pid));
} else error_log("do_ts_woo: FAIL generate_woo_product returned".$pid);
wp_die();
Please, try to use
wp_send_json(['pid' => $pid]);
exit;
instead of echo
And then access your $pid in js with
data.pid
Please, use data.pid without JSON.parse, cause data, in this case, needs to be object
If not - please, consider adding this code to you functions.php
add_action( 'rest_api_init', 'salient_child_rest_api_init' );
function salient_child_rest_api_init() {
register_rest_route(
'namespace/v1',
'/example',
[
'methods' => WP_REST_Server::CREATABLE,
'callback' => 'salient_child_process_example_endpoint',
]
);
}
function salient_child_process_example_endpoint() {
// your logic ...
$data = [
'pid' => 1
]; // example data for testing if it is working
return new WP_REST_Response( $data, 200 );
}
And change your jQuery.post with this
jQuery.post(
{
url: `${document.location.origin}/wp-json/namespace/v1/example`,
data: {
'action': 'do_ts_woo',
'order': orderfilename,
'tilesize': globalTileSize,
'board': urlAtts,
'table': table
},
xhrFields: {
withCredentials: true
}
})
.done(function (data) {
const pid = data.pid;
if (pid > 0) {
console.log("do_ts_woo. SUCCESS response=" + pid);
alert('Add to cart: ' + response.id);
ts_iframe(shopdomain + "/cart/?add-to-cart=" + pid);
} else {
console.log("do_ts_woo. FAILURE response=" + response.id);
}
return false;
})
.fail(function (msg) {
alert("error msg=" + msg);
})
.always(function (response) {
});
If not - maybe there are PHP warnings modifying your response output with enexpected messages and breaking your response data.

Refreshing a List Sent From a Controller When Posting Data to DB Using Ajax

I'm trying to add functionality where users can add items to a cart without refreshing the page using Ajax. I succeeded while posting data to the database, but I can't refresh the list automatically (after the data gets posted).
Ajax
jQuery(document).ready(function(){
jQuery("#addtocartt{{$one->id}}").on('click',function(e){
e.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
jQuery.ajax({
url: "/addtocart",
method: 'post',
data: {
data: jQuery("#name{{$one->id}}").val(),
image: jQuery("#image{{$one->id}}").val(),
price: jQuery("#price{{$one->id}}").val(),
quantity: jQuery("#quantity{{$one->id}}").val(),
},
success: function(result){
var xs = result.qte;
swal(xs+"Kgs of {{$one->name}}", "Is Added to Cart !!", "success");
}});
});
});
Here's my list that I want to be refreshed.
#foreach($list as $one)
<text style="font-family: Poppins-ExtraLight;"> {{$one->cart_item}} : {{$one->quantity}} x {{$one->cart_price}} dh = {{$one->quantity*$one->cart_price}}</text> <br>
#endforeach
Controller
function Add(Request $request){
$item = new cart;
$item->user_id = Auth::user()->id;
$item->cart_number = '0';
$item->cart_item = $request->data;
$item->quantity = $request->quantity;
$item->cart_price = $request->price;
$item->image = $request->image;
$item->save();
$list= cart::all()->where('user_id',Auth::user()->id)->where('state','=','delivering');
return response()->json(['qte' => $item->quantity]);
}
I have not tested this but assuming $list variable returns the cart, you could do something like this:
Your blade template
<div id="some-list-container">
#foreach($list as $one)
<text style="font-family: Poppins-ExtraLight;"> {{$one->cart_item}} : {{$one->quantity}} x {{$one->cart_price}} dh = {{$one->quantity*$one->cart_price}}</text> <br>
#endforeach
</div>
Your Controller
return response()->json(['list' => $list, 'item' => $item]);
Your Javascript
...
success: function(result) {
var item = result.item;
var list = result.list;
swal(item.quantity + "Kgs of " + item.name, "Is Added to Cart !!", "success");
// clear the list
jQuery("#some-list-container").empty()
// loop through the response list
for(var i=0; i < list.length; i++) {
// add to the list
var add_item = list[i];
jQuery("#some-list-container").append('<text style="font-family: Poppins-ExtraLight;"> '
+ add_item.cart_item + ' : '
+ add_item.quantity + ' x '
+ add_item.cart_price + ' dh = '
+ (add_item.quantity * add_item.cart_price)
+ '</text> <br>')
}
}
...
Hopefully that sets you on the right path

Laravel 5 with Select2, Loading data with ajax

first of all, here is my code so far.
My route:
Route::get('cities/citybylang/{lang_id}', [
'uses' => 'CitiesController#cityByLanguage',
'as' => 'dashboard.cityByLanguage'
]);
My controller:
public function cityByLanguage($lang_id){
$cities = City::select('name','id')->where('lang_id',$lang_id)->get();
return $cities;
}
My view select
<select class="js-data-example-ajax">
<option value="3620194" selected="selected">select2/select2</option>
</select>
My Select2 code
$(".js-data-example-ajax").select2({
ajax: {
url: "/dashboard/cities/citybylang/1",
dataType: 'json',
delay: 250,
data: function (params) {
console.log(params.term);
return {
q: params.term, // search term
page: params.page,
name: params.name
};
},
beforeSend: function(jqXHR, settings) {
console.log(settings.url);
},
processResults: function (data, page) {
console.log(data);
// parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to
// alter the remote JSON data
return {
results: data
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 1,
templateResult: formatRepo, // omitted for brevity, see the source of this page
templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
});
});
function formatRepo (repo) {
if (repo.loading) return repo.text;
var markup = '<div class="clearfix">' +
'<div clas="col-sm-10">' +
'<div class="clearfix">' +
'<div class="col-sm-6">' + repo.name + '</div>' +
'<div class="col-sm-3"><i class="fa fa-code-fork"></i> ' + repo.name + '</div>' +
'<div class="col-sm-2"><i class="fa fa-star"></i> ' + repo.name + '</div>' +
'</div>';
if (repo.name) {
markup += '<div>' + repo.name + '</div>';
}
markup += '</div></div>';
return markup;
}
function formatRepoSelection (repo) {
return repo.name || repo.text;
}
Okey, the basic problem is, i can't pass the right parameter to the controller.
This is how this work now: I start typing to the select field and it give a list with the cities which has the lang_id = 1.
So the ajax call send this to the controller:
somthing.com/dashboard/cities/citybylang/1?q=[value, what i type to the select field]
I have pretty url, so i want something like this:
somthing.com/dashboard/cities/citybylang/[value, what i type to the select field]
So the question is, how can i pass parameter to the controller in the right way?
This question is old but I was looking for same thing that's how I manged it.
url: function(params) {
return '/some/url/' + params.term;
},
Here is reference link
https://select2.github.io/options.html

Delete record without a page refresh with ajax in php

I am working on a Cakephp 2.x but I don't think the problem has anything to do with the Cakephp. I want to delete a file without a page refresh.
HTML / PHP :
<div class = "success" style="display:none;">Deleted successfully </div>
<div class = "error" style="display:none;">Error </div>
JavaScript :
function openConfirm(filename, idImage) {
$.modal.confirm('Are you sure you want to delete the file?', function () {
deleteFile(filename, idImage);
}, function () {
});
};
function deleteFile(filename, idImage) {
var filename = filename;
$.ajax({
type: "POST",
data: {
idImage: idImage
},
url: "http://localhost/bugshot/deleteFile/" + filename,
success: function (data) {
if (data == 1) {
$(".success").fadeIn(500).delay(2000).fadeOut(500);
} else {
$(".error").fadeIn(500).delay(2000).fadeOut(500);
}
},
error: function () {
alert("error");
}
});
}
my images which is in foreach loop
this code is displaying the image
foreach($file as $files):?>
<?php $downloadUrl = array('controller' => 'bugshot', 'action' => 'downloadImages', $files['Image']['filename'], '?' => array('download' => true));
$imageUrl = array('controller' => 'bugshot', 'action' => 'downloadImages', $files['Image']['filename']);
?>
<?php echo $this->Html->link(
$this->Html->image($imageUrl),
$downloadUrl,
array('class' => 'frame', 'escape' => false)
);?>
Delete link
The code works great except that after the image or record is deleted the record/image is still displayed on the page until it is refreshed. How do I fix this?
You need to remove it with javascript.
$.ajax({
...
success: function (data) {
if (data == 1) {
$(".success").fadeIn(500).delay(2000).fadeOut(500);
$('img[src="/pathToImg/' + filename + '"]').remove(); // Remove by src
// $('#' + idImage).remove(); // Remove by ID.
} else {
$(".error").fadeIn(500).delay(2000).fadeOut(500);
}
}
...
});
Note : var filename = filename; means nothing because you are assigning filename argument to a new variable with the same name. You can just remove it.

Options not getting added again when the form is submitted +zendFramework

i have to dependent combo box
$this->addElement('Select', 'Category',array(
'label' => 'Category:',
'AutoComplete'=> true,
'multiOptions' => array('0' => '-Category-',$a->GetCategories(),'2' => '-Add category-'),
'required' => true ));
$this->addElement('Select', 'SubCategory',array(
'label' => 'Sub Category:',
'AutoComplete'=> true,
//'multiOptions' => array('0' => '-Select Category-'),
'required' => true ));
the second one is filled using ajax
<script type="text/javascript">
//for send data i'll use jquery library
$(document).ready( function(){
$('#Category').change(function() {
var message=$('#Category option:selected').text();
if (message != '') {
$.ajax({
type: "GET",
dataType : 'json',
url: 'http://localhost/EverTags1/Authentification1/public/Product/add',
async: false,
data:{"message" : message},
success: function (respond) {
var json=JSON.stringify(respond);
var objet = eval('(' + json + ')');
e=objet.length;
var str = "";
for ( var count = 0 ; count < e; count++ ) {
str += "<option value='" + count + "'>" + objet[count].name+ "</option>"
}
$("#SubCategory").empty().append(""+str);
}
});
}
});
});
</script>
The elements were loaded correctly in the second combobox. But when I submitted the content of the second combobox disappears. how can i make them displayed
you need to update multioptions after each ajax request. i used session to do that
public function getsubcategoriesAction()
{
if($this->_request->isXmlHttpRequest())
{
$session = new Zend_Session_Namespace('mySession');
$this->getRequest()->param('id',1)
$model = new Application_Model_DbTable_Subcategory();
$result = $model->getSubcategories($category);
// save the result to session
$session->result = $result;
$this->_helper->json($result);
}
}
and in the action that render the form
public function createAction()
{
//some code here
if($this->getRequest()->isPost()){
$session = new Zend_Session_Namespace('mySession');
$subCategory = $form->getelement('subCategory');
$subCategory->addMultiOptions($session->result); // get the result back from session
//some code here
}
}
you need also to enable sessions in you application.ini
resources.session.save_path = APPLICATION_PATH "/../data/session"
resources.session.use_only_cookies = true
resources.session.remember_me_seconds = 864000
Does adding the selected='selected' attribute to the first option of #SubCategory fix it?

Categories