jQuery Img toggle Ajax post - javascript

I have two images, when I click on green.png it changes to red.png. But when I load the page and its already set as red.png I need to click the img twice before it changes.I would like to only click once.
$(".page-state").toggle(function(event){
this.src = "images/red.png";
var id = event.target.id; //the Div ID variable
var dataString = 'page='+ id + '&view=off';
$.ajax({
type: "POST",
url: "pageState.php",
data: dataString,
cache: false,
});
$('#mainFrame')
.attr('src', $('iframe')
.attr('src'))
}, function(event) {
this.src = "images/green.png";
var id = event.target.id; //the Div ID variable
var dataString = 'page='+ id + '&view=on';
$.ajax({
type: "POST",
url: "pageState.php",
data: dataString,
cache: false,
});
$('#mainFrame')
.attr('src', $('iframe')
.attr('src'))
});
How can I improve this?

jQuery:
$(".page-state").click( function() {
var s = $(this).attr("class").split(" ");
if(s[1] == 'red') {
this.src = 'green.png';
$(this).removeClass('red').addClass('green');
// more code for green
}
else {
this.src = 'red.png';
$(this).removeClass('green').addClass('red');
// more code for red image
}
});
HTML:
<img class="page-state red" src="red.png" />
As you can see that .page-state has class which indicates that what by default, it consists red or blue.

Related

How to switch displayed image after AJAX process?

I want to switch from a displayed image to another after an AJAX request completes.
Here is the code for the AJAX call:
<script type="text/javascript">
$(document).ready(function(){
$('.item').click(function(){
var $id = $(this).attr('data-id');
$.ajax({
type: "POST",
url: "test.php",
data: { id: $id },
success: //
})
});
});
</script>
Here is the HTML :
<div class="item" data-id="1"><img src="image1.png" /></div>
If image1.png is displayed, I want to display image2.png instead.
If image2.png is displayed, I want to display image1.png instead.
Please, help me to fill the success part in the AJAX process.
You can use the .find() method to find the image child, and then .attr() to get and set the attribute for the src property.
So before the AJAX call, find the image:
var image = $(this).find('img');
Then in the success function, check the src attribute and set it using attr():
success: function(data) {
if (image.attr('src') == 'image1.png') {
image.attr('src', 'image2.png');
} else {
image.attr('src', 'image1.png');
}
}
See it demonstrated in the example below:
var urls = [
"https://i.stack.imgur.com/C92ci.png?s=32&g=1", //image1.png
"https://www.gravatar.com/avatar/8911010cdec4bb9d56b83b6bbbb1f341?s=32&d=identicon&r=PG"
];
$(document).ready(function() {
//demonstration container- for AJAX request response
var questionsContainer = $('#questions');
$('.item').click(function() {
var $id = $(this).attr('data-id');
var image = $(this).find('img');
$.ajax({
url: "https://api.stackexchange.com/2.2/questions?order=desc&sort=activity&site=stackoverflow",
success: function(data) {
var index = urls.indexOf(image.attr('src'));
image.attr('src', urls[Math.abs(index-1)]);
/*if (image.attr('src') == urls[0]) {
image.attr('src', urls[1]);
} else {
image.attr('src', urls[0]);
}*/
questionsContainer.html('# of Questions: ' + data.items.length);
}
});
questionsContainer.html('...');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item" data-id="1"><img src="https://www.gravatar.com/avatar/8911010cdec4bb9d56b83b6bbbb1f341?s=32&d=identicon&r=PG" /></div>
<div id="questions">Click the image to load # of questions</div>
Hope this helps.If needed we can use toggle jquery function to toggle between these two images.
<script type="text/javascript">
$(document).ready(function(){
$('.item').click(function(){
var $id = $(this).attr('data-id');
var $imgId = $('.item img').attr('src');
$.ajax({
type: "POST",
url: "test.php",
data: { id: $id , ImageId :$imgId },
success: function(data){
if(ImageId == 'image1.png'){
$(this).attr('src', 'image2.png');
}
else{
$(this).attr('src', 'image1.png');
}
}
})
});
});
</script>

Append a button with a specific ID returned from PHP is not working

I am appending a button to a row when adding via Ajax and PHP:
var addHistory = function()
{
var patient_medication = $("#patient_medicationn").val();
var disease = $("#disease option:selected").text();
var patient_side_effect = $("#patient_side_effect").val();
var pid = $("#pid").val();
var elem = '<button type="button" class="btn btn-danger btn-sm"
id="delete_disease" name="delete_disease"><i class="fa fa-remove"></i>
</button>';
$.ajax({
url: '../php/history.php',
data: {pid: pid, patient_medication: patient_medication, disease:
disease, patient_side_effect: patient_side_effect},
type: 'POST',
dataType: 'TEXT',
success:function(resp)
{
console.log(resp)
$("#after_th").after("<tr id='resp'><td>"+disease+"</td><td>"+patient_medication+"</td><td>"
+patient_side_effect+"</td><td>"+elem+"</td></tr>")
},
error:function(resp)
{
console.log(resp)
}
})
}
And on click:
$(document).ready(function()
{
$("#add_history").on('click', addHistory);
});
In my php file:
$addHistory = "INSERT INTO history(patient_medication, patient_side_effect, disease, patient_id, clinic_id)
VALUES(:patient_medication, :patient_side_effect, :disease, :patient_id, :clinic_id)";
$ExecAddHistory = $conn->prepare($addHistory);
$ExecAddHistory->bindValue(':patient_medication', $patient_medication);
$ExecAddHistory->bindValue(':patient_side_effect', $patient_side_effect);
$ExecAddHistory->bindValue(':disease', $disease);
$ExecAddHistory->bindValue(':patient_id', $pid);
$ExecAddHistory->bindValue(':clinic_id', $clinic_id);
$ExecAddHistory->execute();
$lastId = $ExecAddHistory->lastInsertId();
echo $lastId;
I am echoeing the last insert ID so I can append it to the newly added <tr> and then if directly the user clicked on the remove button, to delete directly if a mistake happened while adding the history.
Now everything working properly and the new row is appending, but it's remove button does not work at all.
The remove button of already existing rows works fine:
$("#delete_disease ").on('click', function()
{
var elem = $(this).closest('tr');
console.log(elem)
var patient_medication_id = $(this).closest('tr').attr('id');
var pid = $("#pid").val();
if(confirm("Are you sure that you want to remove the selected history?"))
{
$.ajax({
url: "../php/deleteDiseaseFromHistory.php",
type: 'POST',
data: { pmid: patient_medication_id, pid: pid},
dataType: 'TEXT',
success:function(resp)
{
if(resp="deleted")
{
elem.fadeOut(800, function() {
//after finishing animation
});
}
},
error:function(resp)
{
alert("Please try again");
}
});
}
});
You need
$(document).on('click', '#delete_disease ', function(event)
in place of
$("#delete_disease ").on('click', function()
Since the content has been loaded through AJAX.

how to make jquery remove() on just one item

this is the first time i use jquery and im trying to figure out to to make jquery remove(), remove just one item with a specific class, not every item with the same class.
my code is like this
jquery:
$(function() {
$(".vote").click(function()
{
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
if (name == 'up') {
$(this).fadeIn(600).html('<span class="glyphicon glyphicon-ok"></span>');
$.ajax({
type: "POST",
url: "up_vote.php",
data: dataString,
cache: false,
success: function(html) {
parent.html(html);
$(".vote").remove();
$(".escondido").css("display", "block");
}
});
}
(code continues with else vote down)
after clicking on a up button, the jquery code removes the button containing class vote, but if i have 2 buttons with class vote, both will be removed. i want to delete just the one clicked. any idea how?
<button type="button" class="btn btn-success btn-xs vote up" name="up" id="'.$reg['id'].'">BUTTON</button>
thank you!
you need to add a reference to this in the scope of the click for usage in your success callback, then jQuery it like you've jQueried other this's:
$(function() {
$(".vote").click(function()
{
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
var _this = this;
if(name=='up')
{
$(this).fadeIn(600).html('<span class="glyphicon glyphicon-ok"></span>');
$.ajax({
type: "POST",
url: "up_vote.php",
data: dataString,
cache: false,
success: function(html)
{
parent.html(html);
$( _this ).remove();
$( ".escondido" ).css( "display", "block" );
}
});
}
});
as a bonus, here's a refactored version that saves some cpu cycles and prettyfies the code a bit:
$(function() {
$(".vote").click(function()
{
var $this = $(this),
id = $this.attr("id"),
name = $this.attr("name"),
dataString = 'id='+ id;
if(name=='up')
{
$this.fadeIn(600).html('<span class="glyphicon glyphicon-ok"></span>');
$.ajax({
type: "POST",
url: "up_vote.php",
data: dataString,
cache: false,
success: function(html)
{
$this.html(html);
$this.remove();
$( ".escondido" ).css( "display", "block" );
}
});
}
});
});
You can declare a new variable that references $(this) so that you can use it in the scope of the $.ajax() function. Alternatively, you can also declare the context property of the $.ajax() function as follow:
$.ajax({
type: "POST",
url: "up_vote.php",
data: dataString,
cache: false,
context: this, // Passes $(this)
success: function(html) {
parent.html(html);
$(this).remove();
$(".escondido").css("display", "block");
}
});

Targeting specific element jquery

I have searched this on the net however couldn't find a solution, simply I would like to replace the content inside button element with ajax response. The only problem I am facing is that, the whole divs are being changed not the one I click on. If I change the class to id only the first one changes not the specific button I want. So how do I replace the content of specific button?
PHP Code:
while($row = $result->fetch_assoc()){// there are four rows so I have 4 buttons.
echo "<button class=btn btn-primary test' value='."$row['id']".'>."$row['voteup']".</button>";
}
javascript code:
$(function() {
$('.test').on('click', function() { // attach the click to the button
var test_val = $(this).val(); // Grab the value from the button
$.ajax({
type: "GET",
url: "test.php", // Move ?tar=vrate to the data array.
data: {tar: 'vrate', test: test_val},
cache: false,
success: function(response)
{
$(".test").fadeIn('slow').html(response);//this is replacing all 4 buttons not just one, if I change the class to id, only the first one is being replaced with the response. I also tried $( .test", this) but no luck.
}
});
});
});
$(function () {
$('.test').on('click', function () {
var test_val = $(this).val();
$.ajax({
// -------v Set the context of the callback
context: this,
type: "GET",
url: "test.php",
data: {
tar: 'vrate',
test: test_val
},
cache: false,
success: function (response) {
// v--and use `this` here
$(this).fadeIn('slow').html(response);
}
});
});
});
Try to use the $(this) reference here to achieve what you want,
$('.test').on('click', function() { // attach the click to the button
var test_val = $(this).val(); // Grab the value from the button
var $this = $(this);
$.ajax({
type: "GET",
url: "test.php", // Move ?tar=vrate to the data array.
data: {tar: 'vrate', test: test_val},
cache: false,
success: function(response)
{
$this.fadeIn('slow').html(response);
}
});
});

Load jQuery Dialog with cascading dropdowns from server

I have a jQuery dialog that needs to be opened and populated with data from a database. The dialog has in it drop downs that when in a "new" mode (not editing for re-saving) cascade.
How can I load the dialog with the values from the database, while at the same time causing the cascading to happen.
I have tied using the onfocus event of the dialog when the dialog is in "edit" mode, but the focus hit every time an element gets focus. Didn't work without being sneaky with the editing mode.
I have tried opening the dialog and using jQuery to set the dropdown, which works, but then the cascading does work.
For the cascading I am using .change on the the different dropdowns.
Not sure if the code is going to help, but will post some to itterate the jQuery functionality I am using.
The question is: How do I open a dialog, load dropdowns with information from the server and have the .change functionality work?
$('#collectDD').change(function(){
// first change the item drop down list
var collection = $('#collectDD').val();
data = "coll=" + collection + "&action=getItems&func=";
$('#addCollection').text(collection);
$.ajax({
url: "getItemList.php",
type: "GET",
cache: false,
data: data,
success: function (html) {
$('#itemDD').empty();
$("#itemDD").html(html);
// now update the function collection dropdown
data = "coll=" + collection + "&action=getFunction";
}
});
Collection DD HTML
<select id="collectDD" name="collectionDD">
<option>Select Collection</option>
<option>Option1</option>
</select>
This doesn't exactly match up with your tag names, and I made a little change to the data string, but I think it's in line with what you're looking for
<div id="dialogbox">
<select id="s1"></select>
<select id="s2"></select>
<select id="s3"></select>
</div>
<script type="text/javascript">
$(document).ready( function() {
$( "#dialogbox" ).dialog({
open: function(event, ui) {
var s1 = $("#s1").empty();
var s2 = $("#s2").empty();
var s3 = $("#s3").empty();
s1[0].enabled = false;
s2[0].enabled = false;
s3[0].enabled = false;
//load first dropdown from the database
var data = "coll=dropdown1&val=&action=getItems&func=";
$.ajax({
url: "getItemList.php",
type: "GET",
cache: false,
data: data,
success: function (html) {
s1.html(html);
s1[0].enabled = true;
}
});
//load the second DD when the first changes
s1.change( function() {
s2[0].enabled = false; //disable until after ajax load
s3[0].enabled = false;
data = "coll=dropdown2&val=" + s1.text() + "&action=getItems&func=";
$.ajax({
url: "getItemList.php",
type: "GET",
cache: false,
data: data,
success: function (html) {
s2.empty().html(html);
s2[0].enabled = true;
}
});
});
s2.change( function() {
if (s2[0].enabled) { //test for enabled to prevent some unnessecary loads
s3[0].enabled = false;
data = "coll=dropdown3&val=" + s2.text() + "&action=getItems&func=";
$.ajax({
url: "getItemList.php",
type: "GET",
cache: false,
data: data,
success: function (html) {
s3.empty().html(html);
s3[0].enabled = true;
}
});
}
});
}
});
});
</script>
UPDATE
Here is an example with change functions in their own functions
<div id="dialogbox">
<select id="s1"></select>
<select id="s2"></select>
<select id="s3"></select>
</div>
<script type="text/javascript">
var s1, s2, s3, data;
$(document).ready( function() {
s1 = $("#s1").empty();
s2 = $("#s2").empty();
s3 = $("#s3").empty();
$( "#dialogbox" ).dialog({
open: function(event, ui) {
s1[0].enabled = false;
s2[0].enabled = false;
s3[0].enabled = false;
//load first dropdown from the database
data = "coll=dropdown1&val=&action=getItems&func=";
$.ajax({
url: "getItemList.php",
type: "GET",
cache: false,
data: data,
success: function (html) {
s1.html(html);
s1[0].enabled = true;
}
});
//load the second DD when the first changes
s1.change( changeDD1 );
//load the third DD when the second changes
s2.change( changeDD2 );
}
});
});
function changeDD1() {
s2[0].enabled = false; //disable until after ajax load
s3[0].enabled = false;
data = "coll=dropdown2&val=" + s1.text() + "&action=getItems&func=";
$.ajax({
url: "getItemList.php",
type: "GET",
cache: false,
data: data,
success: function (html) {
s2.empty().html(html);
s2[0].enabled = true;
}
});
}
function changeDD2() {
if (s2[0].enabled) { //test for enabled to prevent some unnessecary loads
s3[0].enabled = false;
data = "coll=dropdown3&val=" + s2.text() + "&action=getItems&func=";
$.ajax({
url: "getItemList.php",
type: "GET",
cache: false,
data: data,
success: function (html) {
s3.empty().html(html);
s3[0].enabled = true;
}
});
}
}
</script>

Categories