How to post array to php using ajax in laravel - ajax

Bagaimana cara mengirim data dari array ke controller pada sebuah php? aku sudah mencoba menggunakan ajax. tapi hasil mengeluarkan ErrorException
Undefined index: genres.
This My Js
function publish(){
var genres = ["Romance", "Drama", "History"];
$.ajax({
type: "POST",
url: "/admin/movies/stores",
dataType:"json",
data: {'genres' : JSON.stringify(genres)},
contentType: "json",
});
}
this my controller
public function store(Request $request){
$input = $request->all();
$genres = ($_POST['genres']);
dd($genres);
dd($input);
}
my route
Route::post('/admin/movies/stores', 'App\Http\Controllers\PostController#store')->name('store');

When posting arrays to PHP, you use []
$.ajax({
type: "POST",
url: "/admin/movies/stores",
dataType:"json",
data: {'genres[]' : genres},
// contentType: "json", not json
});

Related

Unable to send value through Ajax in Codeigniter 4.1.3

I am using CodeIgniter 4.1.3 for a project. I am facing issue caching value in Controller through Ajax post. Codes are following:
$(document).on('click','#showCont', function(){
var memID=$(this).attr('data-mem');
$data = {memID: memID};
//console.log($data);
$.ajax({
url: "<?=base_url();?>"+"/Member/getContact/",
headers: {'X-Requested-With': 'XMLHttpRequest'},
type: "POST",
data: $data,
cache: false,
success: function (cont) {
console.log(cont);
}
});
});
And here is the Controller:
<?php
namespace App\Controllers;
use App\Controllers\BaseController;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use App\Models\Project_model;
use App\Models\General_model;
use CodeIgniter\I18n\Time;
class Member extends BaseController {
public function getContact(){
if ($this->request->isAJAX()) {
// echo "Hi"; printing Hi in console
//echo $query = $this->request->getPost('memID'); // returning nothing
print_r($_REQUEST);
}
}
And the route:
$routes->post('Member/getContact)', 'Member::getContact');
Below is the response of print_r in console.log
Array
(
[__tawkuuid] => e::xxxdomainxxx.com::FtBr5/am9LXZ8gvI7KxyHJZ279zLJEw11KZhdGh+4sflsIqrslML4R2NgRYqN8Vc::2
[__utmz] => 120264590.1625144765.12.5.utmcsr=l.facebook.com|utmccn=(referral)|utmcmd=referral|utmcct=/
[_ga] => GA1.2.2142405146.1621409499
[__utmc] => 120264590
[__utma] => 120264590.2142405146.1621409499.1629910859.1629978516.31
[_gid] => GA1.2.1913990981.1630182229
[ci_session] => e27a1e9ce4d0ee37f9b6569bd8eb15ab77fe45b2
)
Unable to understand why print_r $_INPUT is not showing sent data. Can anyone help me to solve this issue?
You are not writing the ajax correctly, you are going to have to pass the parameter in the url
$(document).on('click','#showCont', function(){
var memID=$(this).attr('data-mem');
$data = {memID: memID};
//console.log($data);
$.ajax({
url: "<?=base_url();?>"+"/Member/getContact/" + "<?=$data?>",
headers: {'X-Requested-With': 'XMLHttpRequest'},
type: "GET",
cache: false,
success: function (cont) {
console.log(cont);
}
});
});
On the other hand if you are using codeigniter 4 csrf validation, the method cannot be POST, you will have to use GET.

Cannot insert ajax data into database codeigniter

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);
}

laravel ajax function doesn't return a value

Hello I'm working on laravel and trying to make a ajax action
function jsfunctionrr(value){
var value_parts = value.split("+");
$.ajax({
type: 'POST',
url: '/getpoinsts',
data: {
'_token': $('input[name=_token]').val(),
'name': value_parts[1]
},
success: function (data) {
$('#pointsValue').append(total_points);
}
});
and the controller function
public function getpoinsts(Request $request)
{
$user_points_parts = DB::table('clients_points')->where('user_id', $request->name)->get;
$total_points = 0;
foreach ($user_points_parts as $points_part) {
$total_points += $points_part->points;
}
return response()->json($total_points);
}
and the route
Route::post('/getpoinsts', 'LoyalityController#getpoinsts');
but I get no value in back any one know why ??
There are a few issue in your code that I've noticed:
->get; should be get();
There might be an issue with trying to convert a number to json.
In your ajax method you're referencing total_points but it isn't defined anywhere.
Try changing your controller method to:
public function getpoinsts(Request $request)
{
$total_points = DB::table('clients_points')->where('user_id', $request->name)->sum('points');
return response()->json(compact('total_points'));
}
and your ajax method to:
$.ajax({
type: 'POST',
url: '/getpoinsts',
data: {
'_token': $('input[name=_token]').val(),
'name': value_parts[1]
},
dataType: 'json',
success: function (data) {
$('#pointsValue').append(data.total_points);
}
});
Hope this helps!

Symfony ajax form need reload page to show results

I have a product page where users can write comments, this works fine but i would like to implement ajax form with no page refresh.
The code call ajax and persist, but need press f5 to show new comment.
what am I doing wrong?
Thanks, and sorry for my english.
In product view, render a controller that call the form:
<div class="comments">
{{ render(controller('AppBundle:Comment:newComment',{'media': selected.id})) }}
</div>
Controller:
class CommentController extends Controller
{
/**
* #Route("/media/{media}/", name="create_comment", options={"expose"=true})
* #Method("POST")
* #ParamConverter("media", class="AppBundle:Media")
*/
public function newCommentAction(Request $request, $media)
{
$comment = new Comment();
$form = $this->createForm(CommentType::class, $comment);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()){
$data = $form->getData();
$data->setUser($this->getUser());
$data->setMedia($media);
$em = $this->getDoctrine()->getManager();
$em->persist($data);
$em->flush();
return new JsonResponse('Success!');
}
return $this->render('comment/newComment.html.twig', array(
'media' => $media,
'form' => $form->createView()
));
}
}
newComment.html.twig
<form method="POST" id="commentForm" action="{{path('create_comment', {'media': media.id})}}">
{{ form_row(form.comment) }}
<button type="submit" id="submitButton" class="btn btn-xs btn-danger">{{ 'btn.send' |trans }}</button>
app.js
$('body').on('click','#submitButton', function(e){
e.preventDefault();
var $form = $('#commentForm');
$.ajax({
type: "POST",
dataType: "json",
url: 'http://demo/app_dev.php/media/16/',
data: $form.serialize(),
cache: false,
success: function(response){
$(".ajaxResponse").html(response);
console.log(response);
},
error: function (response) {
console.log(response);
}
});
});
This should work for you to reload the element with class="comments" after your POST:
$('#submitButton').on('click', function (e) {
e.preventDefault();
var $form = $('#commentForm');
$.ajax({
type: "POST",
dataType: "json",
url: 'http://demo/app_dev.php/media/16/',
data: $form.serialize(),
cache: false,
success: function (response) {
$('.comments').load(window.location + ' .comments > *');
console.log(response);
},
error: function (response) {
console.log(response);
}
});
});
Edit:
As far as your second question regarding $request->isXmlHttpRequest() -- this method just looks for the X-Requested-With header with value of XMLHttpRequest. Are you testing for it on the first request or on the second request or on both requests? Can you take a look in Firebug or Chrome Tools and see if the header is on both requests?

Error Code using $Ajax, phpjson and sqlsrv_fetch_array

I have code like this in dataset.php
$query = "SELECT A,B,C from Table ";
$stmt = sqlsrv_query($link2,$query);
$data = array();
while($row=sqlsrv_fetch_array($stmt))
{
$data['data'][]= array (
'kodeLang' => $row['A'],
'nama_lang' => $row['B'],
'address' => $row['C']
);
}
echo json_encode($data);
and , i want to load the dataset.php in index.php with code like this :
<script>
$(document).ready(function(){
$.ajax({
type: 'POST',
url: 'dataset.php', //Relative or absolute path to response.php file
data: '',
dataType: 'json',
contentType: "application/json",,
success: function(data){
alert(data);
$("#atotal td#aTotal").html(data[0]['kodeLang']);
},
error : function (jqXHR,textStatus, errorThrown){
$('#errorr').fadeIn(1000).show();
}
});
event.preventDefault();
});
</script>
But when i using alert(data) in index.php, there's no alert. Is there any missed with my code ?
Trims
I have answer by my self, the proble about the array. I modified the file in index.php
<script>
$(document).ready(function(){
$.ajax({
type: 'post',
dataType: 'json',
url: 'dataset.php',
data: '',
contentType: 'application/json',
success: function(response){
$("#atotal td#aTotal").html(response.data[0].A);
},
error : function (jqXHR,textStatus, errorThrown){
$('#errorr').fadeIn(1000).show();
}
});
event.preventDefault();
});
</script>

Resources