cannot display the data got via ajax call - javascript

Just want to display following information which I got from my controller via ajax call:
{"results":{"name":"Bob","city":"Ottawa","reg_date":"12-Feb-2004"}}
Here is my controller:
$data["results"] = $this->my_model->did_get_data($user_id);
echo json_encode($data);
Here is My view:
<div id="display"></div>
Here is my JS file:
$.get('controller/get_data', function (data) {
$( "#display").text(data.results); //???
}, "json");

If you need to display all the attributes inside data then you can do it like this:
$.get('controller/get_data', function (data) {
var name = data.results.name;
var city = data.results.city;
var reg_date = data.results.reg_date;
$("#display").text("name :" + name + ", city:" + city + ", reg date:" + reg_date);
}, "json");

If you want to display those attributes, you need to specify them individually:
var string = "Name: "+data.results.name+", City:"+data.results.city;
$( "#display").text(string);
Or something along those lines.

Your scenario is not well explained. What is the error u get? And have u checked if $("#display") exists?
However there is one thing you could do:
$.get('controller/get_data', function (data) {
$( "#display").text(JSON.stringify(data.results)); //???
}, "json");
The above is if you want to print for checking purpose however if your #display should have only the values of your data i.e. name and such then you need to use the above answer i.e.
var name = data.results.name;
$("#display").html(name);

Related

How to POST with AJAX using just an a tag

I have an a tag that is dynamically generated with database content, it includes a data-target that I capture in javascript when it is clicked on, this is an example of one of the generated buttons:
Edit
Simple, right?
Now, what I do in the JS when it is clicked, is as so:
var $this = $(this),
$target = $this.data("target"),
$endpointURL = "";
$endpointURL = $target.split("?id=")[0];
$id = $target.split("?id=")[1];
This allows me to set the endpoint I want, in out example above, it would be "edit" and also set the id which is just a number at this point.
Now, I have to POST this ID to the edit endpoint to return the right info, correct?
So, here is my AJAX for that:
$.ajax({
type: "POST",
data: '{"id": ' + $id + ' }',
url: "../assets/scripts/php/" + $endpointURL,
success: function (data) {
$("#content-lockup").html(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log("error: " + textStatus + ", error thrown: " + errorThrown);
}
});
This does not throw an error and does indeed output a var dump of the $_POST array as I have set it to, however it doesnt contain my ID that I passed over, here is the code on the endpoint and a screenshot of the output:
<?php
var_dump($_POST);
?>
Why would the vardump on $_POST not contain the id that I passed over in the apparently successful AJAX request?
What I expect is that I can say on the endpoint, something like:
$id = $_POST['id'];
Maybe its something obvious that i'm doing wrong but yeah, any ideas?
it's because you are passing a string to data that isn't form encoded
Make it an object and jQuery will encode it for you
data: {"id": $id },
If it's a string it needs to be in format
data: 'id=' +id + '&someOtherParam=' + somevar

Passing JavaScript array from view to Laravel controller

I am trying to pass objs array to a function in Laravel controller using ajax. I am not recieving any data after the post.
<script>
var itemCount = 0;
var objs=[];
$(document).ready(function(){
var temp_objs=[];
$( "#add_button" ).click(function() {
var html = "";
var obj = {
"ROW_ID": itemCount,
"STREET_ADDRESS": $("#street_address").val(),
"CITY": $("#city").val(),
"ZIP": $("#zip").val()
}
// add object
objs.push(JSON.stringify(obj));
itemCount++;
// dynamically create rows in the table
html = "<tr id='tr" + itemCount + "'><td>" + obj['STREET_ADDRESS'] + "</td> <td>" + obj['CITY'] + " </td> <td>" + obj['ZIP'] + " </td><td><input type='button' id='" + itemCount + "' value='remove'></td> </tr>";
//add to the table
$("#multiple_table").append(html)
// The remove button click
$("#" + itemCount).click(function () {
var buttonId = $(this).attr("id");
//write the logic for removing from the array
$("#tr" + buttonId).remove();
});
});
$("#submit").click(function() {
$.ajax({
url:'/app/Http/Controllers/Search/search_address',
type: 'POST',
dataType:'json',
contentType: 'application/json',
data: objs
});
});
});
</script>
In my controller function is like this
public function search_address(){
$data = json_decode($_POST['data'], true);
print_r($data);
}
I guess that I am having a problem with the url in ajax and I am not sure how a controller's url is obtained.
Thank you
Can you change:
$data = json_decode($_POST['data'], true);
to:
$data = json_decode(Input::get('data'));
and make sure you have: use Input; above your class extends Controller
See if that works.
Edit: Also make sure your routes (in the Controllers folder) are correct.
You should console.log() your javascript by placing the following in you ajax post:
error : function(e){
console.log(e);
}
You can then see what errors you are getting in your browsers' developers tools panel.
You should also be aware that that Laravel posts require a csrf token unless you have explicitly turned them off, which means you will need to add this token in to your post as well. So you should end up with:
$("#submit").on('click', function() {
$.ajax({
url:'/app/Http/Controllers/Search/search_address', // Is this what you meant, is this the route you set up?
type: 'POST',
data: {'data': objs, '_token' : '<?=csrf_token()?>'},
success : function(data){
// Do what you want with your data on success
},
error : function(e){
console.log(e);
}
});
});
Notice that I've embedded php inside the javascript, which is just to illustrate the point. Ideally javascript is kept in it's own files, so you would then need to find a way to pass this token through. I personally use knockoutjs for this type of thing (AngularJS is also popular), but you can easily do something like:
<input type="hidden" id="_token" value="{{ csrf_token() }}" />
in your HTML, then pull this value from inside your ajax request:
data: {'data': objs, '_token' : $('#_token').val()}
EDIT
I've just noticed your url, it looks like you are trying to access the controller directly. You need to set up a route in your routes.php file, such as:
Route::post('/searchAddress', 'YourController#search_address');
Then use:
url: /searchAddress
in your ajax request.

parse name from user input when using jquery serialize

I am trying to grab user input from a dynamic form using jquery serialize. My form looks like this
<form id="lookUpForm">
<input name="q" id="websterInput" />
<button onclick="webster(); return false;">Search</button>
</form>
I want to take the input, and attach it to the end of websters dictionary URL to search for a word.
http://www.merriam-webster.com/dictionary/ + (user input)
When you run an alert to see what the value of 'q' is, you get
q=input
so for example if I put 'cats'
the alert would say q=cats.
I want the the string to just be what the user entered. However, you need to give the input a name to use seralize. So how can I take the user input, and strip out the 'q=' part.
EDIT
as requested here is the function I'm calling. Note. I HAVE to use serialize(); This isnt an option.
function webster() {
var stringHolder = $("#lookUpForm").serialize();
alert(stringHolder);
$.ajax({
type: 'GET',
crossDomain: 'true',
url: "http://www.merriam-webster.com/" + stringHolder,
success: function (data) {
console.log(data);
console.log("http://www.merriam-webster.com/" + stringHolder);
},
error: function () {
alert("Failed to get dictionary data");
console.log("http://www.merriam-webster.com/dictionary/" + stringHolder);
}
});
};
You can just access it using val method of jQuery
function webster() {
var stringHolder = $("#lookUpForm").serialize();
alert(stringHolder);
$.ajax({
// (...) removed some code for brevity
error: function () {
alert("Failed to get dictionary data");
console.log("http://www.merriam-webster.com/dictionary/" +
$('#websterInput').val()); // I suppose you want the user-input here
}
});
};
You could use serializeArray().
And then do something like this and put your string together like you want to
var array = $("#lookUpForm").serializeArray();
$(array ).each(function(){
alert(this.value);
});

Events not triggered when posting json string using jquery [duplicate]

This question already has answers here:
jQuery posting JSON
(3 answers)
Closed 8 years ago.
I'm totally new to this, so apologies if I'm not explaining this correctly.
I want to post some data in json format to a rest service. I'm trying to get this work with JQuery in a simple .cshtml (razor) page.
My json string looks like this:
{
"ListRequest":{
"Values":[
{
"Name":"SC",
"Value":"PRO001"
},
{
"Name":"PC",
"Value":"Z0R14"
}
]
}
}
I need to pass 2 values from a form into this string and then post it but I'm not sure how do I declare this in javascript and then post it to my $.post function.
My HTML looks like this:
<form action="/" id="getListForm">
<input type="text" name="txtSC">
<input type="text" name="txtPC">
<input type="submit" value="Get List">
</form>
I thought I'd just declare a var:
var jsonText = '{"ListRequest":{ "Values":[' +
'{"Name":"SC", "Value":"' + $form.find("input[name='txtSC']").val() + '"},' +
'{"Name":"PC","Value":"' + $form.find("input[name='txtPC']").val() + '"}]}}';
Is that the correct way to handle this??
Then I've got my 'post' code to test:
var posting = $.post( url, term);
posting.done(function (data) {
var content = $(data).find("#content");
$("#result").empty().append(content);
});
But whenever I call this, it put these 2 values as part of a query string, instead of doing an actual post where this data is not visible in the url.
http://localhost/WebTest/WebDataService.svc/GetList?txtSC=brc001&txtPC=12345
Can someone tell me how to fix this??
Thanks.
UPDATE:
Here is the full code from my test page as it still not working for me. I just noticed that the submit event is not triggered. It seems to be putting the textbox and value automatically because they are part of the form, but my event is definitely not triggered as I've just commented all the code and put a alert('test'); and it didn't show up.
Any ideas?
Thanks.
<script src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.5.js" type="text/javascript"></script>
<script type="text/javascript">
// Attach a submit handler to the form
$("#getListForm").submit(function (event) {
event.preventDefault();
//var jsonText = '{"ListRequest":{ "Values":[' +
// '{"Name":"SC", "Value":"' + $form.find("input[name='txtSC']").val() + '"},' +
// '{"Name":"PC","Value":"' + $form.find("input[name='txtPC']").val() + '"}]}}';
var obj = {
ListRequest: {
Values: [
{
Name: "SC",
Value: $('input[name="txtSC"]').val()
},
{
Name: "PC",
Value: $('input[name="txtPC"]').val()
}
]
}
}
var jsonObj = JSON.stringify(obj);
var $form = $(this), term = jsonText, url = 'http://localhost/WebTest/DataService.svc';
$.post(url + '/GetList', jsonObj,
function (data, status) {
alert("Data: " + data + "\nStatus: " + status);
});
// Send the data using post
//var posting = $.post( url, term);
//posting.done(function (data) {
// var content = $(data).find("#content");
// $("#result").empty().append(content);
//});
});
</script>
#{
ViewBag.Title = "Json Test";
}
<hgroup class="title">
<h1>#ViewBag.Title.</h1>
<h2>#ViewBag.Message</h2>
</hgroup>
<form id="getListForm">
<input type="text" name="txtSC">
<input type="text" name="txtPC">
<input type="submit" value="Get List">
</form>
<div id="result"></div>
Thanks.
UPDATE:
Latest code where I've updated the term to use the jsonObj and I've put my code in the $(document).ready block as suggested:
<script src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.5.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
// Attach a submit handler to the form
$("#getDocumentListForm").submit(function (event) {
event.preventDefault();
alert('test1');
var obj = {
ListRequest: {
Values: [
{
Name: "SC",
Value: $('input[name="txtSC"]').val()
},
{
Name: "PO",
Value: $('input[name="txtPC"]').val()
}
]
}
}
var jsonObj = JSON.stringify(obj);
var $form = $(this), term = jsonObj, url = 'http://localhost/WebTest/DataService.svc';
alert(term);
alert(url);
$.post(url + 'GetList', jsonObj,
function (data, status) {
alert("Data: " + data + "\nStatus: " + status);
});
//Tried posting using term but no luck. Same problem.
//$.post(url + 'GetList',
//function (data, status) {
// alert("Data: " + data + "\nStatus: " + status);
//});
// Send the data using post
//var posting = $.post(url, term);
//posting.done(function (data) {
// //var content = $(data).find("#content");
// //$("#result").empty().append(content);
// alert(data)
//});
alert('test2');
});
});
</script>
#{
ViewBag.Title = "Test";
}
<hgroup class="title">
<h1>#ViewBag.Title.</h1>
<h2>#ViewBag.Message</h2>
</hgroup>
<form id="getDocumentListForm">
<input type="text" name="txtSC">
<input type="text" name="txtPC">
<input type="submit" value="Get Document List">
</form>
<div id="result"></div>
Finale Update on this question
MAKE SURE:
NOT TO USE IE11 WITH JQUERY, WELL AT LEAST JQUERY 2.1.1! DON'T KNOW HOW WELL IT WORKS WITH OTHER VERSIONS OF IE.
ALWAYS TEST WITH OTHER BROWSERS
MAKE SURE TO SET YOUR JQUERY SRC TO THE CORRECT HTTP OR HTTPS DEPENDING ON WHAT YOU USE.
That's it.
I suppose what's going on there is that you are trying to pass an undefined variable named term instead of jsonText, so the javascript code is throwing an uncaught exception and gets ignored, and you get a normal action from your form element.
You should pass the correct data. And also, knowing about JSON.stringify can probably save you a lot of time and headaches ;). You could build your object like so:
var obj = {
ListRequest: {
Values: [
{
Name: "SC",
Value: $('input[name="txtSC"]').val()
},
{
Name: "PC",
Value: $('input[name="txtPC"]').val()
}
]
}
};
var jsonObj = JSON.stringify(obj);
Another pitfall I can think of in your code, is that you have bound your AJAX to a click event on your submit button, or to an onsubmit event, and you are not preventDefault()ing.
Edit
Given the code you posted, you have a couple of mistakes:
Did you wrap your code into a jQuery(document).ready() block?
You commented out jsonText but still assign it to the variable term, causing an uncaught exception.
Fix these two things and your POST request will be done correctly.
On the other hand, why on Earth are you using jQuery version 1.5?

jquery MVC4 receive JSON

I want to send json data from my controller to my view when a specific action happens.
I used this on controller to send the data
[HttpGet]
public JsonResult JSONGetParking(int buildingID){
return this.Json(
new
{
Result = (from obj in db.Parkings.Where(p => p.buildingID == buildingID) select new { ID = obj.ID, Name = obj.note })
}
, JsonRequestBehavior.AllowGet
);
}
it works very good
on my script i used this:
FloorScript.js
$(document).ready(function () {
$('#buildingID').change(function () {
alert("what is not");
$.getJSON('JSONGetParking?buildingID=' + $('#buildingID').val(), function (data) {
alert("afd");
var items = " ";
$.each(data, function (obx, oby) {
items += "<option value='" + oby.ID + "'>" + oby.Name + "</option>";
});
$('#parkingID').html(items);
});
});
});
I have opened google chrome and I can see the request and the response like this:
i can see the two text that i alerted
However, on my selector, i just see undefined value
Html
<div id="editor-label">
<select id="parkingID" name="parkingID"></select>
</div>
I have added the jquery in this
#section scripts {
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/Scripts/FloorScript.js");
}
You're not looping on the correct variable.
You did this:
$.each(data, function (obx, oby) {
whereas you should do this:
$.each(data.Result, function (obx, oby) {
This is pretty visible in the Google Chrome screenshot you provided. As you can see the returned JSON has a property called Result which is the collection whereas you were looping over the data variable which is not an array - it's just a javascript object that has a property called Result which is the array you wanna be looping through.
Also I'd replace:
$.getJSON('JSONGetParking?buildingID=' + $('#buildingID').val(), function (data) {
with:
$.getJSON('JSONGetParking', { buildingID: $('#buildingID').val() }, function (data) {
and of course get rid of this hardcoded url over there and use an url helper to generate it, on the dropdown as an HTML5 data-* attribute:
#Html.DropDownListFor(
x => x.BuildingId,
Model.Buildings,
new {
id = "buildingID",
data_url = Url.Action("JSONGetParking")
}
)
and then inside the change event you can trivially easy retrieve this url and avoid hardcoding it (and of course taking the risk of breaking your code when you deploy it in IIS in a virtual directory or simply change the routing pattern of your application):
$('#buildingID').change(function () {
var url = $(this).data('url');
$.getJSON(url, { buildingID: $('#buildingID').val() }, function (data) {
Alright, now the initial mess is tidied up.
use data.Result in your each loop
$(document).ready(function () {
$('#buildingID').change(function () {
alert("what is not");
$.getJSON('JSONGetParking?buildingID=' + $('#buildingID').val(), function (data) {
alert("afd");
var items = " ";
$.each(data.Result, function (obx, oby) {
items += "<option value='" + oby.ID + "'>" + oby.Name + "</option>";
});
$('#parkingID').html(items);
});
});
});
Hope this helps...

Categories