Associative array not an array when passed to controller thru AJAX - javascript

I'm trying to pass this array var data_array into my controller thru AJAX
This is the value of var data_array when I use alert(JSON.stringify(data_array));
This is my AJAX method
var project_details = $.extend({}, data_array);
$.ajax({
type: "POST",
url: "<?php echo base_url('PPMP_controller/submitPPMP'); ?>",
data: { data_array : $.param(project_details) },
dataType: 'json',
success: function(data) {
alert('PPMP submission success!');
alert(data);
},
error: function(errorw) {
console.log(errorw);
}
});
This is my PPMP_controller
public function submitPPMP(){
$data_array = $this->input->post('data_array');
$value = $this->PPMP_model->submitPPMP($data_array);
echo json_encode($value);
}
This is my model
function submitPPMP($data_array){
$date_format = 'DATE_W3C';
$date_submitted = standard_date($date_format);
$data = array(
'user_id' => 1,
'date_submitted' => $date_submitted,
'first_lvl_status' => 0,
'second_lvl_status' => 0,
'third_lvl_status' => 0,
'fourth_lvl_status' => 0,
'submitted' => 1
);
$this->db->insert('project', $data);
$id = $this->db->insert_id();
if(is_array($data_array) || is_object($data_array)){
return "yes";
foreach($data_array as $object){
$project_details = array(
'project_id' => $id,
'supply_id' => $object->supply_id,
'supply_description' => $object->supply_description,
'quantity' => $object->quantity,
'price' => $object->price,
'jan' => $object->jan,
'feb' => $object->feb,
'mar' => $object->mar,
'apr' => $object->apr,
'may' => $object->may,
'jun' => $object->jun,
'jul' => $object->jul,
'aug' => $object->aug,
'sep' => $object->sep,
'oct' => $object->oct,
'nov' => $object->nov,
'dec' => $object->dec
);
$this->db->insert('project_details', $project_details);
}
}
else{
return "no";
}
return $this->db->last_query();
}
However the array passed from controller to model is not an array since it doesn't go thru the line if(is_array($data_array) || is_object($data_array)) instead it goes to the else condition and return "no".
What might be causing this array not being passed an array from controller to model. Thank you for the help. I am using Codeigniter 3.0 as an MVC framework.

you are passing json to your model not array , when it comes to your model it should be ,
try var_dump($data_array) to check its data type i.e json or object or array
$data_array = json_decode($data_array); // to get object
$data_array = json_decode($data_array,true); // to get array
Your PPMP_controller should be
public function submitPPMP(){
$data_array = $this->input->post('data_array');
$data_array = json_decode($data_array);
$value = $this->PPMP_model->submitPPMP($data_array);
echo json_encode($value);
}

Related

How to return a string that only has a special value of text that has been set?

I have data like the image above. However, in the "Bahan-bahan" column, I only want to display the values ​​in the predefined custom values ​​below.
<?php
return [
'shopping_list' => [
'1' => 'Ikan Bawal',
'2' => 'Udang Segar',
'3' => 'Daging Ayam',
'4' => 'Daging Sapi',
],
];
?>
How to make this using PHP Laravel or javascript?
Following this, the code I have created using Laravel 7.
public function index(Request $request)
{
$payment_method = PaymentMethod::Where('payment_type', 1)->get();
if (request()->ajax()) {
$category = Category::find(6);
$orders = $category->products()
->withCount([
'orderSummaries as order_count' => function ($query) {
$query->whereHas('order', function (Builder $query) {
$query->where('order_status', 2);
});
}
])
->whereHas('orderSummaries', function (Builder $query) {
$query->whereHas('order', function (Builder $query) {
$query->where('order_status', 2);
});
})
->get();
return DataTables::of($orders)
->addIndexColumn()
->editColumn('ingredient', function($item) {
$text = \Str::between($item->description, 'Bahan-bahan:','Cara Membuat');
return nl2br($text);
})
->rawColumns(['name','order_count', 'ingredient'])
->make(true);
}
return view('admin.marketplace.shoppingList.index',[
'title' => 'Belanja',
'subtitle' => 'Daftar Belanja',
'payment_method' => $payment_method,
]);
}

Uncaught TypeError: a.getElementsByClassName is not a function with Ajax

I am creating an E-commerce web application In frontend I am using a template and in backend I am using Laravel 8, I need to post AddToCart data with ajax, but when I click AddToCar button I get and error
'Uncaught TypeError: a.getElementsByClassName is not a function'
My button
<button type="submit" class="btn btn-primary mb-2" onclick="addToCart">Add to Cart</button>
Ajax code
//Start Add to Cart Product
function addToCart(){
var product_name = $('#pname').text();
var id =$('#product_id').val();
var color = $('#color option:selected').text();
var size = $('#size option:selected').text();
var quantity =$('#qty').val();
$.ajax({
type:"POST",
datatype:'json',
data:{
color:color,
size:size,
quantity:quantity,
product_name:product_name,
},
url:"/cart/data/store/"+id,
success:function(data){
console.log(data);
}
})
}
My controller
public function AddToCart(Request $request, $id){
$product = Product::findOrFail($id);
if ($product->discount_price == NULL) {
Cart::add([
'id' => $id,
'name' => $request->product_name,
'qty' => $request->quantity,
'price' => $request->selling_price,
'weight' => 1,
'options' => [
'image' => $request->product_thambnail,
'color' => $request->color,
'size' => $request->size,
],
]);
return response()->json('Successfuly Added on Your Cart');
}else{
Cart::add([
'id' => $id,
'name' => $request->product_name,
'qty' => $request->quantity,
'price' => $request->discount_price,
'weight' => 1,
'options' => [
'image' => $request->product_thambnail,
'color' => $request->color,
'size' => $request->size,
],
]);
return response()->json('Successfuly Added on Your Cart');
}
}
First of all, there are some things we can get better on the function like using const instead of var and not defining two times the variable on the object as they have the same name.
function addToCart() {
const id = $('#product_id').val();
const product_name = $('#pname').text();
const color = $('#color option:selected').text();
const size = $('#size option:selected').text();
const quantity = $('#qty').val();
$.ajax({
type:"POST",
datatype:'json',
data: {
color, size, quantity, product_name,
},
url: `"/cart/data/store/"${id}`,
success: console.log
});
}
Anyways, your main issue is an error that is not related or visible in your code as you are using a library/framework (in this case, seems like jquery). You gotta check the stacktrace to see what part of YOUR code is triggering the error. Maybe is not even on this snippets you're sharing here.

Controller API return to Ajax a response with a status 200 but an empty array

I am totaly stuck with an Ajax request. I m trying to send a response to Ajax with an encoded array to json. Ajax get a status 200 response, but only strings are sent ; not my variables.
I wonder if the probleme is due to the asynchronous... When I test with Postman, i can see the full response but Js give to me : {"recipies":[]}.
Thanks for your help.
Ajax :
searchByIngredients: function () {
console.log('Search for recipies');
var array = [];
var ingredients = $('.span-ingredient');
ingredients.each(function () {
array.push(this.innerHTML);
});
console.log(array);
console.log(Array.isArray(array));
$.ajax(
{
url: Routing.generate('shopping_list_by_ingredients_ajax'),
type: "POST",
contentType: "application/json",
dataType: "json",
data: JSON.stringify(array)
}).done(function (response) {
if (null !== response) {
console.log('ok : ' + JSON.stringify(response));
console.log(typeof(response));
} else {
console.log('Error');
}
}).fail(function (jqXHR, textStatus, error) {
console.log(jqXHR);
console.log(textStatus);
console.log(error);
});
}
};
Controller :
/**
* #Route("/by-ingredient-ajax", name="shopping_list_by_ingredients_ajax", options={"expose"=true}, methods={"GET","POST"})
*
* #return JsonResponse|Response
*/
public function createShopplistByIngredientsAjax(Request $request, RecipeIngredientRepository $recipeIngredientRepository, RecipeRepository $recipeRepository)
{
if ($request->isMethod('POST')) {
$dataIngredients = json_decode($request->getContent());
$dataIngredients = $request->getContent();
// Sorry for this :/
$arrayIngredients = explode(', ', $dataIngredients);
$text = str_replace("'", '', $arrayIngredients);
$text2 = str_replace('[', '', $text);
$text3 = str_replace(']', '', $text2);
$recipiesArray = [];
// Get matching RecipeIngredient
foreach ($text3 as $data) {
/**
* #return RecipeIngredient()
*/
$recipeIngredients = $recipeIngredientRepository->findBy([
'name' => $data,
]);
foreach ($recipeIngredients as $recipeIng) {
$name = $recipeIng->getName();
$recipeNames = $recipeRepository->findRecipeByKeywwords($name);
foreach ($recipeNames as $recipeName) {
/**
* #return Recipe()
*/
$recipies = $recipeRepository->findBy([
'id' => $recipeIng->getRecipe(),
]);
// Built array with names & ids of recipies
foreach ($recipies as $key => $recipe) {
$recipeName = $recipe->getName();
$recipeId = $recipe->getId();
$recipiesArray[] = ['name' => $recipeName];
$recipiesArray[] = ['id' => $recipeId];
}
}
}
}
$response = new Response();
$response->setContent(json_encode([
'recipies' => $recipiesArray,
]));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
return new Response(
'Something wrong...',
Response::HTTP_OK,
['content-type' => 'text/html']
);
Repository :
/**
* #return Recipe[] Returns an array of Recipe objects
*/
public function findRecipeByKeywwords($value)
{
return $this->createQueryBuilder('r')
->andWhere('r.name LIKE :val')
->setParameter('val', '%'.$value.'%')
->orderBy('r.id', 'ASC')
->setMaxResults(10)
->getQuery()
->getArrayResult();
}
composer require jms/serializer-bundle
After you have installed the package, you just need to add the bundle to your AppKernel.php file:
// in AppKernel::registerBundles()
$bundles = array(
// ...
new JMS\SerializerBundle\JMSSerializerBundle(),
// ...
);
The configured serializer is available as jms_serializer service:
$serializer = $container->get('jms_serializer');
$json=$serializer->serialize(['recipies' => $recipiesArray], 'json');
return new JsonResponse($json,200);
Symfony 2.1
$response = new Response(json_encode(array('recipies' => $recipiesArray)));
$response->headers->set('Content-Type', 'application/json');
return $response;
Symfony 2.2 and higher
You have special JsonResponse class, which serialises array to JSON:
use Symfony\Component\HttpFoundation\JsonResponse;
//
//
return new JsonResponse(array('recipies' => $recipiesArray));
https://symfony.com/doc/current/components/http_foundation.html

DataTable column is showing object and not displaying actually value?

I am trying to populate DataTable with my Data but DataTable is showing object in columns and not printing the actual values!
Function in Controller:
public function getEvaluationSymptomsAction() {
//Get Evaluation Symptoms from DataBase
$evaluation_symptoms = CxEbEvaluationSymptom::getAllEvaluationSymptomsWithNameForDataTable();
$inferredRemedies = array();
$additonalRemedies = array();
$data = array();
foreach ($evaluation_symptoms as $key => $symptom) {
$data[ $key ][ 'id' ] = $symptom[ 'id' ];
$data[ $key ][ 'title' ] = $symptom[ 'title' ];
// Get Inferred Remedies By Symptom ID
$inferredRemedies = CxEbEvaluationSymptom::getInferredRemediesBySymptomId($symptom[ 'id' ]);
$additonalRemedies = CxEbEvaluationSymptom::getAdditionalSymptomRemediesBySymptomId($symptom[ 'id' ]);
$data[ $key ][ 'remedy' ] = $inferredRemedies;
$data[ $key ][ 'additional-remedy' ] = $additonalRemedies;
$data[ $key ][ 'date_created' ] = $symptom[ 'date_created' ];
}
//print_r($data);exit;
// Return data array
return array('data' => $data);
// Return data
}
The above function return the below array: (NOTE the below array is var_dump version actually data is in JSON format)
Array code is here
Queries:
public static function getInferredRemediesBySymptomId($symptomId){
$queryBuilder = new Builder();
return $queryBuilder
->from(array('es' => 'Cx\EbFront\Models\Evaluation\CxEbEvaluationSymptom'))
->leftJoin('Cx\EbFront\Models\Evaluation\CxEbEvaluationSymptomCause', 'es.id = esc.evaluation_symptom_id','esc')
->leftJoin('Cx\EbFront\Models\Evaluation\CxEbEvaluationCause','esc.evaluation_cause_id = ec.id','ec')
->leftJoin('Cx\EbFront\Models\Evaluation\CxEbEvaluationCauseRemedy','ec.id = ecr.evaluation_cause_id','ecr')
->leftJoin('Cx\EbFront\Models\Evaluation\CxEbEvaluationRemedy','ecr.evaluation_remedy_id = er.id', 'er')
//->leftJoin('Cx\EbFront\Models\Evaluation\CxEbEvaluationSymptom', 'es.id = :ID:', 'es')
->columns('er.id, er.title')
->where('es.is_active = 1')
->andWhere('es.id = :ID:')
->getQuery()
->execute(array('ID' => $symptomId))
//->execute()->setHydrateMode(Resultset::HYDRATE_ARRAYS)
->toArray();
}
/**
* A
* Data for column Additonal Remedies in DataTable
* #return array
*/
public static function getAdditionalSymptomRemediesBySymptomId($symptomId){
$queryBuilder = new Builder();
return $queryBuilder
->from(array('er' => 'Cx\EbFront\Models\Evaluation\CxEbEvaluationRemedy'))
->innerJoin('Cx\EbFront\Models\Evaluation\CxEbEvaluationSymptomRemedy', 'er.id = esr.evaluation_remedy_id','esr')
->columns('er.id, er.title')
->where('er.is_active = 1')
->andWhere('esr.evaluation_symptom_id = :ID:')
->getQuery()
->execute(array('ID' => $symptomId))
->toArray();
}
The below is the JS code for initializing the DataTable:
function EbEvaluationSymptom(){
var $body = $('body');
var $CxRecordsTable = $('#cx-records-table');
// Init the DatTable using the Cx Admin DataTable plugin
cx.common.data.cxAdminDataTables.EbEvaluationSymptom = $CxRecordsTable.cxAdminDataTable({
ajaxUrl: '<?php echo $this->CxHelper->Route('eb-admin-get-evaluation-symptoms')?>',
columns: [
cx.common.admin.tableEditColumn('id'),
{ data: 'title' },
{ data: 'remedy' },
{ data: 'additional-remedy' },
{ data: 'date_created' }
],
});
};
JSON Response:
https://pastebin.com/g2mhhS4D
DataTables doesn't know how to format the array of object(s) supplied for remedy & additional-remedy.
Assuming there is always one object in each of those arrays, you want to access the first object in each array and use its title property:
columns: [
cx.common.admin.tableEditColumn('id'),
{ data: 'title' },
{ data: 'remedy.0.title' },
{ data: 'additional-remedy.0.title' },
{ data: 'date_created' }
],
If you plan to have more than 1 element in each array, you'll need a different approach

ajax function outputs a "0" when I use die() at the end

I have a php page that is making a couple of ajax calls. The first ajax call is made and on success it activates a second ajax function. Each function has die() at the end. No matter what I do, die() keeps outputting a "0" to the screen. I tried commenting the die() out of the first ajax function, but it never processes the ajax request when I do that. The loading gif just keeps spinning. When I comment out the die() in the second function, it outputs "0" twice. I have no clue why it keeps printing that to the screen.
This is the first function.
function json_info() {
// The $_REQUEST contains all the data sent via ajax
if ( isset($_REQUEST) ) {
// create a new array to store projects
$projectsArray = array();
// get values for all three drop-down menus
$status = $_REQUEST['status'];
$industry = $_REQUEST['services'];
$state = $_REQUEST['state'];
// array of values for earch of the three drop-downs
$statusAll = array('complete','incomplete');
$industryAll = array('mining','textile','construction');
$statesAll = array('sc','tx','wa');
// set $statusArray dependent on whether or not "all" is selected
if($status == "all") {
$statusArray = array( 'key' => 'status', 'value' => $statusAll, 'compare' => 'IN');
} else {
$statusArray = array( 'key' => 'status', 'value' => $status, 'compare' => '=');
}
if($industry == "all") {
$industryArray = array( 'key' => 'industry', 'value' => $industryAll, 'compare' => 'IN');
} else {
$industryArray = array( 'key' => 'industry', 'value' => $industry, 'compare' => '=');
}
if($state == "all") {
$stateArray = array( 'key' => 'state', 'value' => $statesAll, 'compare' => 'IN');
} else {
$stateArray = array( 'key' => 'state', 'value' => $state, 'compare' => '=');
}
$pages = array(
'post_type' => 'page',
'orderby' => 'title',
'order' => 'ASC',
'paged' => $paged,
'posts_per_page' => 5,
'meta_query' => array(
'relation' => 'AND',
$statusArray,
$industryArray,
$stateArray,
array(
'key' => '_wp_page_template',
'value' => 'template-individual-project.php',
'compare' => '='
)
)
);
// query results by page template
$my_query = new WP_Query($pages);
$projectsArray = array();
if($my_query->have_posts()) :
while($my_query->have_posts()) :
$my_query->the_post();
$image = get_field('project_photo');
$image = $image['sizes']['thumbnail'];
$projectsArray[] = array(
'title' => get_the_title(),
'lat' => get_field('latitude'),
'long' => get_field('longitude'),
'status' => get_field('status'),
'industry' => get_field('industry'),
'state' => get_field('state'),
'link' => get_permalink(),
'photo' => $image,
'num' => $paged
);
endwhile; endif;
wp_reset_query();
} // end of isset
?>
<?php
echo json_encode($projectsArray);
// Always die in functions echoing ajax content
die();
}
add_action( 'wp_ajax_json_info', 'json_info' );
add_action( 'wp_ajax_nopriv_json_info', 'json_info' );
And this is the second function:
function json_info2() {
// The $_REQUEST contains all the data sent via ajax
if ( isset($_REQUEST) ) {
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
// get values for all three drop-down menus
$status = $_REQUEST['status'];
$industry = $_REQUEST['services'];
$state = $_REQUEST['state'];
// array of values for earch of the three drop-downs
$statusAll = array('complete','incomplete');
$industryAll = array('mining','textile','construction');
$statesAll = array('sc','tx','wa');
// set $statusArray dependent on whether or not "all" is selected
if($status == "all") {
$statusArray = array( 'key' => 'status', 'value' => $statusAll, 'compare' => 'IN');
} else {
$statusArray = array( 'key' => 'status', 'value' => $status, 'compare' => '=');
}
if($industry == "all") {
$industryArray = array( 'key' => 'industry', 'value' => $industryAll, 'compare' => 'IN');
} else {
$industryArray = array( 'key' => 'industry', 'value' => $industry, 'compare' => '=');
}
if($state == "all") {
$stateArray = array( 'key' => 'state', 'value' => $statesAll, 'compare' => 'IN');
} else {
$stateArray = array( 'key' => 'state', 'value' => $state, 'compare' => '=');
}
$pages = array(
'post_type' => 'page',
'orderby' => 'title',
'order' => 'ASC',
'paged' => $paged,
'posts_per_page' => 5,
'meta_query' => array(
'relation' => 'AND',
$statusArray,
$industryArray,
$stateArray,
array(
'key' => '_wp_page_template',
'value' => 'template-individual-project.php',
'compare' => '='
)
)
);
// query results by page template
$my_query = new WP_Query($pages);
if($my_query->have_posts()) :
while($my_query->have_posts()) :
$my_query->the_post();
?>
<li class="group">
<?php the_title(); ?>
</li>
<?php
endwhile;endif;
wp_reset_query();
} // end of isset
?>
<?php
// Always die in functions echoing ajax content
die();
}
add_action( 'wp_ajax_json_info2', 'json_info2' );
add_action( 'wp_ajax_nopriv_json_info2', 'json_info2' );
And this is the ajax call to both functions:
function run_ajax() {
// Get values from all three dropdown menus
var state = $('#states').val();
var markets = $('#markets').val();
var services = $('#services').val();
// This does the ajax request
$.ajax({
url: ajaxurl,
data: {
'action' : 'json_info',
'state' : state,
'status' : markets,
'services' : services
},
success:function(data) {
// This outputs the result of the ajax request
var jsonData = JSON.parse(data);
do_ajax();
} /*,
error: function(errorThrown){
console.log(errorThrown);
}*/
}); // end of ajax call for json_info
function do_ajax() {
$.ajax({
url: ajaxurl,
data: {
'action' : 'json_info2',
'state' : state,
'status' : markets,
'services' : services
},
success:function(moredata) {
// This outputs the result of the ajax request
$('#project-list').html( moredata );
$('#project-list').fadeIn();
}/*,
error: function(errorThrown){
var errorMsg = "No results match your criteria";
$('#project-list').html(errorMsg);
}*/
}); // end of ajax call
} // end of function do_ajax
}
I'm not sure what I'm missing or doing wrong that is causing the "0" to print to the screen.
Well, it turns out that I'm an idiot, and I was just overlooking the problem. There was a third function called by ajax, and I didn't have die() at the end of it. I was thinking the issue was in my second function since the 0 was showing up in the div where I was printing that content.

Categories