Getting data relations by javascript in laravel - javascript

Sorry for title I really didn't know how to describe it.
I have data returned by JavaScript but my data has other data ORM related which i need those as well.
this is my data that returned on selected option:
Object { id: 1, address: "hrktgui erhoutruei9utgy", postalcode: "154785", user_id: 1, city_id: 1, state_id: 10, country_id: 102, created_at: "2018-02-09 13:28:22", updated_at: "2018-02-09 13:28:22" }
I need this data:
address
postalcode
city name (provided under city_id)
state name (provided under state_id)
My issue is to retrieving that city and state name
later i want add this 4 data as hidden input to my view so I can use it for my other function.
here is my js code:
<script type="text/javascript">
$(document).ready(function() {
$('select[name="address_id"]').on('change', function() {
var addressID = $(this).val();
if(addressID) {
$.ajax({
url: '{{ url('addressdetails') }}/'+encodeURI(addressID),
type: "GET",
dataType: "json",
success:function(data) {
$('div#details').empty();
console.log(data['address']);
console.log(data);
// $.each(data, function(key, value) {
// $('div#details').append('<input type="hidden" name="shipment_price" value="'+...+'"><input type="hidden" name="shipment_price" value="'+...+'">');
// });
}
});
}else{
$('div#details').empty();
}
});
});
</script>
my html:
<div id="details"></div>
my function:
public function getAddressDetails($id)
{
$address = Address::findOrFail($id);
return response()->json($address);
}
my route:
Route::get('addressdetails/{id}', 'CartController#getAddressDetails');

its an object. try this.
success:function(data) {
var statename = data.state.name;
var cityname = data.city.name;
}
Edit:
"my issue is to retrieving that city and state names"
your query need to use eager loading
example:
return response()->json(Address::with(['city','state'])->find($id));
in Address Model
class Address {
...
...
public function city(){
return $this->belongsTo(City::class);
}
public function state(){
return $this->belongsTo(State::class);
}
}

Related

When i Submit model data, i get <p> tag in response

My model: xyz.php
public $fillable = [
'name',
'phone',
'status',
];
protected $casts = [
'id' => 'integer',
'phone' => 'string',
'status' => 'boolean',
];
table:
$table->increments('id');
$table->unsignedInteger('user_id');
$table->string('name');
$table->string('phone')->nullable();
$table->boolean('status')->default(0);
$table->timestamps();
JS file code:
$(document).on('submit', '#addNewForm', function (event) {
event.preventDefault();
$.ajax({
url: userCreateUrl,
type: 'POST',
data: $(this).serialize(),
success: function (result) {
if (result.success) {
displaySuccessMessage(result.message);
$('#addModal').modal('hide');
}
},
}):
blade.php
blade.php
response image
When I submit data from the model, I get a response to the data according to the photo above, e.g.,
phone = "<p>1234567890</p>". Please some solutions. Thank you advance.
The problem is most likely when you use the serialize method. Instead i have written a function that can extract the input values from the form. You can then send this information to your server.
function getInputValues(form){
var values = {};
form.find(':input').each(function() {
values[this.name] = $(this).val();
});
return values
}
You can use this function like so:
$(document).on('submit', '#addNewForm', function (event) {
event.preventDefault();
$.ajax({
url: userCreateUrl,
type: 'POST',
data: getInputValues($(this)),
success: function (result) {
if (result.success) {
displaySuccessMessage(result.message);
$('#addModal').modal('hide');
}
},
}):
However you should note that all the returned values are string, even if you used an input with type="number". The alternative to this solution, is to manually extract each input value using a specific id.
const phoneNumber = document.getElementById('#phone-number-input').value.
If you just want to remove the p tags then before inserting into the db use strip_tags().

Sending Array Object Data in Javascript to ASP.NET Core Controller using AJAX ()

I've tried all other solutions pertaining to the problem, but still can't find what i'm missing for my code. Here's my AJAX() Code.
var group = JSON.stringify({ 'listofusers': listofusers });
console.log("listofusers : " + JSON.stringify({ 'listofusers': group }));
(Assuming I have my listofusers object ready, and yes i've checked the console and it has data inside.)
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: "POST",
url: url,
data: group,
success: function (data) {
console.log("output : " + JSON.stringify(data));
//doSend(JSON.stringify(data));
//writeToScreen(JSON.stringify(data));
},
error: function (data) {
console.log("error : " + JSON.stringify(data));
},
});
Here's my Server Side Controller.
[HttpPost]
public IActionResult GetMesssage(List<UserModel> listofusers)
{
var g = listofusers;
}
Just a simple fetch from the controller, so I could verify that the data from client side has really been sent.
I've tried the [FromBody] attribute, but still no luck in fetching the data from the server-side.
Here is a working demo like below:
1.Model:
public class UserModel
{
public int Id { get; set; }
public string Name { get; set; }
}
2.View(remove Content-type):
<script>
var listofusers = [
{ id: 1, name: 'aaa' },
{ id: 2, name: 'bbb' },
{ id: 3, name: 'ccc' }
];
var group = { 'listofusers': listofusers };
console.log(group);
$.ajax({
dataType: 'json',
type: "POST",
url: "/home/GetMesssage",
data: group,
success: function (data) {
console.log("output : " + JSON.stringify(data));
},
error: function (data) {
console.log("error : " + JSON.stringify(data));
},
});
</script>
3.Console.log(group):
4.Result:
Update:
Another way by using json:
1.View(change group from JSON.stringify({ 'listofusers': listofusers });
to JSON.stringify(listofusers);):
<script>
var listofusers = [
{ id: 1, name: 'aaa' },
{ id: 2, name: 'bbb' },
{ id: 3, name: 'ccc' }
];
var group = JSON.stringify(listofusers);
console.log(group);
$.ajax({
contentType:"application/json",
dataType: 'json',
type: "POST",
url: "/home/GetMesssage",
data: group,
success: function (data) {
console.log("output : " + JSON.stringify(data));
},
error: function (data) {
console.log("error : " + JSON.stringify(data));
},
});
</script>
2.Controller(add FromBody):
[HttpPost]
public IActionResult GetMesssage([FromBody]List<UserModel> listofusers)
{
//...
}
You can try this one.
First stringify the parameter that you want to pass:
$.ajax({
url: url,
type: "POST",
data: {
listofusers: JSON.stringify(listofusers),
},
success: function (data) {
},
error: function (error) {
}
});
Then in your controller:
[HttpPost]
public IActionResult GetMesssage(string listofusers)
{
var jsonModel = new JavaScriptSerializer().Deserialize<object>(listofusers); //replace this with your deserialization code
}
What we're doing here is passing your object as a string then deserializing it after receiving on the controller side.
Hope this helps.
I found the solution to my problem guys, but I just want a clarification that maybe there's a work around or another solution for this one.
I've studied the data passed by "JSON.stringify();" from AJAX() and it's somehow like this.
"[[{\"ID\":0,\"UserID\":1014,\"Level\":\"support\",\"Department\":\"\",\"Facility\":\"Talisay District Hospital\",\"Firstname\":\"Joseph\",\"Middlename\":\"John\",\"Lastname\":\"Jude\",\"LoginStatus\":false,\"IPAddress\":\"192.168.110.47:12347\"},{\"ID\":0,\"UserID\":1014,\"Level\":\"support\",\"Department\":\"\",\"Facility\":\"Talisay District Hospital\",\"Firstname\":\"Joseph\",\"Middlename\":\"John\",\"Lastname\":\"Jude\",\"LoginStatus\":false,\"IPAddress\":\"192.168.110.47:15870\"}]]"
to which I was wondering that if the JSON format is a factor in parsing the data from the controller side. (Which of course is stupid since there's only one JSON format. (or maybe there's another, if there is, can you please post some source for reference.))
so I tried Serializing a Dummy Data in my model in "JsonConvert.Serialize()" Method and the output JSON data is like this.
[{"ID":0,"UserID":1014,"Level":"support","Department":"","Facility":"Talisay District Hospital","Firstname":"Joseph","Middlename":"John","Lastname":"Jude","LoginStatus":false,"IPAddress":"192.168.110.47:12347"},{"ID":0,"UserID":1014,"Level":"support","Department":"","Facility":"Talisay District Hospital","Firstname":"Joseph","Middlename":"John","Lastname":"Jude","LoginStatus":false,"IPAddress":"192.168.110.47:16709"}]
and I tried sending the output JSON Data from JsonConvert.Serialize() Method to controller via AJAX() and it worked! And I feel so relieved right now as this problem was so frustrating already.
If there's something wrong with what I found, please respond with what might be wrong or correct. Thank you!

Storing JSON result from ajax request to a javascript variable for Easyautocomplete

I'm trying to implement the EasyAutoComplete plugin on a field based on the value filled in another field, using ajax requests.
I have a customerid field and when it's value changes, I want the productname field to show all products related to that customerid using the EasyAutoComplete plugin.
Here is what I have so far:
$('#customerid').on('change',function() {
var products2 = {
url: function(phrase) {
return "database/FetchCustomerProducts.php";
},
ajaxSettings: {
dataType: "json",
method: "POST",
data: {
dataType: "json"
}
},
preparePostData: function(data) {
data.phrase = $("#customerid").val();
return data;
},
getValue: "name",
list: {
onSelectItemEvent: function() {
var value = $("#productname").getSelectedItemData().id;
$("#productid").val(value).trigger("change");
},
match: {
enabled: true
}
}
};
$("#productname").easyAutocomplete(products2);
});
Contents of FetchCustomerProducts.php:
if(!empty($_POST["customerid"])){
$products = $app['database']->Select('products', 'customerid', $_POST['customerid']);
echo json_encode(['data' => $products]);
}
However it's not working. The code is based on the 'Ajax POST' example found on this page.
you can using element select category add is class "check_catogory"
after using event click element select get value is option, continue send id to ajax and in file php, you can get $_POST['id'] or $_GET['id'], select find database,after echo json_encode
$("#customerid").change(function(){
var id = $(this).val();
if(id!=""){
$.ajax({
url:"database/FetchCustomerProducts.php",
type:"POST",
data:{id:id},
dataType: "json",
cache:false,
success:function(result){
var options = {
data:result,
getValue: "name",
list: {
onSelectItemEvent: function() {
var value = $("#productname").getSelectedItemData().id;
$("#productid").val(value).trigger("change");
},
match: {
enabled: true
}
}
};
$("#productname").easyAutocomplete(options);
}
})
}
});

jQuery: Mixing Strings and List of Javascript Objects in JSON

What I'm trying to do is possibly quite simple, however beeing not very familiar with jQuery I can't figure out how to do it.
I want to send some Data as JSON to an ASP.NET Controller. The Data contains some Strings and a list of Objects.
The Code would look somewhat like this:
View:
$(document).ready(function () {
var stuff = [
{ id: 1, option: 'someOption' },
{ id: 2, option: 'someOther' },
{ id: 3, option: 'anotherOne' }
];
things = JSON.stringify({ 'things': things });
var dataRow = {
'String1': 'A String',
'String2': 'AnotherOne'
}
dataRow = JSON.stringify(dataRow);
var sendData = dataRow + things;
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/Backend/DoStuffWithStuff',
data: sendData,
success: function () {
alert('Success!');
},
failure: function (response) {
alert('Fail! :(');
}
});
});
Controller:
public class Stuff
{
public int id { get; set; }
public string option{ get; set; }
}
public void DoStuffWithStuff(string String1, String2, List<Thing> things)
{
//Do my Stuff
}
Any Ideas would be great! :)
You do not need to stringify the json data.
You just create an object you van to send and than
var jsonObject = {
'string' : 'string',
'object' : {
'stirng': 'string'
}
};
$.ajax({type: "POST", url: DotNetScript, data: jsonObject})
.done(function(dataBack){
//what to do with data back
});
It actually doesn't look too bad so far! Just a few things...
[HttpPost]
public void DoStuffWithStuff(string String1, String2, List<Stuff> things)
{
//Do my Stuff
}
In here, you don't actually give a type to string2. I'm going to assume this is a typo, but that's the minor part here.
Also, in that method, notice it has the HttpPost on the top. In your javascript here:
$.ajax({
...
type: 'POST',
...
});
You specify POST, so you must make the method support post (You could also get away with GET in this case by changing type to GET, then removing the attribute, but i'm not sure what your "stuff" entails...)
var stuff = [
{ id: 1, option: 'someOption' },
{ id: 2, option: 'someOther' },
{ id: 3, option: 'anotherOne' }
];
things = JSON.stringify({ 'things': things });
var dataRow = {
'String1': 'A String',
'String2': 'AnotherOne'
}
dataRow = JSON.stringify(dataRow);
var sendData = dataRow + things;
You didn't actually pass stuff into your method, which may be helpful...
Here is the ajax method re-written with the proper JSON pass (for what you're trying to do here).
$(document).ready(function () {
var stuff = [
{ id: 1, option: 'someOption' },
{ id: 2, option: 'someOther' },
{ id: 3, option: 'anotherOne' }
];
var dataRow = {
String1: 'A String',
String2: 'AnotherOne'
things: stuff
}
$.ajax({
dataType: 'json',
type: 'POST',
url: '/Backend/DoStuffWithStuff',
data: sendData,
success: function () {
alert('Success!');
},
failure: function (response) {
alert('Fail! :(');
}
});
});

JavaScript not working in MVC web application

I have a ASP.NET MVC application and I have a few entries on the page that user can change and click Save and I go save those entries. My problem: It works fine for some entries and for other entries it just doesn't go in the controller Save function to do the save.
My code:
function DoSave() {
$("#pisave").attr("disabled", true);
var pid = $("#personid").val();alert(pid);
var firstname = $("#fname").val();alert(firstname);
var lastname = $("#lastname").val();alert(lastname);
var plz = $("#zip").val();alert(plz);
var ort = $("#city").val();alert(ort);
var bday = $("#birthdate").val();alert(bday);
var strasse = $("#street1").val(); alert(strasse);
var emailtext = $("#email").val();alert(emailtext);
var url = "#(Url.Action("SavePersonInfo", "Info"))";alert("URL");
$.ajax({
url: url,
data: { personid: pid,fn: firstname, ln: lastname, email: emailtext, zip: plz, city:ort, birthday: bday, street:strasse },
success: function () {
alert("Update Successful");
$("#pisave").removeAttr("disabled");
},
error: function () {
alert("Update Failed! Check entries.");
$("#pisave").removeAttr("disabled");
}
});
}
All alerts are displayed in all the cases. Only for some it goes to SavePersonInfo and for others it doesn't go in there. Any ideas what might be wrong?? Can it be validation issue for the entries?
The model binder fails to parse your date, change to post:
$.ajax({
type: "POST",
url: url,
data: { personid: pid,fn: firstname, ln: lastname, email: emailtext, zip: plz, city:ort, birthday: bday, street:strasse },
success: function() {
alert("Update Successful");
$("#pisave").removeAttr("disabled");
},
error: function() {
alert("Update Failed! Check entries.");
$("#pisave").removeAttr("disabled");
}
});​
Read more about the problems with dates in asp.net-MVC
Note that you can add all the elements a class and use the serialize function:
$.ajax({
type: "POST",
url: url,
data: $('.theClass').serialize(), // <=============
success: function() {
alert("Update Successful");
$("#pisave").removeAttr("disabled");
},
error: function() {
alert("Update Failed! Check entries.");
$("#pisave").removeAttr("disabled");
}
});​

Categories

Resources