I am using this jquery code to store data using ajax but if I use
let loc = $('[name="ot_location"]').val(position.coords.latitude+','+position.coords.longitude);
in console it says ReferenceError: loc is not defined I am new to javascript and learning and I need help
html
<span>Visit Clear</span><br><input type="checkbox" data-id="{{ $customer->id }}" name="visit_clear" class="js-switch2 js-switch" {{ $customer->visit_clear == 1 ? 'checked' : '' }}>
Java script
$(document).ready(function(){
$(document).on('change', '.js-switch2', function () {
let visit_clear = $(this).prop('checked') === true ? 1 : 0;
if ($(this).prop('checked') == 1) {
$(this).closest('tr').addClass('visitclear');
//ot get location
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
alert("Try any other browser");
}
}
function showPosition(position) {
let loc = $('[name="ot_location"]').val(position.coords.latitude+','+position.coords.longitude);
}
$(document).ready(getLocation);
} else {
$(this).closest('tr').removeClass('visitclear');
}
let userId = $(this).data('id');
$.ajax({
type: "GET",
dataType: "json",
url: '{{ route('users.update.visit_clear') }}',
data: {'visit_clear': visit_clear, 'user_id': userId , 'ot_location': loc},
success: function (data) {
console.log(data.message);
}
});
});
});
Controller
public function visitclear(Request $request)
{
$customer = Customer::findOrFail($request->user_id);
$customer->visit_clear = $request->visit_clear;
$customer->ot_location = $request->ot_location;
$customer->visit_date = date('Y-m-d H:i');
$customer->save();
return response()->json(['message' => 'User status updated successfully.']);
}
i want on click check box store geo cords in var loc and store it using ajax how i can do that?
use var in place of let in your code for loc and see if the reference error goes away.
So, your let loc = $('[name="ot_location"]').val(position.coords.latitude+','+position.coords.longitude);
should be
var loc = $('[name="ot_location"]').val(position.coords.latitude+','+position.coords.longitude);
Related
I'm working with Laravel 5.8 and I wanted to apply a discount code system for my site.
So I tried sending data with Ajax like this:
$.ajax({
type: 'POST',
url: baseurl + 'discount/register',
data: {
coupon_code: finalDiscountValue,
course_id: itemCourse,
},
dataType: "json",
success: function (data) {
if(data == 99) {
swal("Wrong discount code");
} else if (data == 130) {
window.location.href = {!! json_encode(route('myCourseList')) !!}
} else{
window.location.href = {!! json_encode(route('payCourseRegistrationWithDiscount', ['course'=>$item->cor_id,'value'=>$data['cartValueDiscountedWithCode'] ?? ''])) !!}
}
}
});
Now my problem is $data['cartValueDiscountedWithCode'] which does not send to the defined route name.
And this is because $data is returned in Ajax and it's type is different from the other variable which is $item->cor_id and is Laravel based variable.
Here is how I return $data in the Controller:
public function registerWithDiscount()
{
$courseId = request('course_id');
$findCourse = Course::find($courseId);
$getCoursePrice = $findCourse->cor_price;
if ( request('course_id') == null ) {
return 97; // The input was empty
}
...
$data['cartValueDiscountedWithCode'] = $getCoursePrice - $value_discounted;
$data['discountedPrice'] = $value_discounted;
$data['coupon_id'] = $coupon->id;
$data['coupon_name'] = $coupon->name;
if($data['discountedPrice'] >= $getCoursePrice){
$this->registerDiscountFree($courseId,$data['cartValueDiscountedWithCode']);
session()->flash('registrationMessage', 'Your registration is completed');
return 130; // if the discount code makes the course free
}else{
return $data; // if the remainer balance still needs to pay
}
}
You can try this:
let url = "{{ route('payCourseRegistrationWithDiscount',['course'=>$item->cor_id,'value'=>':cartValueDiscountedWithCode']) }}";
url = url.replace(':cartValueDiscountedWithCode', data.cartValueDiscountedWithCode);
window.location.href = url;
You can't pass the ajax response value like that.
Instead, add a string inside route and later repalce with response value
what you will have to do is add the parameter as optional {value?}example
and then add the in blade
window.location.href = {{route('payCourseRegistrationWithDiscount', ['course'=>$item->cor_id]) }}}+'/'+data.cartValueDiscountedWithCode
I'm using this plugin to validate a tel html input https://github.com/jackocnr/intl-tel-input
I send the form through an ajax response and receive the html structure updated. When I set this html to the page, it loses the plugin instance and it's a normal tel input again, without the plugin instance attached to it. How do I call the previous instance to the new input received that it's technically the same?
// Call and set plugin instance
var inputRec = document.querySelector('#phone_number_rec');
var itiRecruiter = window.intlTelInput(inputRec, {
hiddenInput: "full",
initialCountry: "auto",
geoIpLookup: function(callback) {
$.get('https://ipinfo.io', function() {}, "jsonp").always(function(resp) {
var countryCode = (resp && resp.country) ? resp.country : "us";
callback(countryCode);
});
},
utilsScript : base_url + '/public/assets/modules/intl-tel-input-master/build/js/utils.js',
});
// Send form through ajax
// Submit recruiter experience
$('body').on('submit', '.submit-individual-recruiter', function(e){
e.preventDefault(e);
var form = $(this);
var post_url = $(this).attr('action'); //get form action url
var form_data = $(this).serialize(); //Encode form elements for submission
if ($(this)[0].checkValidity() === false) {
event.stopPropagation();
form.addClass('was-validated');
} else {
$(this).addClass('was-validated');
var responseState = false;
var jqxhr = $.ajax({
url : post_url,
type: 'post',
data : form_data,
}).done(function(response){
response = JSON.parse(response);
if(response.result == 'success'){
responseState = true;
iziToast.success({
message: response.message,
position: "topRight"
});
} else if(response.result == 'error'){
iziToast.error({
message: response.message,
position: "topRight"
});
}
});
jqxhr.always(function() {
if(responseState == true){
var $row = $('#recruiter-experience');
var url = base_url + '/get_info/experience';
$.post( url, function( response ) {
response = JSON.parse(response);
$row.html(response.recruiterView.data);
});
}
});
}
});
well you replaced the dom, so the element that u initialized the tel-validator is gone.
one thing u could do is wrap your initializer into a function so u can just call it again
function initializeTel() {
var inputRec = document.querySelector('#phone_number_rec');
var itiRecruiter = window.intlTelInput(inputRec, {
hiddenInput: "full",
initialCountry: "auto",
geoIpLookup: function(callback) {
$.get('https://ipinfo.io', function() {}, "jsonp").always(function(resp) {
var countryCode = (resp && resp.country) ? resp.country : "us";
callback(countryCode);
});
},
utilsScript : base_url + '/public/assets/modules/intl-tel-input-master/build/js/utils.js',
});
}
// call it initially
initializeTel();
// and then after u received and parsed the response
initializeTel();
I run the PHP code by ajax method with the click of a button.
$(".btn_ranking").one('click', function(e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: {
name: name,
time: time
}
});
});
I would like the file.php to be able to run the js code, for example:
if ($time < $_SESSION['time']) {
[...]
}
else {
echo '<script>alert("lol");</script>';
}
And that when the button .btn_ranking on the page is pressed, an 'lol' alert will be displayed. If it is possible?
you can echo a response to the AJAX call and then run the JS according to the response..
$(".btn_ranking").one('click', function(e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: { name: name, time: time },
success: function (data) {
if(data==1){
//do this
}else if(data==2){
//do that
alert('LOOL');
}
}
});
});
PHP CODE:
if ($time < $_SESSION['time']) {
echo '1';
}
else {
echo '2';
}
You can't said to a server-side script to use javascript.
What you have to do is to handle the return of you'r ajax and ask to you'r front-side script to alert it. Something like that :
file.php :
if ($time < $_SESSION['time']) {
[...]
}
else {
echo 'lol';
exit();
}
Front-side :
$(".btn_ranking").one('click', function(e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: {
name: name,
time: time
},
success : function(data) {
alert(data);
}
});
});
When you used ajax for call php script, everything will be print in the return of the php code will be return to the HTTP repsonse and so be on the Ajax return function as params.
Ok .. First change your js code to handle answer from php script:
$(".btn_ranking").one('click', function(e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: { name: name, time: time }
success: function(data) {
console.log(data);
// check if it is true/false, show up alert
}
});
});
Then change php script (file.php), something like that:
$response = [];
if ($time < $_SESSION['time']) {
$response['data'] = false;
}
else {
$response['data'] = true;
}
return json_encode($response);
Something like that is the idea :) When u send ajax with POST method get variables from there, not from $_SESSION :)
U can see good example here
i have a function in webpage with this code :
enter code here function LoadGrid() {
var gridder = $('#as_gridder');
var UrlToPass = "action=load";
//was var UrlToPass = 'action=load';
gridder.html('loading..');
$.ajax({
url : 'cartajax.php',
contentType: 'application/x-www-form-urlencoded;charset=ISO-8859-7',
type : 'POST',
data : UrlToPass,
success: function(responseText) {
gridder.html(responseText);
}
});
}
and in ajax.php i have this code :
enter code here $action = $_POST['action']; switch($action) { case "load":
and i cant see anything but only loading...
the problem is only in ie8
IE8 has problems inserting long strings of text with jQuery's html()
Probably this is a known bug. You can refer this
A way around is
try {
//new browsers
$('#domElement').html(responseText);
} catch (e) {
//IE8
$('#domElement').innerHTML = responseText;
}
EDIT-1
function LoadGrid() {
// var gridder = $('#as_gridder');
var UrlToPass = "action=load";
//was var UrlToPass = 'action=load';
gridder.html('loading..');
$.ajax({
url : 'cartajax.php',
contentType: 'application/x-www-form-urlencoded;charset=ISO-8859-7',
type : 'POST',
data : UrlToPass,
success: function(responseText) {
try{
$('#as_gridder').html(responseText);
} catch (e) {
//IE8
$('#as_gridder').innerHTML = responseText;
}
}
});
}
I have this PHP CodeIgniter code where in the view I am getting input from a text field. Using AJAC I am trying to pass this value to the controller using GET request. The controller will then call a function from my model to retrieve a database record matching the search criteria.
For some reason it doesn't work. I tried to do a var dump in the controller to see if the value is passed by AJAX, but I am not getting anything. Any ideas what I am doing wrong and why I can't receive the form value in the controller?
View:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.13.3/jquery.min.js"</script>
<script language="Javascript">
$(document).ready(function () {
$('#submitbutton').click(function () {
$.ajax({
url: "../../index.php/testcontroller/getdatabasedata",
data: {
'searchvalue' : $('#inputtext').val()
},
method: 'GET'
}).done(function (data) {
var dataarray = data.split('##');
$('#question').html(dataarray[ 1 ]);
$('#answer1').html(dataarray[ 2 ]);
});
return false;
});
});
</script>
</body>
Controller
public function getdatabasedata()
{
$this->load->model('testmodel');
$year = $this->input->get('searchvalue');
//I TRIED TO DO A VARDUMP($YEAR) BUT I DON'T GET ANYTHING!
$movie = $this->testmodel->findquestion($year);
$moviesstring = implode(",", $movie);
echo $moviesstring;
}
Model
function findquestion($searchvalue)
{
$this->db->where('answer1', $searchvalue);
$res = $this->db->get('questions');
var_dump($res)
if ($res->num_rows() == 0)
{
return "...";
}
$moviearray = $res->row_array();
return $moviearray;
}
Script:
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script language="Javascript">
$(document).ready(function ()
{
$("#submitbutton").bind("click",function()
{
var target_url = '<?php echo(base_url()."testcontroller/getdatabasedata") ; ?>';
var data = {'searchvalue' : $('#inputtext').val() };
$.ajax ({
url : target_url,
type: 'GET',
data: data,
cache: false,
success: function(controller_data)
{
var dataarray = controller_data.split('#');
$('#question').html(dataarray[1]);
$('#answer1').html(dataarray[3]);
},
});
return false;
});
});
</script>
.bind("click",function() - add quotes to click event.
var dataarray = controller_data.split('#'); - split
data caracter must match character in implode function in controller.
Controller:
public function getdatabasedata(){
$this->load->model('testmodel');
$year = $this->input->get('searchvalue');
$movie = $this->testmodel->findquestion($year);
$separated = implode("#", $movie);
echo $separated;
}
Hope this helped.
I will share my usual ajax code that I use in my views , make sure your base url is correct
$("#submitbutton").bind("click",function()
{
var target_url = '<?php echo(base_url()."testcontroller/getdatabasedata") ; ?>';
$.ajax
(
{
url : target_url,
type: "GET",
// data: {'searchvalue' : $('#inputtext').val()},
cache: false,
success: function(data)
{
alert(data);
},
error: function(jqXHR, textStatus, errorThrown)
{
alert("error during loading ....");
}
});
});// end loading via ajax
and in your controller just echo something
public function getdatabasedata()
{
//$this->load->model('testmodel');
//$year = $this->input->get('searchvalue');
//I TRIED TO DO A VARDUMP($YEAR) BUT I DON'T GET ANYTHING!
//$movie = $this->testmodel->findquestion($year);
//$moviesstring = implode(",", $movie);
//echo $moviesstring;
echo "hello";
}