Problem with ajax - sending everythink to linkbar like GET option - php

a problem with ajax because everytime when I want to click submit button then shows everythink in linkbar like 127.0.0.1:8000/?token[...] etc with every parameter it looks like method GET in form html but I haven't any method there. I think my code don't even try to execute Routes because I haven't any issue with json or database
$('#saveBtn').on('click', function () {
ajax: {
url: "{{route('res.Add')}}",
type: "post",
dataType: 'json',
delay: 250,
data: function (params) {
return {
_token: CSRF_TOKEN,
search: params.term // search term
};
},
processResults: function (response) {
return {
results: response
};
},
cache: true
}
});
///BUTTON
<button type="submit" class="btn btn-primary" id="saveBtn">Add</button>
And Route link
Route::post("/res/Add", "ResController#addRes")->name('res.Add');

Related

Can't send id to resource controller destroy function in Laravel 5.5

$("#dialog-confirm").dialog({
resizable: false,
height: "auto",
width: 400,
modal: true,
autoOpen: false,
buttons:
{
"Delete Student": function(event)
{
event.preventDefault();
$.ajax({
type: "POST",
data: {
id: "$(this).data('studentId')",
_method: "DELETE",
},
url: "{{ route('students.destroy') }}",
success: function(result) {
alert('ok');
},
error: function(result) {
alert('error');
}
});
$(this).dialog("close");
},
Cancel: function()
{
$(this).dialog("close");
}
}
});
$(".deleteButton").on("click",function()
{
$("#dialog-confirm").data('studentId',$(this).closest("td").find("input[name='studentId']").val()).dialog("open");
});
I have this code to delete the student after confirmation via dialog box. I want to send id of student to destroy function(working fine coz I have checked by deleting student without dialog box first) of StudentController. I have also tried url:"URL::route('students.destroy')" or url:"URL::to('/students/')"
but nothing working. By inspecting,
this error is coming Please help, any type of suggestions to delete the student would be welcome but dialog box is must ... :)
For doing a delete pass the id as a url param instead of post data and url a normal url and pass the id to that.
var id = $(this).data('studentId');
$.ajax({
type: "POST",
data: {
_method: "DELETE",
},
url: '/students/destroy/'+id,
success: function(result) {
alert('ok');
},
error: function(result) {
alert('error');
}
});
BTW: method: "DELETE" must be in the first node of first ajax function arguments so you don't need the form method spoofing (https://laravel.com/docs/5.5/routing#form-method-spoofing)
$.ajax({
method: "DELETE",
data:{...},
...
AND
the route helper function needs the id for your student model instance:
{{ route('students.destroy', [$student->id]) }}
but only in a Blade file so you mix php syntax with HTML/JS or whatever
(I really dislike this JS in Blade, but sometimes for very local unique "problems" it is the quickest solution, hopefully "cut and dry")

getting 404 not found when submitting form using ajax in laravel

I am new with laravel, I am having an issue when posting my data to controller in laravel while using ajax. My view contains a select box which is populated from database when a user select a value from select box i am trying to call ajax which will return details of salary of the user.The issue is it gives me 404 not found error.
The Code for the controller file is shown below.
this function is defined inside a controller
public function getPostSalary()
{
echo "ajax called";
return 'true';
}
The Routes file is
Route::post('company/salary-user', 'CompanyController#getPostSalary');
this is my ajax code from where the controller is being calleD
<script>
$(document).ready(function() {
$('#employee').change(function () {
var values = $('#employee').val();
if (values == '') {
$.pnotify({
title: 'Message',
text: 'Please Select a User.',
type: 'error',
delay: 3000
});
return false;
}
var csrf = $('#csrf').val();
$.ajax({
url: '{!! URL::to("company/salary-user")!!}',
type: "POST",
data: { user_id: values, _token: csrf },
cache: false,
beforeSend: function () {
},
success: function (data) {
console.log(data);
$('#loader').hide();
}
});
});
});
</script>
Can someone help me to figure out what is the issue and what should be done to call my function.
Single quotes is for string so your url is not generating as you expecting. Use like this
url : "{!! URL::to('company/salary-user')!!}",
You can use direct url like
$.ajax({
url:'company/salary-user',
type: "POST",
data: { user_id: values, _token: csrf },
cache: false,
beforeSend: function () {
},
success: function (data) {
console.log(data);
$('#loader').hide();
}
});
replace this line:
{!! URL::to("company/salary-user")!!}
by :
{{ url('/company/salary-user') }}
or
{{ route('/company/salary-user') }}

Select 2 ajax call not populating with results

Just downloaded a select2 files from github, the latest release 4.0.3, and i want to populate the options based on what i'm typing (ajax request)
heres the code
$('#usernetwork').select2({
ajax: {
url: 'someurl.php',
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, page) {
return data.items;
},
cache: false
},
minimumInputLength: 1
});
the url (someurl.php) shows this json result
[{"id":"1","text":"ClickWeb"},{"id":"2","text":"ClickWeb 1"},{"id":"3","text":"ClickWeb 2"},{"id":"4","text":"ClickWeb 3"}]
and finally the select field is this
<select name="usernetwork" id="usernetwork" class="form-control">
</select>
this is the very first time i try this for now im getting nothing as query (for test purposes)
The results are not showing up, and i have no idea on how to fix this, any tips?
Try my answer the only thing you need to change is your return statement inside processResults callback like this
return {
results: data
};
Here is full code :
$('#usernetwork').select2({
ajax: {
url: 'someurl.php',
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, page) {
return {
results: data
};
},
cache: false
},
minimumInputLength: 1
});

Passing data from view to controller using ajax

I am trying to send some data on button click to a controller and display the response in a content div back in the view. However i am facing problem while sending the data to the controller. Here is what i am trying to do :
test.php
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$.ajax({
type: 'GET',
url: 'get-response',
dataType: 'json',
data: {
"id": "1"
},
success: function(response){
$('#content').html(response.first);
}
});
});
$("#btn2").click(function(event){
$.ajax({
type: 'GET',
url: 'get-response',
dataType: 'json',
data: {
"id": "2"
},
success: function(response){
$('#content').html(response.first);
}
});
});
});
</script>
<input type="button" id="btn1" value="Button1 Content" />
<input type="button" id="btn2" value="Button2 Content" />
<br>
<div id="content"></div>
route.php
Route::get('ajax-example', function(){
return View::make('test');
});
Route::get('get-response/{id}', array('as'=>'get-response', 'uses'=>'AjaxController#getResult'));
AjaxController.php
public function getResult($id){
if($id==1){
$content = "Hello";
}
else if($id==2){
$content = "World";
}
return Response::json(array('first'=>$content));
}
Error
Can anyone please help me out here. I am a bit confused right now. Thanks :)
if you need to get the parameter do this,
Input::get('id');
and route
Route::get('get-response', array('as'=>'get-response', 'uses'=>'AjaxController#getResult'));
because your ajax request is something like, host/get-response?id=5 and this is not compatible with Route::get('get-response/{id}'.., because this route needs something like host/get-response/5
Another way, you can keep your route as u declared and change the ajax request url,
$.ajax({
type: 'GET',
url: 'get-response/'+1,
dataType: 'json',
data: {},
success: function(response){
$('#content').html(response.first);
}
});
ok so i guess i figured it out what was causing the problem.
I changed my route to
Route::get('get-response', array('as'=>'get-response', 'uses'=>'AjaxController#getResult'));
and in controller i added
public function getResult(){
$id = $_GET['id'];
Now it seems to working just fine :)

my jquery ajax form submit doesnt work

I have the following javascript that's using ajax with jquery to submit a form.
$(function() {
$("#signform").submit(function() {
alert();
$.ajax({
type: "POST",
url: "page/sign.php",
data: { mail: $("#inputEmail").val(),
pass: $("#inputPassword").val(),
nick: $("#inputNick").val(),
date: $.datepicker.formatDate('yy/mm/dd', new Date()) },
sucsess: handler,
error: function(err) { alert('error: ' + err.status) }
});
});
function handler(var){
$('#message').html(val);
}
});
and html code is here, using bootstrap !
<form class="form-horizontal" id="signform">
// ... something codes
<div class="form-group">
<div class="col-offset-2 col-lg-10" align="center">
**<button type="submit" class="btn btn-default">Sign in</button>**
<button type="button" class="btn">Cancel</button>
</div>
</div>
</form>
When I pressed the submit button, it went to the index page.
I don't know what is wrong.
js code is in the same page in sign.php
You are not preventing the default action of the submit button, you can either call event.preventDefault(), or return false from the submit handler to fix this
Also in the handler method the parameter was called var which is invalid
$(function() {
$(document).on('submit', "#signform", function(e) {
$.ajax({
type: "POST",
url: "page/sign.php",
data: {
mail: $("#inputEmail").val(),
pass: $("#inputPassword").val(),
nick: $("#inputNick").val(),
date: $.datepicker.formatDate('yy/mm/dd', new Date())
},
success: handler,
error: function(err) {
alert('error: ' + err.status)
}
});
return false; //this will prevent the default action and will stop the event propagation
//if you do not want to stop event propagation you can use
//e.preventDefault();
});
function handler(val){ //also invalid variable name var here
$('#message').html(val);
}
});
Try this, It will help you better, Here U=page URL, F=Page method,D=Data
U=sign.php,
F=page,
D="mail: '+$("#inputEmail").val()+',pass: '+$("#inputPassword").val()+',nick: '+$("#inputNick").val()+',date: '+$.datepicker.formatDate('yy/mm/dd', new Date())+'"
// function for call page method using ajax
function Operation(U, F, D) {
$.ajax({
type: "POST",
url: U + '/' + F,
data: D,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
cache: false,
success: function (r) {
var str = r.d;
});
}

Categories