I'm getting a list of user's data using ajax. But after this ajax call, I have to render a html structure (like a datasheet) with many user's data to each user. My doubt is about how to "store" the HTML code in a functional and elegant way to keep my code readable and allow me insert the users data.
Creating a file with the component template and include it throught javascript is the best idea? If yes, how could I do this? If not, what's the best?
What I have:
Ajax call:
`
$("#list-users").click(function(ev){
ev.preventDefault();
$.ajax({
url : '/ajax/Users.php',
type : 'POST',
dataType: 'json',
data : data,
success : function(users){
users.forEach((user, index) => {
//The problem is here. I'm looking for a way to
//"store" the html component code to dont need put
//the code inside a variable.
var complexHtml = '...<p>' + user.name + '</p>...';
$('.list').append(complexHtml);
})
})
})
`
because it will make the success function very big and unreadable.
... are you looking for this ?
`
var myUSERS = {};
var myUsersLoaded = false;
$("#list-users").click(function(ev){
ev.preventDefault();
$.ajax({
url : '/ajax/Users.php',
type : 'POST',
dataType: 'json',
data : data,
success : fctDo_Stuff_User
})
})
//...
function fctDo_Stuff_User(users) {
users.forEach((user, index) => {
var complexHtml = '...<p>' + user.name + '</p>...';
$('.list').append(complexHtml);
})
`
Using Vue/React/Angular can be a simple solution, because they do the rending job automatically for you.
Without using these frameworks, I usually do the following:
create a html template structure and style it invisible
use jquery clone to create
use jquery to set data
use jquery appendTo to display it.
Example codes are as below:
<div id="target"></div>
<div class="template-code" style="display:none">
<div class="container">
<div class="cls1"></div>
<div class="cls2"></div>
</div>
</div>
<script>
.... ajax success function (){
var div = $(".template-code .container").clone();
$(div).find(".cls1").html("data from ajax result");
$(div).find(".cls2").html("data from ajax result");
.... bind event as well if required ...
$("#target").empty();
$(div).appendTo("#target");
}
</script>
Hope this is helpful.
Related
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.
I have several buttons which should change content of region on the page. I've read numerous tutorials how can lazy load can be implemented using ajax, but unfortunately with no success. Here is my html:
<div>
<div>
<button id="btn_goals">Goals</button>
<button id="btn_achievements">Achievements</button>
</div>
<div id="region_content"></div>
</div>
and here is my js:
$(document).ready(function () {
$('#btn_goals').on('click', function () {
$.ajax({
url: '#Url.Action("Index", "Goals")',
success: function (data) {
$('#region_content').html(data);
}
});
});
$("#btn_achievements").on("click", function () {
......
});
});
what is the problem?
********** EDIT ************
Well, I changed url in ajax parameters from url: '#Url.Action("Index", "Goals")' to url: '/Goals/Index' and it starts work fine. What is the reason?
Try following the following steps:
Use console.log("Inside Success function"+ data); to test whether the required data is being returned from the controller method.
Use Ctrl+Shift+I in your browser to view the console. If Successful:
Use:
var div = document.getElementById("region_content");
div.innerHTML = div.innerHTML + data;
Make sure your type conversions are done right.
Also specify type: POST in your ajax function.
If you do not see 'Inside Success function' on your console, there might be something wrong with your controller function.
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
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(...)
I am developing an application using Symfony2 and Jquery as a JavaScript FW. I am using Twig for the templates. I render a template from the controller and after making a selection using the cursor in the template I would like the value of the selected tag to be returned to the controller when submitting using a submit button in the mentioned template.
I use the next Jquery function:
$("MatchedTag").click(function ()
{
$(this).toggleClass("highlight");
var IdOfTag = this.id;
$.ajax({
url: "{{ path('AcmeAcmeBundle_myaction') }}",
type: "POST",
data: { "tag_id" : idOfTag },
success: function(data) {
//(success) do something...
//variable "data" contains data returned by the controller.
}
});
});
I guess in the controller, in myaction I should use something like $_POST["tag_id"] or getrequest() , bindrequest() to get the value but I dont really know how. Could someone give me an example. Thanks.
You can try to get this parameter by :
$request->request->get('tag_id');
Update
simple action
namespace Acme\HelloBundle\Controller;
use Symfony\Component\HttpFoundation\Response;
class HelloController
{
public function indexAction($name)
{
$myParam = $request->request->get('tag_id');
// write your code here
}
}