I'm very new to this ajax request using laravel and currently I'm stuck. I'm having trouble inserting the sessionStorage from database.
For example I have here in my sessionStorage:
Key Value
=================
gclid 12345
token abcde
I want to get the value for gclid or token values using ajax and store it in the database.
Here in my ajax I'm having trouble how to get these parameter values and store it in my db. I have this condition to get the key of the parameters like this logic:
This is in my controller:
if(key == gclid)
$traffic->traffic_type = $request->('gclid');
else if (key == token)
$traffic->traffic_type = $request->('token');
How do I pass this variables in my jquery and add a request in my controller to fetch it using ajax?
var gclid = sessionStorage.getItem('gclid');
var token = sessionStorage.getItem('token');
Ajax
// Tracking Parameters
function storeVisitorParameters() {
let url = '{{ route('trackvisit') }}';
var gclid = sessionStorage.getItem('gclid');
var token = sessionStorage.getItem('token');
const data = {};
$.ajax({
type: 'POST',
url: url,
data:data,
beforeSend: function (xhr) {
var token = $('meta[name="csrf-token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
complete: function() {
},
success: function (data) {
$.notify("Visitor Parameters Stored!", 'success');
},
error: function (xhr, ajaxOptions, thrownError) {
console.log('server errors', thrownError);
}
});
}
TrafficController.php
class TrafficController extends Controller
{
// Store gclid or token parameters to traffic_tacking_table
public function storeVisitorParameters(Request $request)
{
$traffic = new TrafficTracking();
$traffic->user_id = $user->user_id;
if($traffic->traffic_type = $request->gclid;) // check if key = gclid
{
$traffic->traffic_type = $request->gclid; // store the key in db
$traffic->traffic_value = $request->get('gclid');
}
else if ($traffic->traffic_type = $request->token) // check if key = token
{
$traffic->traffic_type = $request->token; // store the key in db
$traffic->traffic_value = $request->get('token');
}
$traffic->ip_address = $request->ip();
$traffic->domain = $request->getHttpHost();
$traffic->save();
return response()->json($traffic);
}
}
web.php
Route::post('/trackvisit', 'TrafficController#storeVisitorParameters')->name('trackvisit');
migration
public function up()
{
Schema::create('traffic_tracking', function (Blueprint $table) {
$table->increments('traffic_id');
$table->string('ip_address');
$table->string('traffic_type');
$table->string('traffic_value');
$table->integer('user_id');
$table->timestamps();
});
}
my main goal is to only get the sessionStorage values and send a request to my controller.
In your php controller, change this if($traffic->traffic_type = $request->gclid;) to if($traffic->traffic_type == $request->gclid) , you're comparing the values right ?? It should be double == and remove ; inside if condition
In javascript catch csrf token as,
var _token = $('meta[name="csrf-token"]').attr('content');
In AJAX Request,
dataType: 'JSON', // Add datatype as JSON, optional still for good practice
data:{
_token: _token,
gclid: gclid,
token: token
},
Inside data {} you're passing the values (gclid, _token and your sessionStorage token) as JSON formatted data to laravel controller
Related
I am trying to retrieve data from the database, but when the get parameter appears in the address bar, there is no change on the page, so I have to refresh the page to receive the data, instead of receiving it without refresh/reload.
Route:
Route::get('writers/{orders?}/{number?}', ['as'=>'writers','uses'=> 'HomeController#writers']);
Controller:
public function writers($order='all',$num=10){
$dm = new DataModel();
$orders = $dm->getCertainWriters($num);
$this->certainOrders =$orders;
return view('writers')->with(array('title'=>'Writers','data'=>$this->certainOrders,));
}
Method:
public function getCertainWriters($orders = 'all'){
$data = DB::select("SELECT * FROM `writers` WHERE `completed_orders` > '$orders' ");
return $data;
}
AJAX:
$("#ajax-orders").change(function(e) {
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "GET",
url: url,
dataType:"html",
headers: {
'X_CSRF_TOKEN':CSRF_TOKEN,
'Content-Type':'application/json'
},
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
$(form).submit(e);
var orders = $('select').val();
window.history.pushState("writer", "orders", "/writers/orders/"+orders);
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
I've successfully sent some information through AngularJS to my backend in Laravel, however, I'm facing some issues while trying to get some authenticated user data.
Basically, it just don't retrieve any authenticated user data from my backend.
AngularJS
$scope.generatePrescription = function () {
//check for token in meta tag
var csrf_token = $('meta[name=csrf-token]').attr('content');
console.log('CSRF_TOKEN =>'+csrf_token);
info = {
_token: csrf_token,
receita: $scope.receita,
receita_info: $scope.receita_info
};
$http({
method: 'POST',
url: apiURL + '/prescription/create',
data: info,
headers:{
'Content-Type': 'application/x-www-form-urlencoded',
}
}).then(
function(response){
console.log(response.data)
},
function(error){
console.log(error.data)
}
);
}
Api.php (Laravel)
Route::middleware('api')->post('/prescription/create','Dashboard\PrescriptionController#store');
PrescriptionController.php
public function store(Request $request, Prescription $prescription)
{
//receive prescription object
$data = $request->json()->all();
if(auth()->check()){
return 'authenticated!!!';
} else {
return 'user is not authenticated..';
}
}
How should I proceed to get my authenticated user variables?
Thank you in advance.
To remove only one record I realize this ajax
var borrar = confirm("¿Realmente desea eliminarlo?");
if (borrar)
{
var token = document.getElementById('token').value;
$.ajax({
headers: {'X-CSRF-TOKEN': token},
dataType: "json",
data: {radicado: radicado},
url: ip+'/eliminarRadicado/delete/'+radicado,
type: 'get',
beforeSend: function(){
},
success: function(respuesta){
alert(respuesta);
},
error: function(xhr,err){
alert("Error");
}
});
}
which sends by $get the id of the record that I delete the file and run this route :
Route::get('eliminarRadicado/delete/{id}', 'RadicadoController#destroy');
which ultimately goes to the driver and performs the function of removing
public function destroy($id)
{
\App\Radicado::destroy($id);
return response()->json(['Documento eliminado']);
}
What is not like removing more than one record (id ) I send. Any ideas ?
You shouldn't send delete requests using a GET verb. Instead you should use the DELETE verb which is semantically correct.
With your current approach, sending the X-CSRF-TOKEN header doesn't do anything, as Laravel doesn't check the CSRF token for read requests (GET and HEAD). Instead you should pass all the IDs you want to deleted as parameters with a DELETE request like so:
var ids = [1, 10, 17]; // Use your own logic to set the array of the IDs here
$.ajax({
headers : {'X-CSRF-TOKEN': token },
dataType: "json",
data : { ids: ids }, // Pass IDs array
url : ip + '/eliminarRadicado/delete',
type : 'delete', // Send a delete request
beforeSend: function () {
},
success: function (respuesta) {
alert(respuesta);
},
error: function (xhr, err) {
alert("Error");
}
});
Then change your route definition to this:
Route::delete('eliminarRadicado/delete', 'RadicadoController#destroy');
And in your destroy controller method use the array of IDs received via the request:
use Illuminate\Http\Request;
...
public function destroy(Request $request)
{
\App\Radicado::destroy($request->input('ids'));
return response()->json(['Documento eliminado']);
}
Now you can pass an array of one or more IDs to be deleted using the same request.
I'm trying to receive data from a form through AJAX on Laravel 5.
JavaScript code:
event.preventDefault(); // Disable normal behaviour of the element (Form)
var formData = {
form: $("#newCustomerForm").serialize() // Transmit all input data of the form serialized
}
console.log(formData); // Log to the console the Input data
$.ajax({
type: 'post', // POST Request
url: 'save', // Url of the Route (in this case user/save not only save)
data: formData, // Serialized Data
dataType: 'json', // Data Type of the Transmit
beforeSend: function (xhr) {
// Function needed from Laravel because of the CSRF Middleware
var token = $('meta[name="csrf_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
success: function (data) {
// Successfuly called the Controler
// Check if the logic was successful or not
if (data.status == 'success') {
console.log('alles ok');
} else {
console.log(data.msg);
}
},
error: function (data) {
// Error while calling the controller (HTTP Response Code different as 200 OK
console.log('Error:', data);
}
});
Route:
Route::post ('user/save', 'CustomerController#createNewCustomer');
Controller:
public function createNewCustomer (Request $request)
{
$inputArray = $request->all();
print_r ($inputArray['form']);
// Set JSON Response array (status = success | error)
$response = array ('status' => 'success',
'msg' => 'Setting created successfully',);
// Return JSON Response
return response ()->json ($response);
}
In the network tab I can see how the parameters look like:
radio-inline-left=on&firstname=sdsd&private_lastname=&private_title=&private_birthdate=&private_email=&business_email=&private_phone=&business_phone=&private_mobile=&business_mobile=&brand=&business_job_title=&business_address_street=sdsd&business_address_po_box=&business_address_addon_1=&business_address_addon_2=&private_zip=&private_location=&business_address_street=&business_address_po_box=&business_address_addon_1=&business_address_addon_2=&private_zip=&private_location=&source=social_media&source=&availability=on&additional-info={"status":"success","msg":"Setting created successfully"}
I also tried to access the data with $request->input('name of the field') but then it's always empty.
Does anybody have an idea what i'm doing wrong?
The problem is that you are calling $("#newCustomerForm").serialize(), and this method serializes the form in url-encoded parameters and not a json encoded body.
In this question an answer is provided for this to work.
You can access like this
$request['name of field'];
i think you need to receive the data in the controller as json:
$request->json('field_of_interest')
The problem is your formData variable. Instead of:
var formData = {
form: $("#newCustomerForm").serialize()
}
it should be
var formData=$("#newCustomerForm").serialize();
I am trying to return an Eloquent Model Object as an Ajax Response that i get from search process and i want to pass it to the view.
JS
$(document).ready( function() {
$(".client_search_option").change(function(){
var selectedClientTypeVal = "";
var selectedSmsDecisionVal = "";
var selectedClientType = $('input[type=radio][name=clientType]:checked');
var selectedSmsDecision = $('input[type=radio][name=sms_decision]:checked');
if (selectedClientType.length > 0) {
selectedClientTypeVal = selectedClientType.val();
}
if (selectedSmsDecision.length > 0) {
selectedSmsDecisionVal = selectedSmsDecision.val();
}
//alert(selectedClientTypeVal);
//alert(selectedSmsDecisionVal);
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
url: 'http://localhost/pages/clientSearchAjax',
type: 'POST',
data: {_token: CSRF_TOKEN, selectedClientTypeVal:selectedClientTypeVal,selectedSmsDecisionVal:selectedSmsDecisionVal},
dataType: 'JSON',
success: function (data) {
console.log(data);
},
error:function(){
alert("An error has occured !");
}
});
});
});
Contoller
public function clientSearch(){
$client_option = Input::get('selectedClientTypeVal');
$sms_option = Input::get('selectedSmsDecisionVal');
if($client_option == 'all' && $sms_option == 'all'){
$ajax_clients = Client::with('clientType')->paginate(5);
}else{
$ajax_clients = Client::with('clientType')->where('clienttype_id', $client_option)->where('send_sms', $sms_option)->paginate(5);
}
return $ajax_clients->toJson();
}
I am sure that $ajax_client object is not null, i test it and i am able to get data from database but when i want to pass it to the view(or console) it shows up like undefined. How can pass it to the view(or console) and get the values of model's columns. Any help would be appreciated.
Try replacing
return $ajax_clients->toJson();
with
return $ajax_clients;
Laravel automatically converts Eloquent objects to JSON, moreover it will set content type header to application/json, which is something you don't do in your code and what might cause the issues you describe.