Send Request In Laravel Using AJAX GET Method - javascript

Want to Access Show function data through AJAX, but it returns error when i passed id variable in route
Contoller
public function show($id)
{
$features['UnitFeatures'] = UnitFeatures::find($id);
return $features;
}
View Blade File
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var feature_id = $('#unitFeatures').val();
$.ajax({
url: '{{ route('unitfeatures.show',feature_id) }}', // error in this line when i pass feature_id value to route
type: 'GET',
dataType: 'json',
success: function(response){
console.log(response);
}
});
});
Please give me a solution

The problem is that you cannot access a JS variable in your {{}} PHP code.
You will have to get the route uri and replace the placeholder manually in your JS code.
You can get the URI of your Route with this piece of code:
\Route::getRoutes()->getByName('unitfeatures.show ')->uri
This returns the uri as a string like that: /sometext/{id}
Now you can simply replace the {id} with the feature_id by using str.replace() or whatever function you like.
var feature_id = $('#unitFeatures').val();
var origUrl = '{{ \Route::getRoutes()->getByName('unitfeatures.show ')->uri}}';
$.ajax({
url: origUrl.replace('{id}', feature_id),
type: 'GET',
dataType: 'json',
success: function(response){
console.log(response);
}
});
});

Problem With You are using Javascript Variable in PHP Code You can use Javascript Variable After Execution of PHP Code treated as a String.
$.ajax({
url: "{{ route('unitfeatures.show') }}"+'/'+feature_id,
type: 'GET',
dataType: 'json',
success: function(response){
console.log(response);
}
});
});

Related

Pass variable via ajax to api.php

I am trying to pass a js variable via ajax to the php side. My js code is:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
var sAgentId = 'hi'
$.ajax({
url: "api-test.php",
method: "POST",
data : { id:sAgentId}
}).done(function(){
console.log('done')
})
and in the php file, I am trying to get the variable via post:
$sAgentId = $_POST['id'];
But finally in api i get the notification that says
Notice: Undefined index: id in C:\xampp\htdocs\webdev-php-exam-prep\exercise\api-test.php on line 2
Can anyone tell me what I am doing wrong?
Try adding this to your AJAX method:
dataType: "json"
Try also console logging the response back to check $_POST['id'] is being set.
.done(function(data) {
console.log("Data: ", data);
});
and in your PHP just return $_POST['id']
var sAgentId = 'hi'
$.ajax({
url:'api-test.php',
type: "POST",
data: {id: sAgentId },
cache: !0,
dataType: 'json',
success: function(data) {
console.log(data);
}
});
try replace method by type:
type: "POST",

Ajax Request: Json Data Not Being Passed to Controller

I'm building a program that searches documents in ASP.NET Core. I'm passing the search data from a text box to the controller through an Ajax request but the controller isn't receiving the string.
I've tried changing how the ajaxData field is defined, adding quotations around 'search' and even turning the whole thing into a string but I can't get it to pass to the controller.
This is the code for the request:
ajaxData = {search: $("#textSearchBox").val()}
console.log(ajaxData);
$.ajax({
type: 'POST',
url: "#Url.Action("GetDocuments", "DocumentSearchApi")",
data: ajaxData,
dataType: "json",
contentType: "application/json; charset=utf-8",
error: function (e) {
//Error Function
},
success: function (jsonData) {
//Success Function
},
fail: function (data) {
//Fail Function
}
});
And this is the top of the Controller's GetDocuments function:
[Route("GetDocuments")]
public async Task<IActionResult> GetDocuments(string search)
{
No error messages anywhere. The Console shows an Object that contains 'search: "Test"' but when I hit the breakpoint in GetDocuments 'search' is null.
I think is more elegant way to use GET in this case then you should change your code to
var ajaxData = $("#textSearchBox").val();
url: "#Url.Action("GetDocuments", "DocumentSearchApi")"?search=ajaxData
and remove data: ajaxData
Because you want to get something from the search. Using the post is when you want to modify the data from API
you need use JSON.stringify() when sending data to a web server, the data has to be a string not a object
$.ajax({
type: 'POST',
url: "#Url.Action("GetDocuments", "DocumentSearchApi")",
data: JSON.stringify(ajaxData),
dataType: "json",
contentType: "application/json; charset=utf-8",
error: function (e) {
//Error Function
},
success: function (jsonData) {
//Success Function
},
fail: function (data) {
//Fail Function
}
});

Getting Certain values from an AJAX return JSON object

I am trying to retrieve certain values in a JSON object retrieved from AJAX.
Using console.log(), I was able to view these:
0: Object
title: "First post"
body: "This is a post"
id: 1
userId: 27
.
.
.
100: //same format of data as object 0
Now I want to try storing the whole JSON object above so that I can use the userId and match it with another list of data to find the user who made the post. Problem is, I can't store it to a global variable. Here is my jscript snippet:
var postJson; //global variable
---somewhere in a function---
$.ajax({
url: root + '/posts',
type: "GET",
dataType: "JSON",
success: function(response){
postJson = response;
console.log(response);
}
});
I also tried doing postJson = $.ajax but nothing happened and postJson continues to be undefined.
$.ajax is async function, you need to use callback or do all the code in success function
var postJson; //global variable
function doSomething(r){
//r is here
}
---somewhere in a function---
$.ajax({
url: root + '/posts',
type: "GET",
dataType: "JSON",
success: function(response){
postJson = response;
//do something with postJson or call function doSomething(response)
}
});
function doSomething(r){
//r is here
}
---somewhere in a function---
$.ajax({
url: root + '/posts',
type: "GET",
dataType: "JSON",
success: function(response){
doSomething(response);
//do something with postJson or call function doSomething(response)
}
});
You can do directly via calling function from response no need to declare variable. Hope it will also helps you

Call JSON inside AJAX success

I want to call a json data inside my AJAX success. I'm still new on manipulating json and AJAX. Can somebody help me on how to access my json data which is from another URL? And I want to compare the id to the JSON data. Here's my code so far:
function getCard(id){
$.ajax({
type: "GET",
data: "id=" + id,
success: function(data){
#call JSON data here from another URL
# Is it possible to call another AJAX here?
}
});
}
This code will work for you
$.ajax({
url: "url",
method: "post",
data: "id=" + id,
success:function(data) {
// success goes here
$.ajax({
url: "url",
async:false,
method: "post",
data: "id=" + id,
success:function(json) {
JSON.parse(json);
// compare data and json here
},
error: function(){
// error code goes here
}
});
},
error: function(){
// error code goes here
}
});
yes Zuma you can call another Ajax inside Success function of Ajax call. Below is the example:
$.ajax({
type: "post",
url: url1,
data: data1,
success: function(data){
$.ajax({
type: "post",
url: url2,
data: data2,
success: function(data){
});
});
});
function getCard(id){
$.ajax({
type: "Get",
url: "发送请求的地址",
data: "id=" + id,
success: function(data){
#call JSON data here from another URL
# if success,you can call another AJAX.
# Is it possible to call another AJAX here?
# yes!
}
});
}

Populate a html div with json data received from a server

I need to have a html div populated with the json data received from the server which is a json-rpc server and it retruns an application/jsson-rpc content type and i can see the result in the chrome and firefox dev tools... I need to view it as part of the page inside a given div
i have this script to populate the mybox div but it gives nothing
var returnedinfo;
var request = $.ajax ({
url: "/url",
type: "POST",
data: JSON.stringify(data),
success: function(json) {
alert("success sent ajax");
$("#mybox").html(json);
returnedinfo = json;
});
I also tied having the populating function outside the ajax block when the request is done
request.done(function(msg) {
$("#mybox").text(msg);
});
This just return an empty array like this
[object Object]
and nothing else help will be appreciated.
you need to append the key of the json item.
$("#mybox").html(json.key);
Add dataType to your ajax request.
var request = $.ajax ({
url: "/url",
type: "POST",
data: JSON.stringify(data),
dataType: "json",
success: function(json) {
alert("success sent ajax");
$("#mybox").html(json);
returnedinfo = json;
});
try this my working example
look contentType and html function to replace html of mybox element
$.ajax({
type: 'POST',
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
url: 'url',
success: function (dataRes) {
$('#mybox').html(dataRes);
},
error: function(a,b,c) {
}
});
Note that in this case dataRes in success function is an html string like <strong>test</strong>. If your server side function returns a json object you should add dataType: 'json' to ajax request and then you can use properties of dataRes object like here $('#mybox').html(dataRes.property1);

Categories