data to javascript handler - javascript

I'm trying to find the best way to provide some information to ajax handlers from html markup.
The scenario is:
for i=0; i<5; i++
print <div class="clickable"></div>
Let's say that div will be clicked to add a product to a shopping cart. Like
$('.clickable').click(function{
cart.add(this.somethind);
})
I would like to transmit to that handler the unique sql id of that product clicked.
1) one ideea would be to add an attribute to that div, and store the information there. what do you think about this ideea?
2) is there any other way to achive this, without using html markup?
info: Client side-jquery, Server side-PHP, not xml-xsl transformation used.
Thanks!

There is a jQuery metadata plugin just for those scenarios
<?php
print '<div class="clickable {id: 1}"></div>';
// or (HTML5-like)
print '<div class="clickable" data-id="1"></div>';
?>
// jQuery
$('.clickable').click(function{
cart.add($(this).metadata().id);
})
There are several other ways of providing metadata, check out project page

You could store it using jquery's data on the div.
$('.clickable').click(function{
cart.add(jQuery.data($(this), "id"));
});
EDIT
In response to your comment use this data link:
You could have you id as an HTML5 attribute:
<?php
print '<div class="clickable" data-id="1"></div>';
?>
Then you would access that id using data this way:
$('.clickable').click(function{
cart.add($(this).data("id"));
});
Note that this requires jquery 1.4.3 and above to work.

Related

Opening jQuery UI Dialog box with dynamic content and then dynamically react to click in the dialog

I want to populate a jQuery dialog with dynamic content from a getData.php file. That works fine so far via:
$("#buttonGetData").click(function() {
$.get("getData.php", function(data){
$("#dialog").html(data);
$("#dialog").dialog();
return false;
});
});
The getData.php just gives something back like:
<p id="data1" class="data">data1</p>
<p id="data2" class="data">data2</p>
<p id="data3" class="data">data3</p>
My problem now is: How do I add a dynamic click listener to each data row so I can use the clicked data in my site? I want each 'p' be clickable and then use the data inside for setting its content to a 'textarea'.
The problem seems to be, that the new dynamically added rows arent part of the JS from the site, so I can't reach them via a clickListener.
How would this be done correctly? Thank You!
When you get html related data result using Ajax like you used $(get)... , your newly generated html from Ajax cannot be used for jQuery code OR in other word jQuery/JS don't recognized your newly added html elements generated from Ajax. There is a way you can achieve your required result. You can send your jQuery/JS code with html codes to Ajax from your file (getData.php) as String.In your getData.php you can echo like this.
echo '<p id="data1" class="data">data1</p>';
echo '<script>';
echo "$(document).on('click', '#data1', function(){alert('DATA1 Clicked');});"
echo '</script>';
die();
Above may be very straight forward answer so there is another way which may be more convicting. You can also used delegation on based on event handler. Examples:
$("#dialog").on("click","p", function(){
alert("DATA1 Clicked");
// your code to add content of this element to textarea
});
$("#dialog").on("click","#data1", function(){
alert("DATA1 Clicked");
// your code to add content of this element to textarea
});
$(document).on('click', '#data1', function(){
alert("DATA1 Clicked");
// your code to add content of this element to textarea
});
One of them should be able to solve the problem.

editing html with embedded PHP using javascript

I hope someone has an answer for me,
I am currently trying to create a PHP product page for my shop website, I have an sql table that stores the name of an image prefix eg if the image file is 'test_1.png' then the table stores 'test'. using embedded php
src="images/shop/<?php echo $row['item_img'], '_1.png';?>"></img>
what I would like to do is using js, dynamically update the src on a mouse click.
something like eg.
var imgSwitch = function(i){
Document.getElementById('js-img').src = "images/shop/
<?php echo $row['item_img'], '_';?>i<?php echo '.png';?>";
}
Even to me this seems wrong which is why I've turned to the GURU's here
Is there anyway this would be possible? If not, any suggestions would be GREATLY appreciated
I am trying to figure out what you are asking, and I think this is your way to go:
var imgSwitch = function(i){
document.getElementById('js-img').src = "images/shop/<?php echo $row['item_img'], '_';?>" + i + ".png";
}
The change is in the i, you have to cut the string and add it as a variable.
But remember that the PHP code is executed at the server, and will not change once the page is sent to the client. When you execute that function, $row['item_img'] will always be the same.
A simple example which you can adapt. What I do in the code below is give the element an id and attach an onclick to it.
In the function we pass the id as a parameter (onclick(changeSrc(this.id))) and we manipulate the src using the getElementById as we have the id.
<img src="http://ladiesloot.com/wp-content/uploads/2015/05/smiley-face-1-4-15.png" id="test" onclick="changeSrc(this.id);" height="400" width="400" />
<script>
function changeSrc(id) {
document.getElementById(id).src = "http://i0.wp.com/www.compusurf.es/wordpress/wp-content/uploads/2014/04/smiley.jpeg?fit=1200%2C1200";
}
</script>
http://jsfiddle.net/tq1Lq5at/
Edit 1
You're using Document when it should be document, notice the lowercase d.

How can I send POST data and navigate with JQuery?

On my blog I have a lot of <pre> blocks containing code snippets.
What I want to do is add a .click() handler to all the <pre> elements on the page which will send its content to another page - let's call it viewcode.php - via POST.
I know how to send information to this page using $.ajax, I'm just not sure how to send the information and navigate to the page.
The idea is that visitors can click a <pre> which will navigate to another page containing the code on its own for readability and easy copy / paste.
I have a feeling the solution is dead simple and probably obvious, I just can't think of it.
Not sure I would handle it this way, probably I would simply pop up a dialog with the code rather than leave the page, but you could handle this by building a form using javascript then triggering a submit on that form instead of using AJAX.
Using dialogs with jQuery UI:
$('pre').on('click', function() {
$('<div title="Code Preview"><p>' + $(this).text() + '</p></div>').dialog({
... set up dialog parameters ...
});
});
Build a form
$('pre').on('click', function() {
var text = $(this).text();
$('<form class="hidden-form" action="something.php" method="post" style="display: none;"><textarea name="code"></textarea></form>')
.appendTo('body');
$('[name="code"]').val(text);
$('.hidden-form').submit();
});
You could use a hidden <form> element. Then set the onclick() attribute of the <pre> to copy the value from the <pre> to the form. Optionally, you can set the action attribute to select the page you'd like to post the information to. Finally, submit that form.
I know it's not elegant, but it'll work.
If your code snippets are stored somewhere in a database or files, I suggest you just link the snippets to a page where you get the snippet based on some identifier.
If the snippets are only contained in your html, and you just want to display them in a cleaner way, you shouldn't need any ajax posting. You might want to Use a hover div or a jquery plugin, that pop's up and shows a cleaner piece of code obtained from the pre element, something like:
$('pre').click(function() {
var code = $(this).html(); //this is the pre contents you want to send
$('#hoverDiv').html(code).show();
});
Yes, you have to create a form and submit it. You can do all sorts of things with ajax posts/gets but the only way to navigate to a post result is via an actual form post. Here is concise version of it:
$('<form style="display: none;"/>').attr('action', action).html(html).appendTo('body').submit();
My code does this:
// Navigate to Post Response, Convert first form values to query string params:
// Put the things that are too long (could exceed query string limit) into post values
var form = $('#myForm');
var actionWithoutQueryString = form[0].action.split("?")[0];
var action = actionWithoutQueryString + '?' + $.param(form.serializeArray());
var html = myArray.map(function(v, i) { return "<input name='MyList[" + i + "]' value='" + v + "'/>"; }).join("\n");
$('<form style="display: none;"/>').attr('action', action).html(html).appendTo('body').submit();

storing values on page to use with javascript

I am populating a list from php, and using the onClick event to run a javascript function once the link has been clicked, I need to associate the value for the engine to the link that has been clicked..and at the moment it is by having the value assigned to the TITLE tag as shown in the code below, I know this is not the proper way of doing this, so instead how could I store the values on the page and be able to access them in the javascript function, so depending on the link that is clicked it retrieves the corresponding value, I was thinking of a storing them as a javascript array or object? or something associative so I could access them from the id of the link so if the link is clicked with the id of e213, once it is clicked then inside the javascript function I could use, 'objectname'.value + 'idvariable', and the property names would be "value" + the id's of the links.
Any help would be great thanks!
<?php
connect();
$sql = "SELECT engine_id, engine, image, value FROM engines";
$result = mysql_query($sql);
while ($row=mysql_fetch_array($result) ) {
echo "<li><a style=\"color:#FF6600;\" id='e".$row['engine_id']."' title = '".$row['value']."' onclick='return enginepic(this)' onfocus='this.hideFocus=true;' href='".$row['image']."'>".$row['engine']."</a></li>";
}
?>
HTML5 allows attributes that start data- for this case. Eg...
<div data-whatever-property="some value" id="some-id"></div>
You can then fetch this data using:
document.getElementById('some-id').getAttribute('data-whatever-property')
Or with jquery...
$('#some-id').attr('data-whatever-property')
Or even easier...
$('#some-id').data('whateverProperty')
Notice that the data method on jQuery turns one-two-three to oneTwoThree. This is conforming to the dataset part of the html5 spec.
Also, consider adding your events via JavaScript rather than using onclick/onfocus/etc attributes. For a list of links, you'll get better performance out of delegated events, jquery makes these easy.
You could just pass in the data you want to the enginepic function as a parameter.
Your onclick would look something like this
onclick='return enginepic(this, \''" . $row['value'] . "\')
And your function declarations would look something like
function enginepic(oLink, data){
.
.
.
}

Passing information to jqModal

I'm using jqModal inside a Django application. What I would like to do is have a bunch of different links each of which passes a parameter to jqModal to have it call a different ajax url based on the parameter. For example, depending on the ID of what is click on, I want to do something like:
$('#popup').jqm({ajax: '/myapp/objects/' + id, trigger: 'div.modaltrigger'});
Where id is the id of whatever I've clicked on.
Is this possible to do?
Use data attributes of the triggering elements to store your URLs:
<div class="modaltrigger" data-ajax-url="/myapp/objects/108"...
Then use jqModal in the following way:
$('#popup').jqm({ajax: '#data-ajax-url', trigger: 'div.modaltrigger'});
You said you want to change the url depending on ID, so I assume your links look like this
<div id="obj1" class="modaltrigger">foo</div>
<div id="obj2" class="modaltrigger">bar</div>
And you want jqModal to call urls like this
/myapp/objects/obj1
/myapp/objects/obj2
Then this code should work
//must run before first ajax call is made
$('div.modaltrigger').each(function(i, ele) {
ele.title = '/myapp/objects/'+this.id;
});
$('#popup').jqm({
ajax: '#title',
trigger: 'div.modaltrigger'
});

Categories

Resources