How can I capture the attribute id from a dynamically generated html? - javascript

I am pretty sure this is not so complicated but I have been for hours trying to figure out how to catch the id of this dynamically generated anchor tags.
What I do in my code is that everytime a text input changes, theres an ajax request that goes to a php file and returns me a json array with the prices then I render this results of search in buttons that will be clickable to do other types of request but so far here's where I'm stuck.
heres's the code that loops through the array and renders this buttons (NOTE:The Id of the buttons are variables rendered by the function too.
$.ajax({
type: "POST",
url: "php/get_products.php",
data: {query:prod_qry},
success: function(data){
$('#loader_s').hide();
var jsarray = JSON.parse(data);
var length = jsarray.length;
for(i=0;i<jsarray.length;i++){
var index1 = i;
var index2 = Number(i++) + 1;
var index3 = Number(i++) + 2;
$('#modal-bod').append('<a onclick="renderProds();" class="btn btn-default-item prod_sel" style="margin-top:10px;" id="'+index3+'" data-dismiss="modal">'+jsarray[index1]+' <span class="pull-right" st>lps. '+jsarray[index2]+'</span></a>');
}
}
Then here's the function renderProds()
function renderProds(){
var id = $(this).attr('id');
alert(id);
}
the alert is just to try and catch the values for testing purposes, but what really goes there is another Ajax request.
The only thing I get here is that the var Id is undefined...

You can pass object like
function renderProds(obj) {
var id = obj.id;
alert(id);
}
Pass invoker object like
onclick="renderProds(this);"

I would do :
onclick="renderProds(this);"
function renderProds(that){
var id = that.id;
alert(id);
}

You use jQuery.. so USE jQuery !
Ajax can do the JSON.parse for you with just dataType: "json".
The inline onclick is bad practice.
Move the success function to make your code more readable.
$.ajax({
type: "POST",
url: "php/get_products.php",
data: {query:prod_qry},
dataType : 'json',
success: productsUpdate
});
function renderProds(event){
var id = $(event.target).attr("id");
alert("Id is:"+id);
}
function productUpdate(data){
$('#loader_s').hide();
for(i=0;i<data.length;i++){
var link = $('<a>....</a>');
link.click(renderProds);
$('#modal-bod').append(link);
}
}
Now, this is readable.
Complete the link creation with your code, without the onclick, remove the inline css and use a real css selector and finally, check this ugly Number(i++)+ .... it looks so bad.

Related

Ajax call returns data but in purely string format.

In PHP I can do things like this:
echo "<div>".$myvariable."</div>";
Which will print out my variable with div's in HTML for its tags. However recently, I needed to do a ajax call using jquery. I'm somewhat familiar with ajax but I don't use it much. Anyways, I run the ajax code, it prints the data into my HMTL element box like I wanted, however, the div tags are printed and displayed along with the content itself!
The entire return data is pretty much 1 long string, rather than the PHP parsing my data like I want it to. Where did I go wrong? Why is it only returning 1 long string?
PHP CODE:
<?php
require 'database.php';
$meal = $_POST['meals'];
$meal_q = "SELECT item
FROM meal_ingredients
WHERE meal_name='$meal'
ORDER BY item";
$meal_c = $conn->query($meal_q);
while ($row = $meal_c->fetch_assoc()){
$view_ingredient = $row['item'];
echo "<div>".$view_ingredient."</div>";
};
?>
JQUERY CODE:
if($('body').hasClass('CreateMealPage')){
$('tr').on('click', function(e){
$('#sidebar').animate({right: '-200px'}, 500);
var meals = $(this).find('.meals').text();
$.ajax({
method: "POST",
url: 'meal_list.php',
data: {meals: meals},
success: function(data) {
var sidebar = document.getElementById('sidebar');
sidebar.innerHTML = "";
sidebar.append(data);
}
});
});
};
WHAT IS RENDERED ON SCREEN:
<div>ingredientname</div>
<div>ingredientname</div>
<div>ingredientname</div>
RATHER THAN:
ingredientname
ingredientname
ingredientname
just replace
sidebar.innerHTML = "";
sidebar.append(data);
with
sidebar.innerHTML = data;
To answer your comment you can use append with following in jquery
$(sidebar).append($(data))
so jquery's append needs to be used, instead of append, from dom api, which takes a node element only in arguments. If you still need to use append of dom api, use something like:
sidebar.append(document.createRange().createContextualFragme‌​nt(data))
Add dataType: "html" to the properties in your $.ajax() call, like this:
$.ajax({
method: "POST",
url: 'meal_list.php',
dataType: "html",
data: {meals: meals},
success: function(data) {
var sidebar = document.getElementById('sidebar');
sidebar.innerHTML = "";
sidebar.append(data);
}
});
This will inform the call to expect HTML data to be returned in the response body.

jQuery AJAX onclick get DOM of a specified URL

I would like to make an AJAX pagination withot php and mysql, so when I click a link than I would like to get the next page DOM without reloading page and than in that DOM find the elements I need to append to the current page.
I now that jQuery IAS does this but I have a three col design and I need only one next button which onclick appends the data into the aproppriate col based on its parent class and IAS can't handle tree col layout.
So basicly something like this:
$('a.button').click(function(){
var url = $('a.next').attr('href');
$.ajax({
type: 'GET', //or POST i don't know which one
data: url, //or should this be the url: ?
success: function(data){
//data should be the DOM of the second page
$html = $(data);
$html.find('.col1 .child').appendTo('.col1');
$html.find('.col2 .child').appendTo('.col3');
$html.find('.col3 .child').appendTo('.col3');
}
});
return false;
});
Obviously this doesn't work I just put it here to make my question undersandable.
How can I do this?
yes it would be variable url such as
$('a.button').onclick(function(){
var url = $('a.next').attr('href');
$.ajax({
type: 'GET', //or POST i don't know which one
url: url, //or should this be the url: ?
success: function(data){
//data should be the DOM of the second page
$html = $(data);
$html.find('.col1 .child').appendTo('.col1');
$html.find('.col2 .child').appendTo('.col3');
$html.find('.col3 .child').appendTo('.col3');
}
});
return false;
});
you use data parameter to pass an object of key value pairs to the receiving end.
data: {key1: value1 , key2: value2}

how to pass php value from one file to another through java script

I am working with Concrete-5 CMS, I have an issue in passing value form view to controller.In my application I am using following code for displaying employee role.
foreach($rd as $data){
echo "<tr><td>".$data[role_name]."</td><td>".$data[role_description]."</td><td>Edit</td><td>".$ih->button_js(t('Delete'), "deleteRole('".$data['role_id']."')", 'left', 'error')."</td></tr>";
}
<input type="hidden" name="rno" id="rno" />
script:
$delConfirmJS = t('Are you sure you want to remove this Role?'); ?>
<script type="text/javascript">
function deleteRole(myvar) {
var role = document.getElementById('rno');
role.value = myvar;
if (confirm('<?php echo $delConfirmJS ?>')) {
$('#rolelist').submit();
//location.href = "<?php echo $this->url('/role/add_role/', 'delete', 'myvar')?>";
}
}
</script>
html code
I did edit operation by passing role_id through edit action. But, In case of delete i should ask for a conformation, so I use java script to conform it and call the href location and all.
But i don't know how to pass the role_id to script and pass to my controller. how to achieve this task?
thanks
Kumar
You can pass value to server using ajax calls.
See the following code. Here We use a confirm box to get user confirmation.
function deleteEmployee(empId){
var confirm=confirm("Do you want to delete?");
if (confirm)
{
var url = "path/to/delete.php";
var data = "emp_id="+empId;
$.ajax({
type: "POST",
url: "otherfile.php",
data: data ,
success: function(){
alert("Employee deleted successfully.");
}
});
}
}
In delete.php you can take the employee id by using $_POST['emp_id']
You can do it easily by using jquery
var dataString = 'any_variable='+ <?=$phpvariable?>;
$.ajax({
type: "POST",
url: "otherfile.php",
data: dataString,
success: function(msg){
// msg is return value of your otherfile.php
}
}); //END $.ajax
I would add an extra variable in to the delete link address. Preferrably the ID of the row that you need to be deleted.
I don't know Concrete-5 CMS. But, i am giving you the general idea
I think, you are using some button on which users can click if they want to delete role.
<td>".$ih->button_js(t('Delete'), "deleteRole('".$data['role_id']."')", 'left', 'error')."</td>
My suggestion,
add onClick to button
onClick="deleteEmployee(roleId);" // roleId - dynamic id of the role by looping over
Frankly speaking dude, i dont know how you will add this to your button that i guess there would surely be some way to simply add this to existing html.
And now, simply use Sajith's function
// Sajith's function here
function deleteEmployee(empId){
var confirm=confirm("Do you want to delete?");
if (confirm){
var url = "path/to/delete.php";
var data = "emp_id="+empId;
$.ajax({
type: "POST",
url: "otherfile.php",
data: data ,
success: function(){
alert("Employee deleted successfully.");
}
});
}
}

Telerik MVC Grid - Pass Value to New Controller Action

Using Telerik Extensions for ASP.NET MVC, I created the following Grid:
.. and I am able to extract the value of my Order Number using the client-side event "OnRowSelect", when the user selects any item in the grouped order. I can then get as far as displaying the selected value in an alert but what I really want to do is pass that value back to a different controller action. Is this possible using javascript?
When I tried the server-side control, I ended up with buttons beside each detail row, which was just not the effect/look desired.
You can easily make an ajax call in that event.
Kind of two part process (assuming your event handler resides in a separate .js file- otherwise you can define a url directly in .ajax call).
Define an url you need to post to - in $(document).ready(...)
like:
<script type="text/javascript">
$(document).ready(function() {
var yourUrl = '#Url.Action("Action", "Controller")';
});
Then place in your OnRowSelect event handler something like:
function onRowSelect(e) {
var row = e.row;
var orderId = e.row.cells[0].innerHTML;
$.ajax(
{
type: "POST",
url: yourUrl,
data: {id: orderId},
success: function (result) {
//do something
},
error: function (req, status, error) {
//dosomething
}
});
}
That should do it.
As it turns out there is an easier way to get to the new page by simply changing the Window.location as follows:
var yourUrl = '#Url.Action("Action", "Controller")';
var orderID;
function onRowSelected(e) {
var ordersrid = $('#IncompleteOrders').data('tGrid');
orderID = e.row.cells[1].innerHTML;
window.location = yourUrl + "?orderId=" + orderID;
}
Thanks to those who responded; however, the above answer as provided from Daniel at Telerik is more of what I was looking for.

how to pass and retrieve Html tags via querystring

Default.aspx
<script type="text/javascript">
$(function() {
$("#add_questions").click(function() {
var question = $("#wmd-output").val();
var option1 = $("#option1").val();
var option2 = $("#option2").val();
var option3 = $("#option3").val();
var option4 = $("#option4").val();
var answer = $("#answer").val();
var paper = $("#txt_subject_id").val();
var dataString = 'question='+ question +'&option1='+option1 +'&option2='+option2 +'&option3='+option3 +'&option4='+option4 +'&answer='+answer+'&paper='+paper;
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="../images/validate.gif" align="absmiddle">');
//alert(dataString)
$.ajax({
type: "GET",
url: "Default2.aspx",
data: dataString,
cache: false,
success: function(html){
$("#display").after(html);
//alert(html)
//document.getElementById('content').value='';
//document.getElementById('content').focus();
$("#flash").hide();
}
});
return false;
});
});
</script>
Let
dataString="question=p>hello</p>&option1=option1&option2=option2&option3=option3&option4=option4&answer=answer&paper=paper"
How could I pass this query string to next page using jquery? I didn't get response from the next page, which means the question=<p>hello</p> not getting the value.
Default2.aspx
Dim question As String
question = Request.QueryString("question")
Response.Write(question)
I also tried encodeUri and encodeURIcomponent.
You say that you try the encodeURIcomponent but I am afraid that you apply it on the full line. You must apply the encodeURIcomponent to each value alone to make it work as:
var dataString = 'question='+ encodeURIcomponent(question) +'&option1='+
encodeURIcomponent(option1) +'&option2='+ encodeURIcomponent(option2) +'&option3='+
encodeURIcomponent(option3) +'&option4='+ encodeURIcomponent(option4) +'&answer='+
encodeURIcomponent(answer)+'&paper='+ encodeURIcomponent(paper);
Also, do you have check that you read the values from var question = $("#wmd-output").val(); ? is the "#wmd-output" the correct one or you need to add the rendered client id ?
First of all thanks to everyone for their effort.
This is what i did
question=encodeURIComponent(question)
var dataString = 'question='+ encodeURIComponent(question) +'&option1='+ option1 +'&option2='+ option2 +'&option3='+ option3 +'&option4='+ option4 +'&answer='+ answer +'&paper='+ paper;
I have used encodeURIComponent twice and while decoding at the server side
quest = Server.UrlDecode(question)
display the correct value.
Thanks again for help !!
I am afraid you can't pass HTML via querystring. You can use Session instead. You can store HTML in a string variable and store it in Session. On next page, you can retrieve it from Session.
Session.Add("myHTML","<p></p>");
On next page load
String html = Session["myHTML"].ToString();

Categories