here is my code:
$.ajax({
type: "POST",
url: '<?php echo base_url();?>index.php/profile/add_jobs',
datatype: "json",
traditional: true,
data: {json:JSON.stringify(all_publication)},
success: function (response) {
console.log(response);
$('.all').html('');
}});return false; //disable refresh
and the all_publication is an array containing values,
in controller I put this code:
public function add_jobs()
{
echo ($_POST['json']);
foreach ($_POST['json'] as $key => $value) {
$data[] = array('name'=>$value['pub_name'],'details'=>$value['pub_details'],'date_time'=>$value['pub_date']);
}
$this->profile_model->insert_publication($data);
}
But appeared to me this message "Invalid argument supplied for foreach()"
please show me a way for my problem.
You don't need to stringify your array. Try:
data: {json : all_publication},
Use json_decode with second parameter as true (for getting output as array) before passing it to foreach loop
So revised code looks like
public function add_jobs()
{
echo ($_POST['json']);
$postArray=json_decode($_POST['json'], true); // Decoding json to array
foreach ($postArray as $key => $value) {
$data[] = array('name'=>$value['pub_name'],'details'=>$value['pub_details'],'date_time'=>$value['pub_date']);
}
$this->profile_model->insert_publication($data);
}
Related
I'm using laravel 8.4 .
My route :
Route::post('test',[\App\Http\Controllers\DataController::class, 'store'])->name('pos-test');
My Controller :
public function store(Request $request)
{
// DB::table('data')->insert('product_code',$request->id);
$badge = explode(' ', $request);
$employee_id = $badge[0];
\DB::table('data')->insert(['product_code'=> $employee_id]);
return response()->json(['success'=>'Product saved successfully.']);
}
Ajax code :
function handleBarcode(scanned_barcode) {
//handle your code here....
console.log(scanned_barcode);
let _token = $('meta[name="csrf-token"]').attr('content');
event.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: "{{ route('pos-test') }}",
type: "POST", // Can change this to get if required
data: {
code : scanned_barcode,
_token: _token
},
success: function(data) {
$("#status").html(data);
},
error: function(jqXHR, textStatus, errorThrown) {
$("#status").text(textStatus);
console.log(jqXHR);
}
});
};
The request is like this "555444 Razif Raziq" , i would like to explode it so I may insert only "555444" into table but in table column product_code is 'POST' .
The question is how to fix it? thank you
you must explode your correct data in request object not request object itself.
$badge = explode(' ', $request->code);
If the 'code' value is sent correctly, just use this
$request->code
public function store(Request $request)
{
\DB::table('data')->insert(['product_code'=> $request->code]);
return response()->json(['success'=>'Product saved successfully.']);
}
I have an ajax where it passes the array of arrays or multidimensional/2 dimensional array and when I passed it to controller to model, I need to do a Foreach inside a function so that I can get the $this->input->post('distance'); but I don't know how can I print the array of arrays in the model or get the array of arrays so that I can do a Foreach.
here is my ajax:
$.ajax({
url: url + 'getBookTours',
type: 'POST',
data: data,
success: function(data, textStatus, jqXHR) {
swal("Booked!", "", "success");
},
error: function(jqXHR, textStatus, errorThrown) {
swal("Save Error!", "", "error");
}
});
and in my controller:
public function getBookTours(){
$record = $this->mdl->bookTours();
$this->output->set_output(json_encode($record));
}
and in my model:
public function bookTours(){
$info = array (
'total_price' => $this->input->post('fare'),
'total_distance_km' => $this->input->post('distance'),
'status' => 1,
'ip' => $this->getUserIP(),
'booked' => $time,
);
return $info;
}
Do you mean array of objects ?
[{'total_price':636 .....},{'total_price':8484....}]
Fisrt convert you array to JSON
var json = JSON.stringify(your_array);
Change the ajax to following
data: {data : json},
In the php
$data = json_decode($this->input->post("data"),true);
foreach($data as $obj){
//now you can access
echo $obj["total_price"];
}
I want to insert some ajax post data into database. But when I'm clicking submit, no data is being inserted.
view(header.php)
$(function(){
$(".submit").click(function(){
transaction_student_id=$(".student_id").val();
transaction_particular_name=$(".particular_name").val();
transaction_id=$(".transaction_id").val();
jQuery.ajax({
type: "POST",
url: "<?php echo base_url().'user/add_transaction'; ?>",
dataType: 'json',
data: {transaction_student_id: transaction_student_id,transaction_particular_name:transaction_particular_name,transaction_id:transaction_id},
success: function(data) {
}
});
});
});
Controller (User.php)
public function add_transaction()
{
$columns_and_fields = array('transaction_id','transaction_particular_name','transaction_student_id');
foreach ($columns_and_fields as $key)
$data[$key]=$this->input->post($key);
$query=$this->Mdl_data->insert_transaction($data);
if($query)
redirect('User','refresh');
}
Model (Mdl_data.php)
public function insert_transaction($data=array())
{
$tablename='transaction';
$query=$this->db->insert($tablename,$data);
return $query;
}
First of all, declare the variable in JavaScript with keyword var
var transaction_student_id=$(".student_id").val();
Before starting the Ajax use console.log() to know if the variables have data or not
The second thing is you are not getting the data with right way in the controller
Try like this
public function add_transaction()
{
$columns_and_fields = array('transaction_id' = $this->input->post('transaction_id'),
'transaction_particular_name' => $this->input->post('transaction_particular_name'),
'transaction_student_id' => $this->input->post('transaction_student_id'));
$query=$this->Mdl_data->insert_transaction($columns_and_fields);
if($query){
redirect('User','refresh');
}
}
Don't use the extra line of code without any reason
public function insert_transaction($data = array())
{
return $this->db->insert('transaction', $data);
}
Try debugging your code first.
Do you get all the data in controller? Try to dump POST values var_dump($_POST) in controller if ajax is successfully sending the data.
From there, you can see if the data in successfully sent from the front end.
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>user/add_transaction",
dataType: 'json',
data: {
transaction_student_id: transaction_student_id,
transaction_particular_name: transaction_particular_name,
transaction_id: transaction_id
},
success: function( data ) {
console.log( data );
},
error: function( xhr, status ) {
/** Open developer tools and go to the Console tab */
console.log( xhr );
}
});
change it
$(function(){
$(".submit").click(function(){
transaction_student_id=$(".student_id").val();
transaction_particular_name=$(".particular_name").val();
transaction_id=$(".transaction_id").val();
jQuery.ajax({
type: "POST",
url: "<?php echo base_url().'user/add_transaction'; ?>",
dataType: 'json',
data: {transaction_student_id: transaction_student_id,transaction_particular_name:transaction_particular_name,transaction_id:transaction_id},
success: function(data) {
alert(data + ' id added' );
window.location.reload(); // force to reload page
}
});
});
});
at controller
public function add_transaction()
{ // use it only for ajax call or create another one
$columns_and_fields = array();
// 'transaction_id','transaction_particular_name','transaction_student_id'
foreach ($_POST as $key)
{
array_push($columns_and_fields , array(
'transaction_student_id' => $key['transaction_student_id'],
'transaction_particular_name'=>$key['transaction_particular_name'],
'transaction_id'=>$key['transaction_id']
)
);
}
$this->Mdl_data->insert_transaction_array($columns_and_fields);
}
and at model create new method
public function insert_transaction_array($data=array())
{
$tablename='transaction';
$this->db->insert_batch($tablename,$data);
}
I need help: I do not know how to edit two tables of the database from the same form. I'm using cakephp3.
I'm trying to use ajax
Thanks for your help
Data to save in a different driver, there the script
This script is in a controller called carsController
**<script type="text/javascript">**
function editarCliente(a, b ){
var parametros = {
"clasificacionC" :a,
"descripcion": b,
};
$.ajax({
data: parametros,
url: '<?php echo router::url(array('controller'=>'Clientes','action'=>'editarcliente',$cliente->id));?>',
type: 'post',
dataType: 'json',
success: function (response) {
$("#nomCliente").val(response.uno+" "+response.dos);
$("#telCliente").val(response.tres);
$("#celCliente").val(response.cuatro);
}
});
}
**</script>**
This method is in a controller called clientesController.
public function editarcliente($id = null)
{
$cliente = $this->Clientes->get($id, [
'contain' => []
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$cliente->clasifi_cliente=$_POST("clasificacionC");
$cliente->descripcion=$_POST("descripcionC");
if ($this->Clientes->save($cliente)) {
$this->Flash->desactivar(__('Cliente desactivado'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The cliente could not be saved. Please, try again.'));
}
}
$this->set(compact('cliente'));
$this->set('_serialize', ['cliente']);
}
So basically I have a two item array in javascript that is generated based on which link the user clicks. I am trying to send this array to my controller, and then to the model. The model will look at the array and match one of the items to a certain column/row, and will selectively display data.
I am having issues passing the data from AJAX to my controller.
AJAX code (in a .js file)
$('#youmax-video-list-div').append('<div id="testing1"></div>');
$('#concept').click(function(){
console.log(course);
$.ajax({
url: 'http://localhost:8888/index.php/trial/getValues',
type:'POST',
dataType: 'json',
data:'',
error: function(){
$('#testing1').append('<p>goodbye world</p>');
},
success: function(result) {
var htmlStr = '';
$.each(result, function(a, b){
htmlStr += b.qText + '<br />';
});
$('#testing1').append(htmlStr);
} // End of success function of ajax form
}); // End of ajax call
});
I am assuming I must do something with the data field, but I dont know the syntax for it.
The console log in chrome comes up with this:
Array[2]
0: "PL8G0kdHFfE3WuyevUDvwSYCZw8mp8LBFA"
1: "PL8G0kdHFfE3V62Jp2ju-PelOaNUkH7xR8"
Controller
function getValues(){
$this->load->model('get_db');
$data = $this->get_db->getAll();
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode($data));
return $data;
}
Model
class Get_db extends CI_Model{
function getAll(){
$query=$this->db->query("SELECT * FROM questions");
return $query->result();
//returns from this string in the db, converts it into an array
}
}
As I said before, I am really only concerned with getting the data to my controller and my model.
The name of the array is "course". However, that doesnt appear to be so in the console.log. Is that just something chrome does?
// chkval be the class for elements for the arrays
AJAX function:
function ajaxSub(goals)
{
var theArray = new Array();
var i=0;
jQuery('.chkval').each(function(){
if(jQuery(this).prop('checked'))
{
theArray[i] = jQuery(this).val();
i++;
}
});
jQuery.ajax({
url: '<?php echo site_url('mycontroller/myfunctions');?>',
type: 'post',
data: {
arr: theArray,
other_id: ''
},
datatype: 'json',
success: function () {
}
});
}
in the controller:
$arr = $this->post('arr');
foreach($arr as $ar)
{
echo $ar; // prints each element of the array.
}
Same as above answer but in controller run this code:
$arr = $this->input->post('arr');
foreach($arr as $ar)
{
echo $ar; // prints each element of the array.
}