Put json result from php script into divs jQuery - javascript

I have two divs, each one should have a record name from a json result.
<div class="first"></div>
<div class="second"></div>
My json file is as follows :
[{"Name":"name1","Instruction":"instr"},
{"Name":"name2","Instruction":"instr again"}]
I want to put in the first div's value, the ‘Name‘ value of the first record, same for the second div but with the second record.
I'm using jQuery :
<script>
$(document).ready(function() {
$.post("data/result.php",
function(data) {
//alert("Data: " + data);
$('div.first').append(data.Name); //data.Name returns undefined
}
);
});
</script>
Any help would be appreciated.

as far as you are using post for you ajax call, the data returns as a json string, do this:
$(document).ready(function() {
$.post("data/result.php",
function(data) {
data = JSON.parse(data);
$('div.first').append(data[0].Name);
$('div.second').append(data[1].Name);
}
);
});

As previously mentioned you need to parse the result as json. You could use the built in parser in jquery. Like this:
<script>
$(document).ready(function() {
$.ajax({
url: 'data/result.php',
type: 'POST',
dataType: 'json',
success : function (data) {
$('div.first').append(data[0].Name);
}
});
});
</script>

First of all, you can give a datatype with a request:
$.post('data/result.php',function(data) { },'JSON');
If you are not posting any information, why not just use $.get ? (it's the same syntax btw)
$.post('data/result.php',function(data) {
var $first = $('div.first'),
$second = $('div.second');
$first.text(data[0].Name);
$second.text(data[1].Name);
},'JSON');
Also, if you use .append(..) it will be appended to whatever is already in the div. If that is your intention, use .append(...). However, if you want to replace the content of it, even if it is empty, use .text(...) or .html(...)

Related

Returing a list of strings and iterating over it

I am new to jQuery and I am trying to iterate through a list of strings after making an ajax call to a controller. In this controller, I am returning a list of strings and I want to iterate over this list in jquery and present it to the screen. Here is my code.
This is my controller
[HttpPost]
public ActionResult GetComments() {
var cmts = ex.GetComments(psts, psons);
var lstCmt = ex.GetCommentsList(cments, psons);
return Json(lstCmt);
}
This is my view:
<div>
<button id="ldBtn" class="btn btn-primary">Load</button>
</div>
<div id="cments">
</div>
<script src="~/Scripts/jquery-3.2.1.js"></script>
<script>
$(document).ready(function() {
$("#ldBtn").on('click', function(evt) {
$("#cments").empty();
$.ajax({
type: "POST",
dataType: "html",
url: '#Url.Action("GetComments")',
data: {},
success: function(lists) {
//Something needs to be fixed here
$.each(lists, function(i, name) {
$('#comments').append('<p>' + name.Value + '</p>');
});
}
});
});
});
</script>
When I return the list, I am getting a huge string. How do I fix this?
Thanks in Advance
There's a couple of issues in your JS code. Firstly you're telling jQuery to expect a HTML response in the dataType setting. This is why you see the response as a string. This should be changed to JSON instead, that way jQuery will deserialise the response for you.
Secondly you're attempting to concatenate a Value property on each item in the list, yet they are strings (as you state you're returning a List<string> from your action), and will not have that property. You can simply append the name itself. Try this:
$("#ldBtn").on('click', function(evt) {
$("#cments").empty();
$.ajax({
url: '#Url.Action("GetComments")',
type: "POST",
dataType: 'json',
success: function(comments) {
$('#cments').append('<p>' + comments.join('</p><p>') + '</p>');
}
});
});
I assume the #comments/#cments discrepancy is only due to amending parts of your code when creating the question.
Also note that I simplified the append() logic so that it appends all comments in a single call, which should be slightly faster.

Not able to print <> brackets in XML output in html

So this is with regards to one of my previous questions, where in i wanted to replace "\n" with a "br" tag in HTML using JS.
For the same page, if someone passes a XML or RPC query, i want to return an XML output.
A typical XML output looks like:
<racks>\n
<rack>\n
<rack-name>0</rack-name>\n
<chassis>\n
<serial-number>XYZ789</serial-number>\n
</chassis>\n
</rack>\n
</racks>\n
</diag>\n
</data>\n
</rpc-reply>\n
**I want to be able to print it in this way: (replacing \n with a br)
<racks>
<rack>
<rack-name>0</rack-name>
<chassis>
<serial-number>XYZ789</serial-number>
</chassis>
</rack>
</racks>
</diag>
</data>
</rpc-reply>
**
But i am only getting the plain text in the output, which is 0 and XYZ789 with so many \n's.
The JS:
$(function() {
$('button').click(function() {
$.ajax({
url: '/runCommand_query',
data: $('form').serialize(),
type: 'POST',
success: function(response) {
response = response.replace(/(\n)/g, "<br>");
console.log(response);
$("#opt").html(response);
},
error: function(error) {
console.log(error);
$("#opt").val(error);
}
});
});
});
You should use text() instead of html() like :
$("#opt").text(response);
Else the browser will interpret the code as HTML tags, and shows you just the text.
Hope this helps.
UPDATE :
var response = "<racks>\n<rack>\n<rack-name>0</rack-name>\n<chassis>\n<serial-number>XYZ789</serial-number>\n</chassis>\n</rack>\n</racks>\n</diag>\n</data>\n</rpc-reply>\n";
$('#opt').text(response).wrap('<pre />');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="opt"></div>
Just tweaking Zakaria Acharki's answer a bit to get the final outcome as per my requirement:
response = response.replace(/</g, "<").replace(/>/g,">").replace(/(\n)/g,"<br>");

laravel: view not shown after ajax post

I want to show a view after ajax post. but view shown only in browser console.not in main browser.what i am doing wrong?? please help. i am stucking here for one week.i am using laravel 5.3
javascript:
$('#btn-save').click(function () {
var doctor_id=$('#doctors_id').val();
var doctor_name=$('#autocomplete-custom-append').val();
var patient=$('#p_name').val();
var mobile=$('#p_mobile_no').val();
$.ajax({
url: '{{URL::to('confirmation')}}',
type: "POST",
data: {
'doctor_id':doctor_id,
'doctor_name': doctor_name,
'patient_name': patient,
'mobile_no':mobile
},
dataType: 'json',
success: function (data) {
//window.location.href=data.url;
}
});
return false;
});
controller:
public function serialConfirmation(Request $request)
{
$doctor_id=$request->input('doctor_id');
$doctor_name=$request->input('doctor_name');
$patient_name=$request->input('patient_name');
$mobile_no=$request->input('mobile_no');
return view('serial.confirmation',compact('doctor_id','doctor_name','patient_name', 'mobile_no' );
}
You will need to assing the html to your page you will do this in your javascript like so:
$("#wrapper").html(data);
If so that you want to put the html to a element with the id of wrapper.
Note this will exchange the current html in the element with the html returned from php if you want to preserve current html and just append the new html you will have to use either prepend or append jquery function depending on if you want to prepend or append.
if you want to redirect, there is no need to use ajax, just change the method you call serialConfirmation to call your url /confirmation then keep the function as you have it.
(You can have a form with action="{{ url('/confirmation') }} )
And you can access the data in your view like this {{$doctor_id}}
Just change your success like below:
success: function (data) {
// Insert your html code into the page using ".html(html)" method
// or other similar method.
}
Something like this way.

How to change specific element on ajax ?

I have ajax call that change the user info. And I want to get the value from the response and change value of specific element
Example: the element that need to chage:
<div id="changeMe"><!-- New Value --> </div>
Ajax call:
$.ajax({
url: "?rr=profile",
}).success(function(response) {
});
How to change the value of the "changeMe" element ONLY ?
Try it with
$.ajax({
url: "?rr=profile",
}).success(function(response) {
var r = $( response ).find( "#changeMe" );
$( "#changeMe" ).html( r.html() );
});
You could do this:
$.ajax({
url: "?rr=profile",
}).success(function(response) {
$('#changeMe').html('Your new content');
});
This will change the element with the ID "changeMe". See also JQuery API
To get a value you can use the same method.
Example:
var res = $('#someOtherElement').html();
The variable res has now the content of the element.
You can do it by following line.
$('#changeMe').html(response);
You can use the .html() or .text() jQuery methods depending on your requirements (whether the response content is HTML or plain text):
$.ajax({
url: "?rr=profile",
}).success(function(response) {
$('#changeMe').html(response);
});
switch .html(response) with .text(response) if that's better for you.
In your success function your can do like below
.success(function(response) {
$("#changeMe").append("Your value");
});
If you want to change the text then :
$('#changeMe').text('new data from response');
If you want to change CSS as well :
$('#changeMe').css('property', 'attribute');

Issue populating ajax response into a div

What am I missing? I've added the get element by Id and I'm definitely getting a response back, I checked using firebug and the response is correct. But I can't figure out why it won't populate my div area.
<script>
$(document).ready(function () {
$("#cmdSend").click(function () {
// Get he content from the input box
var mydata = document.getElementById("cmdInput").value;
$.ajax({
type: "POST",
url: "/Terminal/processCommand",
data: { cmd: mydata }, // pass the data to the method in the Terminal Contoller
success: function (data) {
//alert(data);
// we need to update the elements on the page
document.getElementById("terminal").value = document.getElementById("terminal").value + mydata;
document.getElementById("terminal").value = document.getElementById("terminal").value + data;
},
error: function (e) { alert(e); }
})
});
});
</script>
And the Div I want the response to be put in:
<div class="terminal" style="overflow:scroll">
<br>
</div>
First, you are calling document.getElementById(), but your div does not have an ID of terminal, it has a class called terminal.
Second, you are using jQuery but then switch back to classic JavaScript. You could update your code to the following:
success: function (data) {
//alert(data);
// we need to update the elements on the page
var existingHtml = $(".terminal").html();
$(".terminal").html(existingHtml + mydata + data);
}
Note that the $(".SomeName") selector is for selecting by class and $("#SomeName") is to select by id.
Edit and Note
If this terminal div could start to get a lot of data inside of it, you may look at using the .append() function in jQuery to prevent having to make a copy of the HTML and overwrite the HTML each time a request is made. The update would be something similar to the following (its a little shorter and should be more efficient as well)
success: function (data) {
//alert(data);
// we need to update the elements on the pag
$(".terminal").append(mydata + data);
}
If you want to get your element by id, add an id to the div:
<div id=terminal class="terminal" style="overflow:scroll">
<br>
</div>
If you want to change the contend of div not using jquery, you should use innerHTML instead of value.
document.getElementById("divID").innerHTML = document.getElementById("divID").innerHTML + data

Categories

Resources