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.