Changing class type using Jquery - php

I am using this code to fetch the data from startup.php.The response of the PHP file is JSON with 3 fields. One of the field in JSON response is a status message. How to change the value of div class .content based on the status message. I need to do that to change the color of the text displayed in the content DIV based on the status message. .content is the class name of the DIV
var loadinggif = '../img/loading.gif';
$(document).ready(function(){
// set up the click event
$('body').on('click','.btnbg', function() {
var toLoad = '../vr/startup.php';
$('.content').empty();
$('.content').slideUp('slow', loadContent);
$('#load').remove();
$('#waiting').append('<div id="load"><img src="' + loadinggif + '" alt="Loading" /></div>');
$('#load').fadeIn('normal');
function loadContent() {
var userName = $('#userName').val();
var remote_addr = $('#remote_addr').val();
var forwarded_for = $('#forwarded_for').val();
var url = $('#url').val();
//$('#forwarded_for1').val()'';
var _post = {'userName': userName, 'ipAddr1':remote_addr,'ipAddr2':forwarded_for, 'url':url};
$('.content').load(toLoad, _post , function(response, status, xhr)
if (status == 'error') {
var msg = "Sorry but there was an error: ";
$(".content").html(msg + xhr.status + " " + xhr.statusText);
}
}).slideDown('slow', hideLoader());
}
function hideLoader() {
$('#load').fadeOut('normal');
}
return false;
});

You can use the css() function in Jquery :
$(".content").css({'background-color': 'red'});
Edit
I red your question wrong. To change class you can use $('.content').removeClass('classOne').addClass('classTwo');
If you have a class like has-error, you can use toggleClass() to toggle it, it will remove it if it's present or add it if not :
$('.content').toggleClass('has-error');
for your if elseprobleme, simply do :
if(condition) {
$('.content').removeClass('class2 class3').addClass('class1');
} else if(condition2) {
$('.content').removeClass('class1 class3').addClass('class2');
} else {
$('.content').removeClass('class1 class2').addClass('class3');
}

Use removeClass() and addClass().
Here is an example:
$('.content').removeClass("styleOne").addClass("styleTwo");
Edit
if(response == "Worked Fine"){
$('.content').removeClass("default").addClass("styleGreen");
}else{
$('.content').removeClass("default").addClass("styleRed");
}

Related

Yii2 save tag-post via Ajax on dropdown change

I am trying to save tag in database table every time Html::DropDownList option is changed. On debug session it redirects me on ErrorHandler.php but no error is shown.
my jQuery:
var ddList = $('.dd-list');
var tagList = $('.tag-container');
ddList.on('change', function () {
var tagHolder = document.createElement('div');
tagHolder.setAttribute('class', 'tag-holder');
var selected = $('.dd-list option:selected').text();
tagHolder.setAttribute('id', selected);
if(tagList.find('div').length > 2){
alert('You can have most 3 tags!');
return false;
};
if(tagList.find('#'+selected).length){
return false;
}else{
tagHolder.append(selected);
tagList.append(tagHolder);
$.ajax({
method : 'GET',
dataType : 'text',
url : '../post/save-tag?tag=' + selected,
success : function (data) {
alert("Tag saved: " + data);
}
});
}
});
actionSaveTag :
public function actionSaveTag($tag)
{
return \Yii::$app->db->createCommand('INSERT INTO tags(tag_name)
VALUES (' . $tag . ')');
}
I tried also VALUES ($tag) without single quotes but same result.
How should i make it? Appreciating all advices!

Two different ajax requests without refreshing page

I have a site that uses ajax to load a post directly to the page when clicked.
But... I also have an ajax contact-form at the same page. But if I click a post first, then want to send a message later, it fails. But if I refresh the page and go straight to the contact-form and send a message it doesn't fail at sending. Is there any way that I can maybe "reload" ajax without refreshing the page so that you can do multiple things at my site with ajax?
$(document).ready(function() {
function yournewfunction() {
var requestCallback = new MyRequestsCompleted({
numRequest: 3,
singleCallback: function() {
alert("I'm the callback");
}
});
var width = 711;
var animationSpeed = 800;
var pause = 3000;
var currentSlide = 1;
var $slider = $("#slider");
var $slideContainer = $(".slides");
var $slides = $(".slide");
var $toggleRight = $("#right");
var $toggleLeft = $("#left");
$toggleRight.click(function() {
$slideContainer.animate({
'margin-left': '-=' + width
}, animationSpeed, function() {
currentSlide++;
if (currentSlide === $slides.length) {
currentSlide = 1;
$slideContainer.css('margin-left', 0);
}
});
});
$toggleLeft.click(function() {
if (currentSlide === 1) {
currentSlide = $slides.length;
$slideContainer.css({
'margin-left': '-' + width * ($slides.length - 1) + 'px'
});
$slideContainer.animate({
'margin-left': '+=' + width
}, animationSpeed, function() {
currentSlide--;
});
} else {
$slideContainer.animate({
'margin-left': '+=' + width
}, animationSpeed, function() {
currentSlide--;
});
}
});
if ($(".slide img").css('width') == '400px' && $(".slide img").css('height') == '400px') {
$(".options").css("width", "400px");
$(".slide").css("width", "400px");
$("#slider").css("width", "400px");
$(".video-frame").css("width", "400px");
var width = 400;
};
if ($("#slider img").length < 2) {
$("#right, #left").css("display", "none");
};
if ($("iframe").length > 0 && $("iframe").length < 2) {
$(".options").css("width", "711px");
$(".slide").css("width", "711px");
$("#slider").css("width", "711px");
$(".video-frame").css("width", "711px");
$('.slide').hide();
var width = 711;
};
if ($(".slide img").css('width') > '400px' && $(".slide img").css('width') < '711px') {
$(".options").css("width", "600px");
$(".slide").css("width", "600px");
$("#slider").css("width", "600px");
$(".video-frame").css("width", "600px");
var width = 600;
};
}
$.ajaxSetup({
cache: false
});
$(".post-link").click(function(e) {
e.preventDefault()
var post_link = $(this).attr("href");
$("#single-post-container").html('<img id="loads" src="http://martinfjeld.com/wp-content/uploads/2015/09/Unknown.gif">');
$("#single-post-container").load(post_link, function(response, status, xhr) {
if (status == "error") {
var msg = "Sorry but there was an error: ";
$("#error").html(msg + xhr.status + " " + xhr.statusText);
} else {
$("#main-content").fadeIn(500);
$("body").addClass("opens");
yournewfunction();
}
});
requestCallback.requestComplete(true);
return false;
});
});
$(function() {
var form = $('#ajax-contact');
var formMessages = $('#form-messages');
$(form).submit(function(event) {
event.preventDefault();
var formData = $(form).serialize();
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
}).done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$('#name').val('');
$('#email').val('');
$('#message').val('');
}).fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
});
});
Though it's hard to follow exactly what is going on without being able to see the context of your HTML and without you giving us a more concrete description of exactly which line of code fails to execute, this is likely because one Ajax call is replacing a bunch of HTML which clobbers all your event handlers. So, when you then try to do the second Ajax operation, it's click handler is no longer in force so nothing happens.
Replacing a DOM element loses all event handlers that were attached to the original DOM element. Using .html() or assigning to .innerHTML replaces all the DOM elements within that element, thus losing all their event handlers.
The typical solution to this is to either reinstall the event handlers after replacing the content that you want event handlers on or use delegated event handling from a parent element that is not replaced.
Here are some references on delegated event handling:
JQuery Event Handlers - What's the "Best" method
jQuery .live() vs .on() method for adding a click event after loading dynamic html
Does jQuery.on() work for elements that are added after the event handler is created?
Should all jquery events be bound to $(document)?

Dynamically load image with different GET parameters

I'm trying to load an image (created with PHP) with jQuery and passing a few variables with it (for example: picture.php?user=1&type=2&color=64). That's the easy part.
The hard part is that I've a dropdown which enables me to select background (the type parameter) and I'll have an input for example to select a color.
Here're the problems I'm facing:
If a dropdown/input hasn't been touched, I want to leave it out of the URL.
If a dropdown/input has been touched, I want to include it in the url. (This won't work by just adding a variable "&type=2" to the pre-existing string as if I touch the dropdown/input several times they'll stack (&type=2&type=2&type=3)).
When adding a variable ("&type=2" - see the code below) to the pre-existing URL, the &-sign disappears (it becomes like this: "signature.php?user=1type=2").
Here's the code for the jQuery:
<script>
var url = "signatureload.php?user=<?php echo $_SESSION['sess_id']; ?>";
$(document).ready(function() {
window.setTimeout(LoadSignature, 1500);
});
$("#signature_type").change(function() {
url += "&type="+$(this).val();
LoadSignature();
});
function LoadSignature()
{
$("#loadingsignature").css("display", "block");
$('#loadsignature').delay(4750).load(url, function() {
$("#loadingsignature").css("display", "none");
});
}
</script>
Here's the code where I load the image:
<div id="loadsignature">
<div id="loadingsignature" style="display: block;"><img src="img/loading-black.gif" alt="Loading.."></div>
</div>
I don't know how more further I could explain my problem. If you have any doubts or need more code, please let me know.
Thank you for your help!
EDIT:
Here's the current code:
<script>
var url = "signatureload.php?user=<?php echo $_SESSION['sess_id']; ?>";
$(document).ready(function() {
window.setTimeout(LoadSignature, 1500);
});
$("#signature_type").change(function() {
url = updateQueryStringParameter(url, 'type', $(this).val());
LoadSignature();
});
function LoadSignature()
{
$("#loadingsignature").css("display", "block");
$('#loadsignature').delay(4750).load(url, function() {
$("#loadingsignature").css("display", "none");
});
}
function updateQueryStringParameter(uri, key, value)
{
var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i"),
separator = uri.indexOf('?') !== -1 ? "&" : "?",
returnUri = '';
if (uri.match(re))
{
returnUri = uri.replace(re, '$1' + key + "=" + value + '$2');
}
else
{
returnUri = uri + separator + key + "=" + value;
}
return returnUri;
}
</script>
EDIT2:
Here's the code for signatureload.php
<?php
$url = "signature.php?";
$count = 0;
foreach($_GET as $key => $value)
{
if($count > 0) $url .= "&";
$url .= "{$key}={$value}";
}
echo "<img src='{$url}'></img>";
?>
If I understood your question correctly, it comes down to finding a proper way of modifying GET parameters of the current URI using JavaScript/jQuery, right? As all the problems you point out come from changing the type parameter's value.
This is not trivial as it may seem though, there are even JavaScript plugins for this job. You could use a function like this and in your signature_type change event listener,
function updateQueryStringParameter(uri, key, value) {
var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i"),
separator = uri.indexOf('?') !== -1 ? "&" : "?",
returnUri = '';
if (uri.match(re)) {
returnUri = uri.replace(re, '$1' + key + "=" + value + '$2');
} else {
returnUri = uri + separator + key + "=" + value;
}
return returnUri;
}
$('#signature_type').change(function () {
// Update the type param using said function
url = updateQueryStringParameter(url, 'type', $(this).val());
LoadSignature();
});
Here is a variant where all the data is keept in a separate javascript array
<script>
var baseurl = "signatureload.php?user=<?php echo $_SESSION['sess_id']; ?>";
var urlparams = {};
$(document).ready(function() {
window.setTimeout(LoadSignature, 1500);
});
$("#signature_type").change(function() {
urlparams['type'] = $(this).val();
LoadSignature();
});
function LoadSignature()
{
var gurl = baseurl; // there is always a ? so don't care about that.
for (key in urlparams) {
gurl += '&' + encodeURIComponent(key) + '=' + encodeURIComponent(urlparams[key]);
}
$("#loadingsignature").css("display", "block");
$('#loadsignature').delay(4750).load(gurl, function() {
$("#loadingsignature").css("display", "none");
});
}
</script>
With this color or any other parameter could be added with urlparams['color'] = $(this).val();
Why don't you try storing your selected value in a variable, and then using AJAX post data and load image. That way you ensure there is only one variable, not repeating ones. Here's example
var type= 'default_value';
$("#signature_type").change(function() {
type = $(this).val();
});
then using ajax call it like this (you could do this in your "change" event function):
$.ajax({
type: 'GET',
url: 'signatureload.php',
data: {
user: <?php echo $_SESSION['sess_id']; ?>,
type: type,
... put other variables here ...
},
success: function(answer){
//load image to div here
}
});
Maybe something like this:
<script>
var baseUrl = "signatureload.php?user=<?php echo $_SESSION['sess_id']; ?>";
$(document).ready(function() {
window.setTimeout(function(){
LoadSignature(baseUrl);
}, 1500);
});
$("#signature_type").change(function() {
var urlWithSelectedType = baseUrl + "&type="+$(this).val();
LoadSignature(urlWithSelectedType);
});
function LoadSignature(urlToLoad)
{
$("#loadingsignature").css("display", "block");
$('#loadsignature').delay(4750).load(urlToLoad, function() {
$("#loadingsignature").css("display", "none");
});
}
</script>

I have an ajax call firing twice (jQuery) and have tried the solutions found here and nothing has worked

My ajax call goes and enters a record into a database (it's the first part of a form recording data) so I need it to return the id from the database entry.
Problem is, it's firing twice, so it's making 2 database entries each time.
I tried using a $count and while($count>0) in my php code to make sure that wasn't looping - and I didn't think it was, so the problem lies in my jQuery.
I tried putting the preventDefault on my submit button click function and that didn't work either.
Here's my code:
$(document).ready(function(){
$('#wpgstep1').one('click',function(){
// validate form fields are all filled in
var budget=$('#budget').val();
if(budget=='')
{
$('#budgeterror').show();
}
var yellowpages=$('#ads-yellowpages').val();
var flyers=$('#ads-flyers').val();
var brochures=$('#ads-brochures').val();
var radiotv=$('#ads-radiotv').val();
var none=$('#ads-none').val();
var other=$('ads-other').val();
var otherstatement=$('ads-other-statement').val();
var cust_id=$('#cust_id').val();
if(other !='')
{
if(otherstatement==='')
{
$('#adsothererror').show();
}
}
else
{
otherin='0';
}
if(yellowpages==="on")
{
yellowpagesin='1';
}
else{
yellowpagesin='0';
}
if(flyers==="on")
{
flyersin='1';
}
else
{
flyersin='0';
}
if(brochures==="on")
{
brochuresin='1'
}
else
{
brochuresin='0';
}
if(radiotv==="on")
{
radiotvin='1';
}
else
{
radiotvin='0';
}
if(none==="on")
{
nonein='1'
}
else
{
nonein='0';
}
var dataString='cust_id=' + cust_id + '&step=1&budget=' + budget + '&yellowpages='+yellowpagesin + '&flyers=' + flyersin + '&brochures=' + brochuresin + '&radiotv='+ radiotvin + '&none='+ nonein + '&other=' + otherstatement;
$.ajax({
type: "POST",
url: "submitwpg.php",
data: dataString,
dataType:'json',
success: function(data)
{
alert(data);
var i="";
var p=eval (data);
for (i in p)
{
$('#wpgpart2').append('<input type=hidden name=wpgid value=' + p[i] + '>');
}
$('#wpgform1').hide();
$('#wpgform2').show();
}
});
return false;
});
});
Make a global var
var form_submitting = false;
Above your ajax call
if(form_submitting == false){
form_submitting = true;
//your ajax call
}
In your success function of your ajax call
form_submitting = false;
if your submit button is inside of a form, it may be possible that your ajax function is executing and then your form is posting regularly. You could try turning your
<input type='submit' />
into
<button type='button' onclick='validateAndAjaxFunction(); return false;'></button>

How do you modify the id attribute of current selector from inside of a jQuery dialog button section?

I want to replace username string in id of "indirect" class with username specified by users in jquery dialog input field.Problem is i cant use this.id = this.id.replace('username', myvalue) coz $this will refer to the input element inside of jquery dialog ui.... Please help me to sort this out by any other method
<img src="images/AOL_button.png" id='http://openid.aol.com/username' class="indirect" />
<img src="images/google_button.png" id='https://www.username.google.com/accounts/o8/id' class="direct"/>
================================================================================
$(.indirect).click(function(){
$("#dialog").dialog({
buttons: {
"OK": function() {
if($('#username').val() == '') {
$('#username').focus();
} else {
var myvalue= $("#username").val();
var provider_url_post= // replace "username" in google id with myvalue
alert(provider_url_post);
})
You've got a bunch of syntax errors in your JS, but assuming those don't exist in your actual code:
$('.indirect').click(function() {
var self = this;
$("#dialog").dialog({
buttons: {
"OK": function() {
if (!$('#username').val()) { // just check the truthiness
$('#username').focus();
} else {
var myvalue = $("#username").val();
self.id = self.id.replace('username', myvalue);
}
}
}
});
});​

Categories