Checking text of individual divs and changing content - javascript

I have repeats of the same code multiple times because of my PHP echoing the content out, and I want to interact with each div separately. It's hard for me to explain, but here's an example of the code repeated just twice. Hopefully it fully represents what I actually have...
<form id="favorite"><div id="images"><input type="submit" style="background-image: url(grey.png);" onclick="submit" value="" /></div></form>
<form id="favorite"><div id="images"><input type="submit" style="background-image: url(grey.png);" onclick="submit" value="" /></div></form>
javascript:
$('#favorite').submit(function() {
var url = document.URL;
if(document.getElementById("images").innerHTML.indexOf("grey") != -1) {
$.ajax({
type: "POST",
url: url,
data: $("#favorite").serialize(),
success: function(data)
{
$('#images').html("<input type=\"submit\" style=\"background-image: url(red.png);\" onclick=\"submit\" value=\"\" />");
}
});
} else {
$.ajax({
type: "POST",
url: url,
data: $("#favorite").serialize(),
success: function(data)
{
$('#images').html("<input type=\"submit\" style=\"background-image: url(grey.png);\" onclick=\"submit\" value=\"\" />");
}
});
}
return false;
});
So, if I were to click the image for the top form, it works perfectly. It will run the PHP and it will change the image without refreshing. If I click the bottom image, it will run the PHP, but it will refresh the page and it won't change the image. So it seems like if I click the bottom one, it doesn't like the Javascript. I don't know if it's because it's looking at both of the forms since they have the same ID (which I can't fix since it could possibly have hundreds), or something else, which I don't see any problems. I'm guessing there's some way to do it using "this", but I'm unsure of how to use it.
Thank you!

You need to change a few things. Your selector to bind the event only matches the first occurrence of #favourite as id's should be unique. You get around this by using an attribute equals selector.
In addition, ensure you select each sub-element in the context of the current form, similar to this:
$('[id=favorite]').submit(function () {
var $form = $(this); // the current form
var $image = $('#images', $form) // get images element in the context of current form
var url = document.URL;
if ($image.html().indexOf("grey") != -1) {
$.ajax({
type: "POST",
url: url,
data: $form.serialize(), // use current form, don't re-select
success: function (data) {
$image.html("<input type=\"submit\" style=\"background-image: url(red.png);\" onclick=\"submit\" value=\"\" />");
}
});
} else {
$.ajax({
type: "POST",
url: url,
data: $form.serialize(), // use current form, don't re-select
success: function (data) {
$image.html("<input type=\"submit\" style=\"background-image: url(grey.png);\" onclick=\"submit\" value=\"\" />");
}
});
}
return false;
});

Related

AJAX request only executes on one checkbox, need it to execute on any

I have the following code, checkboxes are being generated by php based on the number of objects. There is one checkbox per object, and the code in the foreach that generates these is as follows (NOTE: this part is working fine, my problem is below):
"<input type='checkbox' name='markAsUnread' id='markRead' value='$sms->id' class='markAsUnread'>",
Here is the jQuery script that I am trying to use to mark any of the "clicked" boxes as "read". This particular script works when the first box is clicked at any time, but I need it to work for any of the boxes clicked (second, third, etc). I only need it to work on one at a time, but I need it to do so with any one selected.
<script type="text/javascript">
var myEl = document.getElementById('markRead');
myEl.addEventListener('click', function() {
var bloop = $('#markRead').val();
$.ajax({
type: 'POST',
url: '/link/to/route',
data: {sms: bloop},
success: function(data) {
window.location = '/foo/bar';},
contentType: "application/json",
dataType: 'json'
});
}, false);
</script>
I assume that it is not working because it is only grabbing the first box, so what needs to be changed to make it work with any of the selected checkboxes?
That should not work. If you repeatedly create elements with the same id, you violate html rules. There can only be one.
Instead of applying the function to only one element, identified with an ID, as
var myEl = document.getElementById('markRead');
ask for all elements with the name "markRead":
var myElements = document.getElementsByName('markRead');
which gives you an array to iterate over.
Additionally change your jquery-selector from
$('#markRead')
to
$("[name=markRead]")
Also, make sure that id-values are actually unique within one html document.
try following script and check
<script type="text/javascript">
$(function(){
var myElements = $('input[name=markAsUnread]');
myElements.click(function() {
var bloop = $('input[name=markAsUnread]:checked').val();
$.ajax({
type: 'POST',
url: '/link/to/route',
data: {sms: bloop},
success: function(data) {
window.location = '/foo/bar';},
contentType: "application/json",
dataType: 'json'
});
}, false);
});
</script>
Also, remove ID attribute from your generated checkboxes or make it Unique instead of having same value for all elements.
So I solved it, iterating over the elements and adding a click listener within the iterator seemed to do the trick:
$(function(){
var myElements = document.getElementsByName('markAsUnread');
$.each(myElements, function (index){
$(this).on("click", function(){
$.ajax({
type: 'POST',
url: '/foo/bar',
data: {sms: $(this).val()},
success: function(data) {
window.location = '/back/home';},
contentType: "application/json",
dataType: 'json'
});
});
});
});
I also removed IDs from the PHP generated checkboxes, as I wasn't using them.

Using jQuery or Javascript redirect to given page with a value

I have a dropdown, on its change it should redirect to a page with the dropdown's value say as a POST
I tried something like this:
$(document).ready(function() {
$('some_dropdown').change(function() {
var id = $(this).val();
var datastring = 'id=' + id;
$.ajax({
type: "POST",
url: "xyz.php",
data: datastring,
cache: false,
success: function(html) {
window.location.href("xyz.php");
}
});
});
});
On the xyz.php page:
if ($_POST['id']) {
Blah Blah..
}
It's not recognizing that id value on the xyz page. I want it's value on the redirected page.
Edited - To make things more clear, I tried out to print the xyz.php's contents on my original page (instead of redirecting) like this -
$.ajax({
type: "POST",
url: "xyz.php",
data: datastring,
cache: false,
success: function(html) {
$(".somediv").html(html);
}
FYI, "somediv" was <div class="somediv"></div> in my original page(no-redirecting) and it worked!! It could identify the id. Some how can't work it out with redirecting. It can't identify the id.
Edited --
Last thing, if I don't redirect and use
$.ajax({
type: "POST",
url: "xyz.php",
data: datastring,
cache: false,
success: function(html) {
$(".somediv").html(html);
}
The data loads perfect, my question is can I make some changes in the dynamically loaded textboxes and insert them in the database
If you have to make a post request can make it by appending a virtual form.
Here is the code for that.
$(document).ready(function() {
$('[name="some_dropdown"]').change(function() {
var mval = $(this).val(); //takes the value from dropdown
var url = 'xyz.php'; //the page on which value is to be sent
//the virtual form with input text, value and name to be submitted
var form = $('<form action="' + url + '" method="post">'+
'<input type="text" name="id" value="' + mval + '" />'+
'</form>');
$('body').append(form); //append to the body
form.submit(); //submit the form and the page redirects
});
});
and on PHP
if(isset($_POST['id'])){
echo $_POST['id'];
}
Your datastring should be key value pair. Like this.
var datastring = {'id':id};
you have few mistakes in your code so your correct code will be like this
$('.some_dropdown').change(function(){
var id = $(this).val();
var datastring = 'id='+id;
$.ajax({
type: "POST",
url: "xyz.php",
data: datastring,
cache: false,
success: function(html){
window.location.href= "xyz.php?"+datastring+"";
}
});
});
});
and php code
if(isset($_GET['id'])){
Blah Blah..
}

How to pass form input field value to external page using jquery

I have a form where I would like to pass the value of an text input field to an external page without a form submit event. I would like to field value to become a php variable on the external page.
Here is what I have so far:
<script type="text/javascript">
jQuery(document).ready(function() {
$(function() {
cityField = $('#the_form input[id=city]');
$.ajax({
type: "POST",
url: "external.php",
data:{ city: cityfield },
success: function(data){
console.log(data);
}
});
});
});
</script>
Within the external.php page, I would like to declare the city form field value as a php variable as
$city = $_POST['city'];
To start with
jQuery(document).ready(function() {
and
$(function() {
are equivalent. The $(function() should be something like
$("input[type='button']").click(function() {
so that when you click the button, it runs the ajax request.
I cleaned up the code but the data is not being sent to external.php. It is being set but not posting. Here is my revised code
<script type="text/javascript">
$('#city').blur(function() {
var cityField = document.querySelector('#city').value;
$.ajax({
type: "post",
url: "external.php",
data: {'cityField': cityField },
dataType: "text",
success: function(data, status){
if(status=="success") {
alert("You typed: " + cityField);
}
}
});
});
I dont feel right posting an answer for a single change... But
EDIT: There are actually a few things...
<!-- For .click() -->
Click Me!
<script type="text/javascript">
// $(function() { // Trigger on page load
// $('#doStuff').click(function() { // Trigger on a click
$('#city').blur(function() { // Trigger when the focus on the field is lost (click away, tab to another field, ect)
// $('#city').change(function() { // Trigger when the fields value changes
var cityField = $('#city');
$.ajax({
type: "POST",
url: "external.php",
data:{ 'city': cityField.val() },
success: function(data){
console.log(data);
}
});
});
</script>
Changes:
You dont need jQuery(document).ready(function() {}) AND $(function(){ }). Its the same thing.
Its smart to put a var in front on your variables.
Case is important. cityField and cityfield are not the same thing
You were just sending the whole dom element to your external script. (which I assume you only wanted the contents of the input)
Also, you dont need to look for "an input, with an 'id' attribute , with a value of 'city'". Just look for #city
EDIT:
Your updated code (just putting it here so its easier to see):
<script type="text/javascript">
$('#city').blur(function() {
var cityField=$('#city').val();
$.ajax({
type:"post",
url:"autosuggest.php",
data:{'cityField':cityField },
dataType:"text",
complete:function(data, status) {
alert("You typed: "+cityField);
}
});
});
</script>
Your data will should be available in autosuggest.php as $_POST['cityField'];
Having a status check within the success function, is a little redundant, in my opinion.
It would be better to move the success:function(data,... to a complete:function(data,...

Changing CSS class dynamically

I have an indicator on a page which is either a red or green circle.
<div class="publicBm changeState" currentstate="1" statusid="56" title="This is Public"></div> <!-- green -->
<div class="privateBm changeState" currentstate="1" statusid="57" title="This is Private"></div> <!-- red -->
When a user clicks the circle (which is a div with class changeState as shown above) an AJAX call is made to update the database to the opposite of what the item currently is, public or private. Then it returns the opposite class.
All works perfectly but I want to change the class on the circle clicked to reflect that the update has been successful.
Here's what I'm trying - as I said, the actual database call within the php file is perfect it's just that the div is not having it's class changed.
NOTE - there can be multiple lines on each page so I can't simply give the DIV an id
$('.changeState').click(function() {
var bm_id = $(this).attr('statusID');
var current = $(this).attr('currentState');
$.ajax({
type: "POST",
url: '/ajax/actions/editStateBm.php?bm_id='+bm_id+'&current='+current,
success:
function(data) {
$(this).removeAttr('class').attr('class', data + ' changeState');
}
});
});
Your issue is this. this is not the DOM element inside the ajax success callback. Instead set the context as that of the element so that this inside the callback now refers to the element and not jqXhr object.
$.ajax({
type: "POST",
url: '/ajax/actions/editStateBm.php?bm_id='+bm_id+'&current='+current,
context: this, //<-- Here
success:
function(data) {
this.className = data + ' changeState';
}
});
or use a cached context.
...
var self = this;
$.ajax({
type: "POST",
url: '/ajax/actions/editStateBm.php?bm_id='+bm_id+'&current='+current,
success:
function(data) {
self.className = data + ' changeState';
}
});
...
BTW what are you posting? you need to use GET?
$.ajax({
type: "GET",
....
Use .addClass()
success: function (data) {
$(this).removeAttr('class').addClass(data + ' changeState');
}
and removeProp
success: function (data) {
$(this).removeProp('class').addClass(data + ' changeState');
}
This should be something like:
$(this).removeClass('class').addClass(data + ' changeState');

My function only works with an alert after my ajax call

I'm populating a table with values from my database. I have included a delete icon in rows which can be deleted. The image has an onclick='deleteCat(id);' property, the id is taken from a json array trough a loop like so:
string = "<td align='center'><a href=''><img border='0' src='../images/Bullet-Delete.png' alt='delete' onclick='deleteCat("+json[i]['id']+");'/></a></td>";
This is my deleteCat function:
function deleteCat(id){
var dataString = "catId=" + id;
$.ajax({
type: "POST",
url: "../ajax/categorie_verwijderen.php",
data: dataString,
success: function(data) {
//$("#allecat").find("tr:gt(0)").remove();
//update_table();
}
});
//alert(id);
}
My function works when I put an alert after the ajax. The table refreshes and the row is removed from my db. However when I remove the alert my function does not work, the table is refreshed and the row is still present in the table and db.
Thanks in advance.
You need to prevent the default event for the click - ie the page is being reloaded each time you click on the image
function deleteCat(id){
var dataString = "catId=" + id;
$.ajax({
type: "POST",
url: "../ajax/categorie_verwijderen.php",
data: dataString,
success: function(data) {
$("#allecat").find("tr:gt(0)").remove();
update_table();
}
});
return false; // prevent the browser following the href
}
You will also need to change your html :
onclick='return deleteCat("+json[i]['id']+");
The alert() helps because that delays the processing of the remaining javascript in that function. The ajax send data asynchronously. async key is Default: true and should change it to false in your call till the client wait for end of ajax call.
e.g.:
$.ajax({
async:false,
url: "test.html",
.
.
});

Categories

Resources