Send data to Laravel controller using ajax - ajax

I'm trying to send POST request to a Laravel controller using ajax, BUT nothin happen
Script
<script>
(function($) {
jQuery('#categorie,#marque').change(function () {
var id_marq=$('#marque').val();
var id_cat=$('#categorie').val();
var url = $('#application_url').val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: url+"/produits/ajoutPrixProduit",
type:"POST",
data:{'id_cat':id_cat, 'id_marq':id_marq},
dataType: "json",
success: function (response) {
$.each(response, function (key, value) {
$('#nom').append('<option value="' + key.id + '">' + value.libelle + '</option>');
});
}
});
})(jQuery);
});
Route
Route::post('/produits/ajoutPrixProduit', 'MagasinBoardController#selProduit')->name('magasin.selProduit');
Controller
public function selProduit(Request $request)
{
$id_cat=$request->id_cat;
$id_marq=$request->id_marq;
.......
return response()->json($listProd);
}
I don't know why and how to fix it

Related

ajax() in Laravel 7

My AJAX code is like below
$('select[id="state"]').on('change', function() {
var stateID = $(this).val();
if(stateID) {
$.ajax({
url: '/cities',
type: "GET",
data: { id: 7},
success:function(data) {
$('select[name="city"]').empty();
$.each(data, function(key, value) {
$('select[name="city"]').append('<option value="'+ key +'">'+ value +'</option>');
});
},
error: function(xhr, status, error){
var errorMessage = xhr.status + ': ' + xhr.statusText
alert('Error - ' + errorMessage);
}
});
}else{
$('select[name="city"]').empty();
}
});
My route is like below
Route::get('/cities/{id}', 'LocationController#getSelectedCityajax');
My controller code is like below
public function getSelectedCityajax($id)
{
return response()->json([
'success'=>'get your data'
]);
}
But I am getting result like below
Error - 400: Bad Request
If your route is -Route::get('/cities/{id}', 'LocationController#getSelectedCityajax');
then ajax call should be-
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
},
})
$('select[id="state"]').on('change', function() {
var stateID = $(this).val();
if(stateID) {
$.ajax({
url: '/cities/7',
type: "GET",
success:function(data) {
$('select[name="city"]').empty();
$.each(data, function(key, value) {
$('select[name="city"]').append('<option value="'+ key +'">'+ value +'</option>');
});
},
error: function(xhr, status, error){
var errorMessage = xhr.status + ': ' + xhr.statusText
alert('Error - ' + errorMessage);
}
});
}else{
$('select[name="city"]').empty();
}
});
and if u want send data by post request then route should be -
Route::post('/cities', 'LocationController#getSelectedCityajax');
AJAX Request would be -
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
},
})
$.ajax({
url: '/cities',
type: "post",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: { id: 7},
success:function(data) {
$('select[name="city"]').empty();
$.each(data, function(key, value) {
$('select[name="city"]').append('<option value="'+ key +'">'+ value +'</option>');
});
},
error: function(xhr, status, error){
var errorMessage = xhr.status + ': ' + xhr.statusText
alert('Error - ' + errorMessage);
}
});
And controller code -
public function getSelectedCityajax(Request $request)
{
$id = $request->get('id');
return response()->json([
'success'=>'get your data'
]);
}

How to bind AJAX method's result value with html.?

AJAX method
Now , I want the count variable to bind with html and need help as i don't have enough knowledge of AJAX
$.ajaxSetup({
beforeSend: function (xhr) {
var token = localStorage.getItem('ngStorage-premier_agent_token')
var value = 'Bearer ' + JSON.parse(token)
xhr.setRequestHeader('Authorization', value);
}
});
$.ajax({
url: "/api/activity/listcount",
type: "GET",
success: function (data) {
console.log(JSON.stringify(data))
var count=data.count;
}
});
added a container where you want to print your HTML, like a div
<div></div>
and then append the result to that div on your success function
$.ajax({
url: "/api/activity/listcount",
type: "GET",
success: function (data) {
console.log(JSON.stringify(data))
$("div").append("result is" + data.count);
}
});

Why i can not fetch data from controller from ajax function?

I'm beginner in asp.net mvc ,and want to fetch simple json from controller to ajax variable,for that purpose in view page write this ajax function:
<script>
var OutPut;
OutPut = "behzad";
function CallService() {
$.ajax({
url: '#Url.Action("callService", "myPassword")',
type: 'GET',
dataType: 'json',
cache: false,
data: { 'id': 2 },
success: function (color) {
OutPut= color;
},
error: function () {
alert('Error occured');
}
});
alert("I think is ok!"+":"+OutPut);
}
</script>
and this controller:
[HttpGet]
public JsonResult callService(int id)
{
string JSON = "behzad";
return Json(JSON,JsonRequestBehavior.AllowGet);
}
that ajax function call with this html code in view page:
<button type="button" class="btn btn-success" onclick="CallService()">Success</button>
but this line in ajax function:
alert("I think is ok!"+":"+OutPut);
Output is undefined,what happen?is controller return null?or why i get undefined alert?thanks.
Since the AJAX call is asynchronous, you should place the alert inside the success callback:
<script>
function CallService() {
$.ajax({
url: '#Url.Action("callService", "myPassword")',
type: 'GET',
cache: false,
data: { 'id': 2 },
success: function (color) {
alert("I think is ok!" + ":" + color);
},
error: function () {
alert('Error occurred');
}
});
}
</script>

Ajax call to Webmethod, cross domain

I have two Asp projects. On close of a dialog box in project A I am trying to call a static webmethod in project B using ajax call.
Instead of calling the Webmethod it is calling the PageLoad.
Any ideas what I am doing wrong?
WebMethod
[WebMethod]
public static string UpdateSession()
{
return "Test";
}
$(function () {
$('div#DialogDiv').on('dialogclose', function (event) {
CloseDialog("http://localhost:1330/Application_Default.aspx/UpdateSession");
return false;
});
});
function CloseDialog(URL) {
jQuery.support.cors = true;
$.ajax({
type: "GET",
url: URL,
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
success: function (response) {
alert("success");
},
failure: function (response) {
alert("Failed to trying to find the method: " + URL );
}
});
return false;
}
Try this with pure javascript
function CloseDialog(URL) {
var request = new XMLHttpRequest();
request.open("GET", URL);
request.onload = function() {
if (request.status === 200) {
alert(request.responseText);
// to convert to JSON object-> JSON.parse(request.responseText);
} else {
alert("Failed to trying to find the method: " + URL );
}
};
request.send();
return false;
}
With jQuery I would just do this, you don't need more. It should work with cross-domain too.
function CloseDialog(URL) {
$.ajax({
url: URL,
success: function (response) {
jQuery.each(result.list, function(i, val) {
// iterate the JSON object
// val.node;
});
},
failure: function (response) {
alert("Failed to trying to find the method: " + URL );
}
});
return false;
}

Converting MVC Ajax to Jquery

I am in the process of learning how to convert MVC Ajax to jquery ajax so I can do more.
This is the old ajax, I took out the loading stuff
#Ajax.ActionLink("Update Tweets", "Index", "Home",
new AjaxOptions
{
UpdateTargetId = "TweetBox",
InsertionMode = InsertionMode.InsertBefore,
HttpMethod = "Get",
})
I need to convert this to jquery ajax. It seems to be working lets see the code
<script>
$(document).ready(function () {
$("#StartLabel").click(function (e) {
$.ajax({
type: "Get",
url: '/Home/Index',
// data: "X-Requested-With=XMLHttpRequest",
// contentType: "application/text; charset=utf-8",
dataType: "text",
async: true,
// cache: false,
success: function (data) {
$('#TweetBox').prepend(data);
alert('Load was performed.');
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
},
complete: function (resp) {
alert(resp.getAllResponseHeaders());
}
});
});
});
</script>
In the microsoft ajax it sets XML Request in the headers. Do I need to add that too? I am just paging my controller that performs a query to twitter and appends the data to the top.
I am using fiddler to see how the requests are different but the results are the same.
I also noticed if i put the text in the data: object its puts it in the header. i dont think that is right by any means.
You could define a normal anchor:
#Html.ActionLink("Update Tweets", "Index", "Home", null, new { id = "mylink" })
And then unobtrusively AJAXify it:
$(document).ready(function () {
$("#mylink").click(function (e) {
$.ajax({
type: "GET",
url: this.href,
success: function (data) {
$('#TweetBox').prepend(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
},
complete: function (resp) {
alert(resp.getAllResponseHeaders());
}
});
return false;
});
});
Notice that I return false from the click handler in order to cancel the default action. Also notice that I am using the anchor's href property instead of hardcoding it.
The 2 AJAX requests should be identical.
Here is simple example using Ajax with Jason data
// Post JSON data
[HttpPost]
public JsonResult JsonFullName(string fname, string lastname)
{
var data = "{ \"fname\" : \"" + fname + " \" , \"lastname\" : \"" + lastname + "\" }";
return Json(data, JsonRequestBehavior.AllowGet);
}
in the view add a reference to the query as following
#section Scripts{
<script src="~/Scripts/modernizr-2.6.2.js"></script>
<script src="~/Scripts/jquery-1.8.2.intellisense.js"></script>
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
}
in the view add the js
note: (jsonGetfullname).on is a button
<script type="text/javascript">
$("#jsonGetfullname").on("click", function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "#(Url.Action("JsonFullName", "Home"))",
data: "{ \"fname\" : \"modey\" , \"lastname\" : \"sayed\" }",
dataType: "json",
success: function (data) {
var res = $.parseJSON(data);
$("#myform").html("<h3>Json data: <h3>" + res.fname + ", " + res.lastname)
},
error: function (xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
}
})
});
</script>
you can also use (POST\GET) as following:
[HttpPost]
public string Contact(string message)
{
return "<h1>Hi,</h1>we got your message, <br />" + message + " <br />Thanks a lot";
}
in the view add the js
note: (send).on is a button
$("#send").on("click", function () {
$.post('', { message: $('#msg').val() })
.done(function (response) {
setTimeout(function () { $("#myform").html(response) }, 2000);
})
.error(function () { alert('Error') })
.success(function () { alert('OK') })
return false;
});

Resources