How to open a new page with jQuery - php

//activate selected row in table
jQuery('.activatebutton').click(function(){
var tb = jQuery(this).attr('title');
//initialize to false as no selected row
var sel = false;
//get each checkbox in a table
var ch = jQuery('#'+tb).find('tbody input[type=checkbox]');
//check if there is/are selected row in table
ch.each(function(){
if(jQuery(this).is(':checked')) {
//set to true if there is/are selected row
sel = true;
jQuery(this).parents('tr').fadeOut(function(){
/*
THIS IS THE LINE THAT IS NOT WORKING BELOW!!!! I want to send VALUE ID to delete.php
*/
jQuery.get('delete.php', { id:this.id });
//remove row when animation is finished
jQuery(this).remove();
});
}
});

It's not clear exactly what attribute you want to send, but it looks like it's the element's id. If so, here's where the correction is:
jQuery.get('delete.php', { id:this.id });
should be
jQuery.get('delete.php', { id:jQuery(this).attr('id') });
So you'll send the id attribute of the element.
If that's still not working, you may have the incorrect path of the delete script...chrome dev tools or firebug would tell you this.

Related

Dropdown search from database, get images for different model/brand and display it

My problem is to display an image that is associated with the mysql results... Say the result has ID=250 and Name=brand.model, then I want a piece of code to search in a folder for an image with the name id_brand.model.jpg on the server.
Database structure is id, master, name. When user selects Brand + Model from dropdown it should get image from folder (could also get image from database, which one is better nowadays) and images all have unique name's what should be echoed as part name.
(Pictures to help understanding what i mean http://imgur.com/a/7XwVd )
Here's pastebin's to what i have coded yet.
http://pastebin.com/kQF2qP64
Any help is appreciated.
First you need to bind the change event of the select to send the name to a function to search the file, then append the file/s to the DOM:
Javascript (Ajax)
// Every time a category is selected we request the files
$('#category').on('change', function() {
// If we have an element with images loaded, lets delete it
var searchResult = $("#search-result").empty();
// Now we serialize the form data, add an id to the form
var searchBrand = $('#gender').find('option:selected').text();
var searchModel = $('#category').find('option:selected').text();
var fileName = searchBrand + '.' + searchModel + '.jpg';
var searchData = { filename: fileName }
// Now we create the ajax request with the form data
var request = $.getJSON('search_images.php', searchData);
// If the request success we show the images
request.done(function(data) {
// For each image found we add a new image to the DOM
$.each(data, function(index, image_uri) {
// First let's create the image element
var img = $("<img>", {
"class": "result-image",
"src": image_uri
});
// Then we append it to the DOM
searchResult.append( img );
});
});
// If the search fails, we notify that no results were found
request.fails(function() {
alert('No results found');
});
});
PHP (search_images.php)
<?
// Get the file name
$filename = $_GET['filename'];
// Find all the images
$images = glob("images/file/path/*_{$filename}");
// Return the images as json
echo json_encode($images);

Cannot Modify/Manipulate Dynamic Content From Ajax/JSON Response for A Dynamic PHP Form

I need a dynamic form which is supposed to work like this:
When user press "ADD" button, appear a new ..<.div> DOM to select a package.
Depending on the package, the row must change color (by adding/removing some classes).
But I can't get it working. Here is my HTML:
<button onclick='addDay();'>
<div class='content'>
</div>
My Javascript:
//FUNCTION 1: LOAD AJAX CONTENT
function addDay()
{
baseUrl = $('input#helper-base-url').val();
//Set caching to false
$.ajaxSetup ({
cache: true
});
//Set loading image and input, show loading bar
var ajaxLoad = "<div class='loading'><img src='"+baseUrl+"assets/images/loading.gif' alt='Loading...' /></div>";
var jsonUrl = baseUrl+"car/add_day/"+count;
$("div#loading").html(ajaxLoad);
$("div#content").hide();
$.getJSON(
jsonUrl,
{},
function(json)
{
temp = "";
if(json.success==true)
{
temp = json.content;
}
//Display the result
$("div#content").show();
$("div#content").html($("div#content").html()+temp);
$("div#loading").hide();
});
}
//FUNCTION 2: MODIFY AJAX CONTENT
$("#content").on("change", "select.switch", function (e) {
e.preventDefault();
//Get which row is to be changed in background's color
id = this.id;
id = id.substr(6);
//Add class "package1" which change row's background color
row = "row"+id;
row.addClass('package1');
});
My PHP
function add_day($count)
{
$temp = "<div class='row".$count."'>
<select id='switch".$count."' class='switch'>
<option value='1'>Package 1</option>
<option value='2'>Package 2</option>
</select>
</div>";
$result = array(
'success' => true,
'content' => $temp,
);
$json = json_encode($result);
echo $json;
}
PS. The form is not as simple as this but to make the problem solving easier, I remove the details. But I can't seem to change the class on the fly. Do we have a solution or a good work around here?
Edit 1:
Sorry I didn't make myself clear before. I had no problem with getting the id or variable (it was okay, when I alert it the right value comes out - but after I add the class, no color changes is seen). I run it:
a. On button click, load Ajax content.
b. Ajax content (which results contains a ) loaded successfully.
c. FAIL: On change, add class "package1" to the div row. (So, I had no problem with getting the right id or class name. When I alert the variables it gives the right result, BUT the color doesn't change. I can't check whether class is successfully added or not.)
$("#content").on("change", "select.switch", function (e) {
e.preventDefault();
$('.row' + $(this).attr('id').replace('switch', '')).addClass('package1');
});
Assuming that everything else is ok
//Get which row is to be changed in background's color
id = this.id;
id = id.substr(6);
//Add class "package1" which change row's background color
row = "row"+id;
row.addClass('package1');
This is the problem. To get the attibute id you have to do
var id = $(this).attr('id').substr(6);
You have to use $(this) and not this by the way to use all of jQuery functionalities.
Same below
$(row).addClass('package1');
So, full code:
//Get which row is to be changed in background's color
var id = $(this).attr('id').substr(6);
//Add class "package1" which change row's background color
$('.row'+id).addClass('package1');
Changing the class to id solved the problem (using #row0 instead of .row0). Sorry and thank you for your time :)

How to find the cell index when rowspans are involved

I am working on a scheduling project and have run into an issue with finding the column index of a selected cell (so that i may then get the appropriate header for the column). The issue comes into play when a previous cell(or cells) have/has a rowspan. In which case the cell index is off by that amount of cells. I have been at this since yesterday. My current attempt involves using a solution I found in previous posts, and this is this:
parentTr.find('>td, >th').each(function(i,o) {
if ( this == reference )
{
cellNum = i;
var counter = columnNum;
while ( counter-- )
{
$(this).closest('tr').next().find('>td,>th').each(function(i,o)
{
if ( cellNum == i )
{
$(this).addClass('rowspan-affected');
$(this).attr('colNum', columnNum);
}
});
}
}
});
})
The problem is that this solution counts the number of rowspanned cells on the entire page. I need a count of the rowspanned cells for only the current clicked cell, and then be able to add that count to index so I can get the proper header. What I have been trying looks like this:
var $this = $(this);
//get the row header contents
var row = $this.parent('tr').contents('th:eq(0)').html();
//trying this
var colCount = $(this).prevAll().find('td').parent('tr').attr('rowspan');
alert (colCount);
//used to get the cell index
var rowIndex = $(this).parent().index('.main tbody tr');
var tdIndex = $(this).index('.main tbody tr:eq('+rowIndex+') td');
//alert ("tdindex " + (tdIndex+1));
var headerObj = $(this).parents('.main').find('th').eq(tdIndex+1);
//strip whitespace before passing
var toPass = $.trim(headerObj.text());
//toPass = $.trim(toPass)
//alert (toPass);
This information is gathered and then passed to a new form with the selected information used to populate the form.
If anyone can help me with this, I would be greatly appreciative!!!

Checking change in form field before executing AJAX

I have a form on my view page.. whenever form populate on the page ..it is filled with old values ... I mean input box and check-box have old values ... and then I am posting form through ajax..after posting if values successfully saved into database I am showing the message that information updated successfully or vice versa...so the problem is now that if for example user do not change anything,the form values are same in the text-boxes then when user pressed save button i don't want to show him that information has updated as he didn't do anything .. I want to ask if that possible in java script ...or should i have to query into the database and check that whether values are same or not? and the other thing that if it can be possible that button remains disable until he do some changes in any of the form field...
I am not writing the whole code just the javascript part
$("#submit").click(function(e){
e.preventDefault();
var name = $('#name').val();
var email = $('#email').val();
var password = $('#password-check').val();
var oldpassword = $('#oldpassword').val();
var timezone = $('#UserinfoTimezone').val();
var alternate_email = $('#alternate_email').val();
//var newsletter = $('#newsletter').val();
var form_data = {
name: $('#name').val(),
email: $('#email').val(),
password: $('#password-check').val(),
oldpassword: $('#oldpassword').val(),
timezone: $('#UserinfoTimezone').val(),
alternate_email: $('#alternate_email').val(),
};
$.ajax({
type:"POST",
data:form_data,
url:"https:/localhost/settings/",
success : function(data) {
alert("successfully data saved"):
}
});
You can save the values while you would have populated the fields in the form... Otherwise you can use a flag variable which can be given a value in .change() function of each field and that value can be checked on submit of the form.. But I guess the first option will be more efficient as the flag will be set even if the user edits the field and enters the same value again...
You can save the old values in the JavaScript and compare them against the current values in the submit handler. If nothing changed, don't POST.
And yes, you can also have the save button disabled initially and attach onChange handlers to the form fields that enable the save button when the contents of those fields change.
On ajax submit copy input values to some attribute, so you know last sent data.
$('#form input').each(function() {
$(this).data('last-ajax-value', $(this).val());
});
When invoking second ajax submit you can check if these values match and make some decision.
var someValueDiffers = false;
$('#form input').each(function() {
if($(this).data('last-ajax-value') != $(this).val())
someValueDiffers = true;
});
if(someValueDiffers)
// Form changed
else
// Form is the same
On the page load you can get all the input element values and hold them in seperate global variables. When you submit the form check the current input values with old one that you have saved. If any one is not equal, user has changed the form and you can submit it.
var init_name = "";
var submit_flag = false;
$(document).ready( function () {
var init_name = $('#name').val();
$("#submit").click(function(e){
var name = $('#name').val();
if(name == init_name) {
// user has not changed
submit_flag = false;
} else {
submit_flag = true;
}
if(submit_flag) {
// call the ajax
}
})
})
One simple way to achieve that. Diseable the submit button. Eneable it if a change is made on the page.
After submit the ajax values you need to clear the input field values.
Place this code instead of your success:
...
success: function(data){
alert("successfully data saved"):
$('#myformid').find('input:text, input:password, input:file, select, textarea').val('');
$('#myformid').find('input:radio, input:checkbox')
.removeAttr('checked').removeAttr('selected');
}
You can unset the input values when page gets loaded.
$(document).ready(function(){
$("input").each(function(){
$(this).val() = '';
});
});

Click HTML table data and insert into text area

I have a HTML table with text in the cells like so:
<tr><td>HELLO</td></tr>
I then have a text area like so:
<input type="text" id="txt_message" name="txt_message"
I want to make it so that when you click inside the table cell, the data (in this case the word 'HELLO') is inserted into the text area (so the user does not have to type it).
I dont know if this is possible, but I am guessing it is and it is 'probably' something in JavaScript.
If anybody has any advice that would be great, Thank you :)
[Working demo]
var textbox = document.getElementById('textbox');
var table = document.getElementById('table');
// add one event handler to the table
table.onclick = function (e) {
// normalize event
e = e || window.event;
// find out which element was clicked
var el = e.target || e.srcElement;
// check if it's a table cell
if (el.nodeName.toUpperCase() == "TD") {
// append it's content to the textbox
textbox.value += (el.textContent || el.innerText);
}
}​
Note: all the conditional assignments with || are for cross-browser compatibility.
Here is Working demo using jquery.
To get the value, use innerhtml and a span, more here: http://www.vbforums.com/showthread.php?t=339864
To update the textarea you should be able to do something like: document.getElementById ("text_message").value = x;
a simple jQuery snippet, assuming you have 1 textarea and multiple td's to click over
(function() {
var ta = $('#txt_message');
$('td').bind('click.addtextarea', function() {
var text = $(this).html();
ta.val([ta.val(), text].join(' ')); /* this add words */
/* ta.val(text); this print one word */
});
})()

Categories