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>
Related
I have index.php:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('.on').click(function() {
var val = $(this).val();
$.ajax({
url: "try.php",
type: "POST",
data: {'myVar': val}
});
});
$('.off').click(function() {
var val = $(this).val();
$.ajax({
url: "try.php",
type: "POST",
data: {'myVar': val}
});
});
});
</script>
<body>
<img class="bulb" src="bulb.png" alt="...">
<button class="on" value="http://pageon.org">On</button>
<button class="off" value="http://pageoff.org">Off</button>
</body>
I send value of buttons to try.php. Depending on the clicked button, I get one variable in the try.php file, for the ON button - 1 , for the OFF button - 0 (variable $curl_response).
Is it possible to change the img in the index.php file dynamically, depending on the received variable from the try.php page? For example, if the received variable is 1, src = "bulb.png", and if 0, then src = "bulb2.png"?
try.php :
<?php
$name = $_POST['myVar'];
$service_url = $name;
$curl = curl_init($service_url);
// Ustaw opcje połączenia
curl_setopt($curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );
//curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$curl_response = curl_exec($curl);
curl_close($curl);
?>
EDIT:
<script type="text/javascript">
$(document).ready(function () {
$('.btn').click(function() {
var val = $(this).val();
$.ajax({
url: "try.php",
type: "POST",
data: {'myVar': val}
success: function(result){
switch(result){
case "0":
$(".bulb").attr("src", "bulb.png");
break;
case "1":
$(".bulb").attr("src", "bulb2.png");
break;
}
}
});
});
});
</script>
Yes, you could use this, on the AJAX success:
$.ajax({
...
success: function(result){
switch(result){
case "1":
$("#yourImage").attr("src", "yourImagePath1.jpg");
break;
case "2":
$("#yourImage").attr("src", "yourSecondImagePath.jpg");
break;
}
}
});
EDIT/SUGGESTION
You don't need to trigger 2 separate events for each button if they are going to call the same URL and pass the same structure data. Use the same class to trigger:
HTML
<button class="buttonClass" value="http://pageon.org">On</button>
<button class="buttonClass" value="http://pageoff.org">Off</button>
JS
$(".buttonClass").click(function(){
var val = $(this).text();
//make here your ajax call passing 'val'
});
Have a look at the success option that you pass to $.ajax. That's where you provide the callback function that you want to run if the https request status is 200. Something like
$.ajax({
/** your other stuff, and... */
success : function(data) {
if (data == 1) {
$('button.on').attr({src : "bulb.png"})
}
// and so on
}
});
See http://api.jquery.com/jQuery.ajax/ for further information.
Yes simply you can add if-else condition based on your flag received in your ajax success method and update img src attribute using JavaScript
You can send an AJAX request when one of the buttons is clicked and handle the response, like this:
<script type="text/javascript">
$(document).ready(function () {
$('.on, .off').click(function() {
var val = $(this).val();
$.ajax({
url: "try.php",
type: "POST",
data: {'myVar': val},
success: function(result){
switch(result){
case "0":
$(".bulb").attr("src", "bulb.png");
break;
case "1":
$(".bulb").attr("src", "bulb2.png");
break;
}
}
});
});
});
</script>
I've got an AJAX code, that does POST reqeusts and displays results upon success. The displayed results are in JSON format and from a different website. The result displays all of the list items, but now I want to display only one item of my choice at the same time, instead of displaying all the items. I've been trying to use the each() and slice() functions, but I think I'm not using them correctly or I don't have any idea of how to deal with the problem. Please help, I'm new to AJAX and JQuery.
This is the code I have:
jQuery.ajax({
async:false,
url : "http://brandroot.com/index.php?option=com_brands&controller=brands&task=getbrandsbyuser",
data: postData,
type : "post",
dataType : "jsonp",
jsonp: "jsoncallback",
success : function(jsonData){
if (jsonData.product_display!=='') {
/**The code below will display all the items under a div="product_dispay"*/
jQuery('#product_display').append(jsonData.product_display);
//I want a code that will display one item of my choice at this section.
}else{
alert(jsonData.error);
}
},
error:function(){
alert('fail');
}
});
You can access the contents of the #product_display element with jQuery. The API returns HTML data so you can render it in the page, then using jQuery find the data within the HTML and do whatever you want with it.
I have added this code into your original code.
(function($){
var data = [];
var creatik = null;
$('#product_display .business_list').each(function(){
var price = $(this).find('p a span.price').text();
var bld = $(this).find('p a span.bld').text();
var img = $(this).find('.image_area a img').prop('src');
//How to check each logo
if("Creatick" === bld){
creatik = $(this).clone();
}
data.push({
price: price,
bld: bld,
img: img
});
});
//You can use this data as you please
console.log(data);
//you can replace the contents of the #product_display container with the one logo that you want
$('#product_display .business_detail').html(creatik);
//
})(jQuery);
This is the final code.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script></script>
<script type="text/javascript">
function getbrandsbyuser(user) {
var postData = {user: user};
jQuery.ajax({
async: false,
url: "http://brandroot.com/index.php?option=com_brands&controller=brands&task=getbrandsbyuser",
data: postData,
type: "post",
dataType: "jsonp",
jsonp: "jsoncallback",
success: function (jsonData) {
console.log(jsonData);
if (jsonData.product_display !== '') {
jQuery('#product_display').append(jsonData.product_display);
(function($){
var data = [];
var creatik = null;
$('#product_display .business_list').each(function(){
var price = $(this).find('p a span.price').text();
var bld = $(this).find('p a span.bld').text();
var img = $(this).find('.image_area a img').prop('src');
//How to check each logo
if("Creatick" === bld){
creatik = $(this).clone();
}
data.push({
price: price,
bld: bld,
img: img
});
});
//You can use this data as you please
console.log(data);
//you can replace the contents of the #product_display container with the one logo that you want
$('#product_display .business_detail').html(creatik);
//
})(jQuery);
} else {
alert(jsonData.error);
}
},
error: function () {
alert('fail');
}
});
}
jQuery(".image_area").each(function ()
{
jQuery(this).hover(
function () {
id = jQuery(this).attr("rel");
jQuery(this).children(".published_content_" + id).stop(true, true).fadeIn('slow', function () {
jQuery(this).children(".published_content_" + id).css("display", "block");
jQuery(this).children(".published_content_" + id).stop(true, true).animate({"opacity": 1}, 400);
});
},
function () {
id = jQuery(this).attr("rel");
jQuery(this).children(".published_content_" + id).stop(true, true).fadeOut('slow', function () {
jQuery(this).children(".published_content_" + id).css("display", "none");
jQuery(this).children(".published_content_" + id).stop(true, true).animate({"opacity": 0}, 400);
});
}
);
});
</script>
<script type="text/javascript">
jQuery.noConflict();
jQuery(document).ready(function () {
getbrandsbyuser("Sarfraz300");
});
</script>
</head>
<body>
<div id="product_display"></div>
</body>
</html>
I hope it helps.
This is the code:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script></script>
<script type="text/javascript">
function getbrandsbyuser(user) {
var postData = {
user: user
};
jQuery.ajax({
async:false,
url : "http://brandroot.com/index.php?option=com_brands&controller=brands&task=getbrandsbyuser",
data: postData,
type : "post",
dataType : "jsonp",
jsonp: "jsoncallback",
success : function(jsonData){
if (jsonData.product_display!=='') {
jQuery('#product_display').append(jsonData.product_display);
}else{
alert(jsonData.error);
}
},
error:function(){
alert('fail');
}
});
}
jQuery(".image_area").each(function ()
{
jQuery(this).hover(
function () {
id = jQuery(this).attr("rel");
jQuery(this).children(".published_content_"+id).stop(true, true).fadeIn('slow', function(){
jQuery(this).children(".published_content_"+id).css("display","block");
jQuery(this).children(".published_content_"+id).stop(true, true).animate({"opacity": 1}, 400);
});
},
function () {
id = jQuery(this).attr("rel");
jQuery(this).children(".published_content_"+id).stop(true, true).fadeOut('slow', function(){
jQuery(this).children(".published_content_"+id).css("display","none");
jQuery(this).children(".published_content_"+id).stop(true, true).animate({"opacity": 0}, 400);
});
}
);
});
</script>
<script type="text/javascript">
jQuery.noConflict();
jQuery(document).ready(function(){
getbrandsbyuser("Sarfraz300");
});
</script>
</head>
<body>
<div id="product_display"></div>
The result displayed upon success is in html format.
jsonData.product_display[i]
has not worked.
I'm making hover card on click for every users so i did for one and its working but i want this to work on every user like i have given them unique title and based on that the server will get the data of that particular users but the problem is this is working on only 1 links not for all the links...maybe its because var data is kept store (please correct me if i'm wrong) so i tried to do this on ajax cache: false but didn't help then i tried return false;, return data; still not use.
So, here is the users links example :
<a class="hover" title="user101" href="#">John</a>
<a class="hover" title="user102" href="#">Tonya</a>
Ajax :
$(document).ready(function () {
$.ajaxSetup({
cache: false
});
$('.hover').click(function () {
var get_val = $('.hover').attr('title');
var data = 'vall=' + get_val + '';
$.ajax({
type: 'POST',
url: 'xx.php',
data: data,
success: function (data) {
box.dialog({
message: data
});
return false;
}
});
});
});
I would do it this way.
HTML
<div class='links'>
<a title="user101" href="#">John</a>
<a title="user102" href="#">Tonya</a>
</div>
JS
$(document).ready(function () {
$.ajaxSetup({
cache: false
});
$('.links').on('click', 'a', function (event) {
event.preventDefault();
var get_val = $(this).prop('title');
$.ajax({
type: 'POST',
url: 'xx.php',
data: {vall: get_val},
success: function (data) {
box.dialog({
message: data
});
}
});
});
});
the problem is this is working on only 1 links not for all the links...maybe its because var data is kept store (please correct me if i'm wrong)
you are wrong.. only 1 links is working beacuse you have same id for multiple elements.. each elements should have unique id.
use class instead
<a class="hover" title="user101" href="#">John</a>
<a class="hover" title="user102" href="#">Tonya</a>
and a class selector and return false after ajax success callback function , at the end
$('.hover').click(function () {
var get_val = $('.hover').attr('title');
....
$.ajax({
....
success:function(){
....
}
});
return false;
..
or simply use preventDefault() instead of return false
$('.hover').click(function (e) {
e.preventDefault();
var get_val = $('.hover').attr('title');
.....
#cal div doesn't fade out after completion in jQuery.
<div id="main">
<div id="price"></div>
<div id="cal">Calculating...</div>
</div>
And here is my Javascript/jQuery code:
<script type="text/javascript">
$('#cal').hide();
$('#price_submit').click(function() {
var my_data = {
//successfully sends data
};
$('#price').fadeOut('fast', function(){
$('#cal').fadeIn();
});
$.ajax({
url: "proccess.php",
type: 'POST',
data: my_data,
success: function(msg){
$('#cal').fadeOut('fast', function() {
$('#price').fadeIn().html(msg);
});
}
});
return false;
});
</script>
at last it will successfully retrieve data and shows it but it still shows the #cal div bellow price. I'd appreciate your help.
I'll suggest you to stop previous animations and see:
$('#cal').stop().fadeOut('fast', function () {
$('#price').stop().fadeIn().html(msg);
});
I have just put your code
$('#cal').hide();
$('#price_submit').click(function() {
var my_data = {
//successfully sends data
};
$('#price').fadeOut('fast', function(){
$('#cal').fadeIn();
});
$.ajax({
url: "/echo/json",
type: 'POST',
data: my_data,
success: function(msg){
msg = '1134141234';
$('#cal').fadeOut('fast', function() {
$('#price').fadeIn().html(msg);
});
}
}
);
return false;
});
on
http://jsfiddle.net/pfpqv/ and it works just fine.
Can you give some more info to proper reproduce this your problem?
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.