Why route() function does now works using laravel? - php

In my laravel package the route does not working it is showing following incorrect route in debugger
Request URL: http://localhost:8000/%7B%7B%20route('contact')%20%7D%7D
However my route is as following
Route::group(['namespace' => 'ayazdev\Contact\Http\Controllers'], function(){
Route::get('contact', 'ContactController#index')->name('contact');
Route::post('contact', 'ContactController#send')->name('sendForm');
});
And following is where I am calling the route
$(function(){
$("#contact-form").submit(function(e) {
var form = $(this);
$.ajax({
type: "POST",
url: "{{ route('contact') }}",
data: form.serialize(),
success: function(data)
{
alert(data);
}
});
e.preventDefault();
});
});
if above detail does not enough to understand then you can kindly check it on github.
Can someone kindly guide me why it is now working, I will appreciate. Thanks

The curly braces are part of the Laravel Blade views, but you are using this in a JavaScript file. This code is not parsed by Laravel, so you cannot use php functions here.
If you want to get named routes in your JavaScript code, you will have to render them into a JavaScript variable or use a package like Ziggy to get route functionality in JavaScript.

As noted by Jerodev the curly braces are from Laravel Blade and you are probably using it in a Javascript file. Either you can move it to a blade file as such:
<script>
$(function(){
$("#contact-form").submit(function(e) {
var form = $(this);
$.ajax({
type: "POST",
url: "{{ route('contact') }}",
data: form.serialize(),
success: function(data)
{
alert(data);
}
});
e.preventDefault();
});
});
</script>
Or if you prefer to keep it in a separate file you can have a tag with just the information about that route and get it via jQuery as you are doing:
// at the blade file add
<div id="routeToContact" data-route="{{ route('contact') }}">
// At the javascript file you can do the following
var route = $("#routeToContact").data('route');
$("#contact-form").submit(function(e) {
var form = $(this);
$.ajax({
type: "POST",
url: route,
data: form.serialize(),
success: function(data)
{
alert(data);
}
});
e.preventDefault();
});
As a personal taste I would chose the second method to keep everything organized but as my mom always said: "choose what your heart beats for"

You are using a Blade syntax in a simple Javascript file.
Try to do the following:
$(function(){
$("#contact-form").submit(function(e) {
var form = $(this);
$.ajax({
type: "POST",
url: "<?= route('contact'); ?>",
data: form.serialize(),
success: function(data)
{
alert(data);
}
});
e.preventDefault();
});
});
That way, you use PHP itself to get the address of the desired route.
See more about this sintax in: https://secure.php.net/manual/pt_BR/ini.core.php#ini.short-open-tag

Related

Laravel ajax not returning data

I am having trouble retrieving data from Controller using ajax
this is my code
the trigger
<select id="course_select" name="course_select" class="form-control" required autofocus value="{{old('course_select')}}" onchange="getCourse()">
The my ajax section
function getCourse(){
var id=document.getElementById('course_select').value;
alert(id);
$.ajax({
type:'get',
url:'getCourseLessons/'+id,
datatype:'json',
success:function(data){
console.log(data);
alert(data.lessons);
}
});
}
and my controller
public function getCourseLessons($id){
$lessons = DB::table('lessons')->select('id','Lesson_name')->where('course_id','=',$id)->get();
return response()->json(array('lessons'=>$lessons));
}
Results console.log(data)
console.log(data)
ReferenceError: data is not defined[Learn More]
My Routes.
Route::get('/getcourselessons/{id}','AdminController#getCourseLessons');
I will appreciate all the help i can get.
First of all please check the route you used in Route/Web.php it should be like this
Route::get('getCourseLessons/{id}','YourController#getCourseLessons');
Check the controller.
public function getCourseLessons($id){
$lessons = \DB::table('lessons')->select('id','Lesson_name')->where('course_id',$id)->get();
return response()->json(array('lessons'=>$lessons));
}
As per your ajax code is ook but you can try this also.
function getCourse(){
var id=$('#course_select').val();
alert(id);
$.ajax({
type:'get',
url:'{{url('getCourseLessons')}}/'+id,
datatype:'json',
success:function(data){
console.log(data);
alert(data.lessons);
}
});
}
<select id="course_select" name="course_select" class="form-control" onchange="getCourse()">
<option>hi</option>
<option>hello</option>
</select>
It seems that there is problem in your select as the above code will output
check the following
value="{{old('course_select')}}"
and one more thing I can't see CSRF
Add somewhere in your script
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
1- cheek your route
Route::get('/getCourseLessons/{id}','YourController#getCourseLessons');
2- change your Ajax attributes
function getCourse(){
var id=document.getElementById('course_select').value;
alert(id);
$.ajax({
url: '{{ url("getCourseLessons") }}',
type:'get',
datatype:'json',
data: {
"id": id,
"_token": "{{ csrf_token() }}"
},
success:function(data){
console.log(data);
alert(data.lessons);
}
});
}
try this bro change you url or route
function getCourse(){
var id=document.getElementById('course_select').value;
var url = '{{ url('getCourseLessons/')}}/'+id;
alert(id);
$.ajax({
type:'get',
url:url,
datatype:'json',
success:function(data){
console.log(data);
alert(data.lessons);
}
});
}
change your route
Route::get('getcourselessons/{id}','AdminController#getCourseLessons');

Add custom $_POST before submitting form with jquery

First of all, sorry if this is a duplicate. I've looked and seen some solutions but none worked. I've been trying to do this simple thing for like 3 hours with no result.
I'd have this html:
<form method="post" action="?c=Logo&action=save" id="form">
<!-- some inputs -->
<img src="" data-filename="new-logo.png">
<input type="submit" value="submit">
</form>
Here I'd like to modify the form so my php file will recognise $_POST['new-logo'].
// $_POST['new-logo'] = $('img').data('filename')
$logo = new Logo($_POST['new-logo']);
$logo->save();
I guess I should use the jQuery function $.post() but somehow I can't manage. Thank you all for your help :-)
SOLUTION
Finally since I found a very simple solution. Since I want my data to be processed in my php file, I simply added an <input type="hidden"> and modified its value with JS :-)
You could also make the data array from scratch like this:
$('#form').on('submit', function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: $(this).attr('action'),
data: {key1:"value", key2:"value2"},
dataType: "json",
success: function(data) {
//do success stuff here
},
error: function() {
//do error stuff here.
}
});
});
You can add it as a hidden input.
$("#form").submit(function() {
$(this).append($("<input>", {
type: "hidden",
name: "new-logo",
value: $(this).find("img").data("filename")
});
});
you can add this to you're post request like this :
$('#form').on('submit', function(e){
e.preventDefault();
var $form = $(this);
var datastring = $form.serializeArray();
datastring.push({name:'new-logo', value:$form.find('img').data('filename')});
$.ajax({
type: "POST",
url: $form.attr('action'),
data: datastring,
dataType: "json",
success: function(data) {
//var obj = jQuery.parseJSON(data); if the dataType is not specified as json uncomment this
// do what ever you want with the server response
},
error: function() {
alert('error handing here');
}
});
});
$logo = new Logo($_POST['new-logo']);
Is "new Logo" a function or something? Pretty sure that can't have a space.

Multiple jQuery AJAX calls conflicts?

I am trying to create a simple shopping cart using AJAX and PHP.
Everything works as it should BUT 1 thing doesn't work all the time and it seems that it fails to execute. (it works 3 times out of 5).
to explain this issue please take a look at the code bellow:
jQuery(document).ready(function() {
//////////////////////LETS RUN OUR ADD TO CART FEATURE USING AJAX //////////////
$(function(){
$('.form1').on('submit', function(e){
$( "#preloader" ).fadeIn( 850 );
// prevent native form submission here
e.preventDefault();
// now do whatever you want here
$.ajax({
type: $(this).attr('method'),// <-- get method of form
url: $(this).attr('action'),
//url: "cart.php",
data: $(this).serialize(), // <-- serialize all fields into a string that is ready to be posted to your PHP file
beforeSend: function(){
},
success: function(data){
$( "#preloader" ).fadeOut( 850 );
}
});
});
});
//////////////////////LETS RUN LOAD THE cart-header.php ON PAGE LOAD USING AJAX //////////////
$(document).ready(function () {
function load1() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "cart-header.php",
dataType: "html", //expect html to be returned
success: function (data2) {
$('#headerCart').html($(data2));
//setTimeout(load2, 500);
}
});
}
load1();
});
//////////////////////LETS LOAD THE cart-header.php on form1 submit USING AJAX //////////////
<!----- This is the part that SOMETIMES Fails to work --->
$(function(){
$('.form1').on('submit', function(load2){
// prevent native form submission here
load2.preventDefault();
// now do whatever you want here
$.ajax({
type: "GET",// <-- get method of form
url: "cart-header.php",
//url: "cart.php",
dataType: "html", // <-- serialize all fields into a string that is ready to be posted to your PHP file
beforeSend: function(){
},
success: function(data){
//$('#test').load('cart.php #total').html();
$('#headerCart').html($(data));
}
});
});
});
//////////////////////LETS RUN OUR DELETE FROM CART FEATURE USING AJAX //////////////
$(document).on('submit', '.delForm', function(dleItem){
// prevent native form submission here
dleItem.preventDefault();
// now do whatever you want here
$.ajax({
type: $(this).attr('method'),// <-- get method of form
url: "cart-header.php",
//url: "cart.php",
data: $(this).serialize(), // <-- serialize all fields into a string that is ready to be posted to your PHP file
beforeSend: function(){
},
success: function(data){
$('#headerCart').html($(data));
}
});
});
});
//////////////////////LETS GET THE QUANTITY OF CURRENT ITEMS ADDED IN THE CART USING AJAX/////////////
$(document).ready(function () {
function load() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "cart.php",
//url: "cart-header.php",
dataType: "html", //expect html to be returned
success: function (data) {
$('.item_count').html($(data).find('#total').text());
//$('#headerCart').html($(data));
setTimeout(load, 1000);
}
});
}
load();
});
I have commented the code so you can see the parts of the code and what they do.
the issue is this part:
//////////////////////LETS LOAD THE cart-header.php on form1 submit USING AJAX //////////////
<!----- This is the part that SOMETIMES Fails to work --->
$(function(){
$('.form1').on('submit', function(load2){
// prevent native form submission here
load2.preventDefault();
// now do whatever you want here
$.ajax({
type: "GET",// <-- get method of form
url: "cart-header.php",
//url: "cart.php",
dataType: "html", // <-- serialize all fields into a string that is ready to be posted to your PHP file
beforeSend: function(){
},
success: function(data){
//$('#test').load('cart.php #total').html();
$('#headerCart').html($(data));
}
});
});
});
As I mentioned above, this code works fine but it only works when it wants to as if it has mind of its own!
could someone please advise on this issue?
Thanks in advance.

how to do $_POST for datepicker in php/codeigniter

First, I'm using the codeigniter framework and I'm a beginner in JS and AJAX, so please bear with me.
I read this question, so I tried to follow the answers.
This is the script (UPDATED):
$(function() {
$( "#datepicker").datepicker().click(function() {
$.ajax({
type: 'POST',
url: "<?php echo base_url(); ?>backend/umat/add",
dataType: "json",
data: $('#form_daftar').serialize(),
success: function(data) {
console.log("Done");
}
});
return false;
});
});
And this is my datepicker HTML code:
<input type="text" id="datepicker" name="datepicker"
value="<?php echo isset($umat['tanggal_lahir'])?$umat['tanggal_lahir']:""?>"/>
My questions are (UPDATED):
Is the URL I provided in AJAX above correct?
How should I pass the data from AJAX to PHP (url: "<?php echo base_url(); ?>backend/umat/add")?
Thanks for your help :D
What you have missed here:
your click event is outside of the doc ready handler, that should be inside doc ready so that when page gets ready the element should be available to click.
You have missed a closing }); tag of the click event.(does not matter though)
so try this:
$(function() {
$( "#datepicker").datepicker();
$("#datepicker").click(function() {
$.ajax({
type: 'POST',
url: "<?php echo base_url(); ?>backend/umat/add",
dataType: "json",
data: {frmData : $('#form_daftar').serialize()}, // <----send this way
success: function(data) {
console.log(data.date);
// here data is the returned data from the specified url and make sure
// that url is generating a proper json structrue.
// suppose there is a key named date which holds the submitted date so
// data.date will get you the date.
}
});
}); //<----you missed this closing of click function.
}); //<----------put everything before this closing of doc ready handler.
Although you can chain it too like this:
$(function(){
$( "#datepicker").datepicker().click(function() {
//......ajax function in click here
});
});
See a demo here
Another approach would be to use the datepicker inbuilt methods to trigger ajax request like
$('#datepicker').datepick({
dateFormat:"yyyy-mm-dd",
onSelect:function(){
$.ajax({
type: 'POST',
url: "<?php echo site_url('backend/umat/add'); ?>",
dataType: "json",
data: $('#form_daftar').serialize(),
success: function(data) {
console.log("Done");
}
});
}
});
Check the manual or inbuild functions and callbacks with your datepicker js.
try it:
$(function() {
$( "#datepicker").datepicker();
$("#datepicker").change(function() {
$.ajax({
type: 'POST',
url: "<?php echo base_url(); ?>backend/umat/add",
dataType: "json",
data: $('#form_daftar').serialize(),
success: function(data) {
console.log("Done");
}
});
});
php get data form ajax:
<?php
$date = $_POST["datepicker"];
?>

ajax jquery with codeigniter. url doesnt access controller

I am new to codeigniter and cannot get my ajax to work.
I am trying to make links load content into the main document on click.
I looked for instructions but could not figure it out. All works except the ajax returns alert('ERROR') message. nothing is loadded into <div id='load_here'></div>
Maybe I am missing something in config.php? Do i have to load some library for this to work?
Any ideas would be helpfull
//main document link
<span id='reg_link_rules'>Link</span>
<div id='load_here'></div>
// controller
class Register extends CI_Controller {
public function hello()
{
echo 'hello';
}
}
// jQuery
$(document).ready(function() {
$('#reg_link_rules').click(function(eve){
$.ajax({
type: "GET",
url: "register/hello",
complete: function(data){
$('#load_here').html(data);
},
error: function(){alert('error');}
});
});
});
I think the problem is that the ajax url does not access the controller.
Z:/home/codeigniter/www/register/test this is where i think it takes me
problem solved, the url needed to be http://codeigniter/index.php/register/hello
Try with url: "/register/hello".
Might do the trick.
Usually I do a
<script type="text/javascript">
base_url = '<?=base_url()?>';
</script>
At the beginning of my page and simply
base_url+"register/hello"
instead
That makes my ajax more reliable, even when / is incorrect.
complete: function(data){
$('#load_here').html(data);
},
should be
Just referencing another SO question ... Use success() or complete() in AJAX call
success: function(data){
$('#load_here').html(data);
},
AND
$.ajax({
type: "GET",
Should be
unless you want your form vars to be submitted along in the URL.
$.ajax({
type: "POST",
Hello You should add the base url to the URL Ajax.
$.ajax({
type: "GET",
url: <?php echo base_url();?>"register/hello",
complete: function(data){
$('#load_here').html(data);
},
Remember enable the helper URL in the Controller!
Cheers
you need to pass the bas_url to ajax file
<script type="text/javascript">
$(document).ready(function(e) {
var baseurl = <?php echo base_url();?>
$('#reg_link_rules').click(function(){
$.ajax({
url : baseurl+'index.php/register/hello',
data : '',
type: "POST",
success : function(){
}
})
return false;
})
});
</script>
Sometimes you have do add index.php to the string. Like so:
$.ajax({
type: "GET",
url: <?php echo base_url();?>"index.php/register/hello",
complete: function(data){
$('#load_here').html(data);
},
But it's all about your config file however. It was the mistake in my case.
Hope it helps.
You need to ensure two matter
please put your ajax part as url: ?php echo base_url();?>"register/hello", and type: "GET", and also need to check wheter it is routed the url on config/routes.php.

Categories