i am unable to get posted data on sever using php it returns
Output : Array()
Php Code
public function create()
{
print_r($_POST);
}
Angular Code
angular.module('index',[])
.controller('SignUpController', ['$scope','$http', function($scope,$http) {
$scope.signup=function(user){
var dataObj = {
"name" : "sdadas",
"employees" : "sadsad",
"headoffice" : "sadsa"
};
$http.post("<?=base_url()."index.php/users/create" ?>",dataObj).
success(function(data,status,header,config){
alert(data);
}).
error(function(data,status,header,config){
});
};
}]);
i dont know what base url is but i guess it's a function so i rewrote it from this
$http.post("<?=base_url()."index.php/users/create" ?>",dataObj).
success(function(data,status,header,config){
alert(data);
}).
To this u should put it between single quotes
$http.post('<? echo base_url()."index.php/users/create"; ?>',dataObj).
success(function(data,status,header,config){
alert(data);
}).
public function create()
{
print_r(json_decode(file_get_contents("php://input")));
}
Related
I'm making an dependent drop-downn of countries states and cities in laravel using jQuery and Ajax. I'm doing it on localhost Xampp. First i use jQuery for country. when country change jQuery get value and send to Controller. But when i send value from RegistrationFormComponent to CountryStateCity Controller and try to show what value i get. I got an error ( POST http://127.0.0.1:8000/getstate 500 (Internal Server Error) ). i don't know why im getting this error.
Route:
Route::get('/register', [CountryStateCityController::class, 'getcountry']);
Route::POST('/getstate ', [CountryStateCityController::class, 'getstate']);
JQuery and Ajax
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function () {
$('#country').change(function () {
var cid = this.value; //$(this).val(); we cal also write this.
$.ajax({
url: "getstate",
type: "POST",
datatype: "json",
data: {
country_id: cid,
},
success: function(result) {
// if(cid == "success")
// alert(response);
console.log(result);
},
errror: function(xhr) {
console.log(xhr.responseText);
}
});
});
});
Controller
class CountryStateCityController extends Controller
{
public function getcountry() {
$country = DB::table('countries')->get();
$data = compact('country');
return view('RegistrationForm')->with($data);
}
public function getstate(Request $request) {
$state = State::where('countryid'->$cid)->get();
return response()->json($state);
}
public function getcity() {
}
}
I think i tryed every possible thing. But didn't work. Please tell me how can i get rid of this problem. And please also tell me how can i send data from component to controller using jquery and ajax and get value form controller and take data from database and send back to component.
This is written incorrectly.
public function getstate(Request $request) {
$state = State::where('countryid'->$cid)->get();
return response()->json($state);
}
It should look like this.
public function getstate(Request $request) {
$state = State::where('countryid', '=', $request->country_id)->get();
return response()->json($state);
}
please check controller function
public function getstate(Request $request) {
$state = State::where('countryid' `=` ,request->$countryid)->get();
return response()->json($state);
}
Hello I have a problem when I wanna show my query result at my text fields
I tried to don't use JSON.parse but when I do it this doesn't show anything then I use an alert and show my undefined
this is the code using an alert to show the result
$(document).ready(function(){
$('#zip_code').blur(function()
{
var zip_code=$(this).val();
if(zip_code != '')
{
var _token = $('input[name="_token"]').val();
$.ajax({
url:"{{route('complete.zip')}}",
method:"POST",
data:{zip_code:zip_code,_token:_token},
success:function(data)
{
alert(data.value1);
}
});
}
});
});
when I try to convert the JSON in the console show me it
SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data
this is the code
$(document).ready(function(){
$('#zip_code').blur(function()
{
var zip_code=$(this).val();
if(zip_code != '')
{
var _token = $('input[name="_token"]').val();
$.ajax({
url:"{{route('complete.zip')}}",
method:"POST",
data:{zip_code:zip_code,_token:_token},
success:function(data)
{
var result = JSON.parse(data);
$('#estado').val(result.value1);
$('#municipio').val(result.value2);
}
});
}
});
});
the PHP files is the next
use DB;
class ClientBusinessController extends Controller
{
public function index()
{
return view("new_client.register_business");
}
public function receiveValueZip(Request $request)
{
if(!empty($request->get('zip_code')))
{
$result=DB::table('direccion')
->select('Calle1','Calle2')
->where('Id_Direccion','=',6)
->get();
foreach($result as $r)
{
json_encode(array("value1"=>$r->Calle1,"value2"=>$r->Calle2));
}
}
}
Does someone know how to resolve this problem? thanks so much
If you call json_encode multiple times you end up with invalid JSON. You should instead construct your array structure fully and call json_encode only once. However I recommend using response()->json and letting Laravel handle the JSON serialization:
public function index()
{
return view("new_client.register_business");
}
public function receiveValueZip(Request $request)
{
if(!empty($request->get('zip_code')))
{
$result=DB::table('direccion')
->select('Calle1','Calle2')
->where('Id_Direccion','=',6)
->get();
return response()->json(
$result->map(function ($row) {
return array("value1"=>$r->Calle1,"value2"=>$r->Calle2);
});
);
}
}
I have a simple php function as below defined in one of my php file
add_action('wp_ajax_test','test');
add_action('wp_ajax_nopriv_test','test');
function test(){
echo "Hello";
}
I am calling above "test" function using below ajax function call
jQuery(document).ready(function(){
jQuery('#prev_button_id').click(function(){
jQuery.post(
myAjax.ajaxurl,
{
action:"test",
success: (response)=>{
console.log('Success:'+ response);
},
error:(response)=>{
console.log('Failure:'+ response);
}
});
});
});
I am expecting console output of "Hello" but I getting below undefined response
Success:undefined
Failure:undefined
jQuery(document).ready(function(){
jQuery('#prev_button_id').click(function(){
var params = {action:"test"}
jQuery.post(myAjax.ajaxurl,params,function(data){
if( data ){
console.log ( data );
}
});
});
});
add_action( 'wp_ajax_test','test' );
add_action( 'wp_ajax_nopriv_test','test' );
function test() {
echo "Hello";
die;
}
Try this code and don't forget to die after AJAX call also
make sure you are getting proper AJAX URL in myAjax.ajaxurl
I followed the below video, step by step and it worked.
Probably it had something to do with nonce
AJAX in WordPress using admin-ajax.php
I have a export csv function, it worked fine with laravel. But now I want to call export function via ajax and use method post, but I there is no respone. I can send a variable from laravel controller to response, but can not send a file download.
Here is my code :
route.php
Route::get('/title/show', 'TitleController#show');
Route::post('/title/show', 'TitleController#exportFromDB');
show.blade.php
<script>
$(document).ready(function () {
$('#exportFromDB').click(function () {
$.ajax({
url: "",
type: "post",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: {},
success: function (response) {
var a = document.createElement("a");
a.href = response.file;
a.download = response.name;
}
})
})
})
TitleController.php:
$dataExport['Oversea'] = $dataOversea;
$this->titleRepository->export('csv', $properties, $dataExport);
TitleRepository.php
public function export($type, $properties, $data)
{
if (in_array($type, self::EXPORT_TYPE)) {
try {
return Excel::create($properties['_title'], function ($excel) use ($data, $properties) {
$excel->setTitle($properties['_title']);
$excel->setCreator($properties['_creator'])
->setCompany($properties['_company']);
$excel->setDescription($properties['_description']);
$excel->sheet('Sheet', function ($sheet) use ($data) {
foreach ($data as $item) {
$sheet->fromArray($item);
}
});
})->export($type);
} catch (Exception $error) {
throw $error;
}
}
}
How can I fix them ? Thank !
Try this -
Don't write the code for export in your controller method, instead just save the excel file in your public folder.
Your controller method should return the filename.
On your ajax success do this -
location.href = path/to/file/property_title.xls
So replace your this line
->export($type);
with
->store($type, 'public/reports/', true);
I see your ajax url null value
Change it to
url : "{{ action('TitleController#exportFromDB') }}"
After that, response is data you return in controller
success: function (response) {}
I installed the maatwebsite/excel package and was able to do it without writing any javascript. All you need to do is setup a link (or typical form post if you prefer) to an action like so:
public downloadItemsExcel() {
$items = Item::all();
Excel::create('items', function($excel) use($items) {
$excel->sheet('ExportFile', function($sheet) use($items) {
$sheet->fromArray($items);
});
})->export('xls');
}
This works for csv/excel files alike. There is no reload of a page in the browser.
First you have to change POST method to GET.
For ajax you can do it like this:
$(document).ready(function () {
$('#exportFromDB').click(function () {
$.get('/title/show, function(data){
window.location = '/title/show=' + data;
});
})
})
I'm learning AJAX and I'm trying to do an AJAX request with parameters, but I'm having problems to send the JSON data:
I'm using Typescript and PHP (with Codeigniter), the idea is to create a Typescript object and send it to the PHP in JSON format. So basically I create an object and use the stringify method that I find on Google to convert this object to JSON (or a string in form of JSON I should say?) and send it to the server with AJAX, but the data is not arriving properly.
I used print_r($_POST); to see what is the server receiving and it shows to me the following:
Array
(
[{"_dificultad_seleccionada":"Normal"}] =>
[0] =>
)
The entire string that I get from stringify is shown as the key and the value is empty.
I don't understand very well what is happening, isn't stringify the way to convert an object to JSON and send it to the server? Why it isn't sending the object properly?
Client code:
Dificultad.ts (class that I want to send to the server)
class Dificultad {
private _dificultad_seleccionada: string;
constructor (dificultad_seleccionada: string) {
this._dificultad_seleccionada = dificultad_seleccionada;
}
get dificultad_seleccionada(): string {
return this._dificultad_seleccionada;
}
set dificultad_seleccionada(dificultad_seleccionada: string) {
this._dificultad_seleccionada = dificultad_seleccionada;
}
}
Lib.ts (where I declare all const, DOM elements, etc.)
const BASE_URL: string = window.location.origin + "/Project_name/";
type CallbackFunction = (arg: any, ...args: any[]) => void;
Main.ts (here is where I send the AJAX)
$(document).ready(function() {
$( "a#boton_seleccion_dificultad" ).click(function(event) {
event.preventDefault();
if (pasapalabra.gameState == GameState.GAME_STARTING) {
let _dificultad: Dificultad = new Dificultad("Normal");
sendAjaxRequest("POST", "get_dificultad_seleccionada", JSON.stringify(_dificultad), function(response) {
console.log(response);
});
}
});
});
function sendAjaxRequest(_type: string, _url: string, _params: string, _callback: CallbackFunction) {
var request = $.ajax({
type: _type,
url: BASE_URL + _url,
data: _params,
contentType: 'json'
});
request.done(function(res) {
_callback(res);
});
request.fail(function(jqXHR, textStatus) {
console.error(jqXHR)
_callback({ err: true, message: "Request failed: " + textStatus });
});
}
Server code:
Welcome.php
class Welcome extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->database();
$this->load->library("grocery_CRUD");
date_default_timezone_set('Europe/Madrid');
$this->load->library('session');
$this->load->helper('url');
$this->load->model("Rol_model");
$this->load->model("Questions_model");
}
public function get_dificultad_seleccionada() {
print_r($_REQUEST); print_r($_POST);
//echo json_encode($dificultad);
}
}
It seems to be a problem with the object conversion that I do with stringify on the client because if I change the ajax call like this, sendind a JSON manually, it works:
Main.ts
sendAjaxRequest("POST", "get_dificultad_seleccionada", {"_dificultad_seleccionada":"Normal"}, function(response) {
console.log(response);
});
It seems that I'm doing something wrong but I have no idea of what could be, how can I send this object to the server in JSON format?
I want to do an universal function for all AJAX request in my program, but I don't know very well if I'm doing it properly, is the type of the callback function ok? or am I wrong with this?
Thank you very much for your help.
I think I have solved the problem, I'm sending the same data like I did before but now I use contentType: 'json' to tell the server that I'm sending a JSON and in the server side (PHP) I use the following to get the json: json_decode(file_get_contents('php://input'), true);
Main.ts
$(document).ready(function() {
$( "a#boton_seleccion_dificultad" ).click(function(event) {
event.preventDefault();
if (pasapalabra.gameState == GameState.GAME_STARTING) {
let _dificultad: Dificultad = new Dificultad("Normal");
sendAjaxRequest("POST", "get_dificultad_seleccionada", JSON.stringify(_dificultad), function(response) {
console.log(response);
});
}
});
});
function sendAjaxRequest(_type: string, _url: string, _params: string, _callback: CallbackFunction) {
var request = $.ajax({
type: _type,
url: BASE_URL + _url,
data: _params,
contentType: 'json'
});
request.done(function(res) {
_callback(res);
});
request.fail(function(jqXHR, textStatus) {
console.error(jqXHR);
_callback({ err: true, message: "Request failed: " + textStatus });
});
}
Welcome.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->database();
$this->load->library("grocery_CRUD");
date_default_timezone_set('Europe/Madrid');
$this->load->library('session');
$this->load->helper('url');
$this->load->model("Rol_model");
$this->load->model("Questions_model");
}
public function get_dificultad_seleccionada() {
$data = json_decode(file_get_contents('php://input'), true);
print_r($data);
echo $data["_dificultad_seleccionada"];
}
}
Now the server gets the value properly and I supose that now it's getting it in JSON format.