Error Code using $Ajax, phpjson and sqlsrv_fetch_array - ajax

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>

Related

How to post array to php using ajax in laravel

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

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 5.4 TokenMismatchException Ajax call

I get a TokenMismatchException error only when I submit a form with an ajax call? If I don't use an Ajax call I don't get the error.
What is causing this?
Laravel 5.4
I have this in the head of my app.blade.php:
<meta name="csrf-token" content="{{ csrf_token() }}">
My ajax.js
$( document ).ready(function() {
// storing comments
$('#storeComment').on('submit', function(e) {
e.preventDefault();
$.ajax({
method: 'POST',
url: '/comments',
data: {},
success: function(response){
console.log(response);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
});
});
I also use the bootstrap.js that automatically registers the value of the csrf-token meta tag with the Axios HTTP library. As explained in the Laravel documentation.
Controlle Method:
public function store(CommentRequest $request)
{
$comment = Auth::user()->comments()->save(new Comment($request->all()));
$response = array(
'status' => 'success',
'comment' => $comment
);
return response()->json($response);
}
Add the token to the ajax's data :
$.ajax({
type: 'POST',
......
data: {'_token': '{{ csrf_token() }}'},
........
Instead of calling jQuery you can call Axios directly and have this automatic csrf injection, with the following code:
var data = ['name' => 'Nikola', 'lastName' => 'Gavric'];
axios.post('/comments', data).then(function(response) {
console.log(response);
});
EDIT: Complete example for axios is
$('#storeComment').on('submit', function(e) {
e.preventDefault();
// Retrieve form data
var temp = [];
var data = $(this).serializeArray();
$.each(data, function(index, field) {
temp[field.name] = field.value;
});
// Post request with temp as data
axios.post('/comments', temp).then(function(data) {
console.log(data);
});
});
And this is the code for jQuery, use whichever approach you like better:
$.ajax({
method: 'POST',
url: '/comments',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: {
'name': 'Nikola',
'lastName': 'Gavric'
},
success: function(response){
console.log(response);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
$.ajax({
type: 'POST',
........
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
}
...........
});
try this...
Add csrf-token to head of your application :
<meta name="csrf-token" content="{{ csrf_token() }}">
then :
$.ajax({
url: '/some/url',
type: 'POST',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function(res){
// Your result
console.log(res);
}
});
You can try to disable CSRF verification on specific route in App\Http\Middleware\VerifyCsrfToken.php
protected $except = ['/comments'];

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!

How to use ajax in Wordpress?

I want to use ajax in wordpress. How can I do it? I have attached my code here. But this is not working for me.
Here it is my wordpress action and hook.
function ajax_enqueuescripts() {
wp_enqueue_script('ajaxloadpost', get_template_directory_uri().'/js/my-ajax.js', array('jquery'));
wp_localize_script( 'ajaxloadpost', 'ajax_postajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
add_action('wp_enqueue_scripts', ajax_enqueuescripts);
add_action('wp_ajax_nopriv_ajax_ajaxhandler', 'my_action_callback' );
add_action('wp_ajax_ajax_ajaxhandler', 'my_action_callback' );
function my_action_callback(){
//echo "Df";print_r($_POST);die;
}
and here it is my js code
jQuery(document).ready(function(){
jQuery('#event-form').submit( function () {
var email = jQuery('#event_name').val();
jQuery.ajax({
type: 'POST',
url: ajax_postajax.ajaxurl,
data: {
action: 'ajax_ajaxhandler',
email : email
},
success: function() {
alert(email);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Fd");
}
});
return false;
});
});
The value that you alert in your success ajax function must come from your php function so you would have something like this:
PHP
function my_action_callback(){
echo $_POST['email']; die();
}
Javascript
jQuery.ajax({
type: 'POST',
url: ajax_postajax.ajaxurl,
data: {
action: 'ajax_ajaxhandler',
email : email
},
success: function(data) {
alert(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Fd");
}
});
in your case data in javascript will be equal to anything that you echo out in your php function.
You can send json objects to javascript by encoding arrays in which case you would have
PHP
function my_action_callback(){
echo json_encode('email' => $_POST['email']));
die();
}
Javascript
jQuery.ajax({
type: 'POST',
url: ajax_postajax.ajaxurl,
data: {
action: 'ajax_ajaxhandler',
email : email
},
success: function(data) {
alert(data.email);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Fd");
}
});
I only gave you example of the places in your code that needed to be replaced, the rest seems alright.

Resources