I have started using jQuery few days ago, and although I found information on how to solve any problems that I have encountered (or at least get it working by some workarounds), I seem to be stuck on the current issue:
I have a form that has a variable number of fields - the number of fields may change depending on user input at any point, and I achieved that using AJAX; Since I want to preserve the information user entered every time form is regenerated, I post data from the form fields and use it to repopulate newly generated fields every time the number of fields is changed; This all works (although I know I am doing it not the right way, more on it further).
What I need to do is use the values from form fields for another AJAX call to generate another table on the page; I use the following code to acquire the field values for the first AJAX call, it is generated by php and spans from jq_calc11 to jq_calc99 (depending on number of fields). I understand that this is probably not the correct way, yet I could not figure out how to post a two-dimensional array using jQuery.
$('#ts_addfields').change(function()
{
var comp_select=$('#ts_addfields').val();
var jq_calc11=$('#tb_calc11').val();
var jq_calc21=$('#tb_calc21').val();
var jq_calc31=$('#tb_calc31').val();
var jq_calc41=$('#tb_calc41').val();
var jq_calc51=$('#tb_calc51').val();
var jq_calc61=$('#tb_calc61').val();
var jq_calc71=$('#tb_calc71').val();
var jq_calc81=$('#tb_calc81').val();
$('#calculator_input').load('/elements/AJAX-addfields.php',{addFields: comp_select, pCalc11:jq_calc11, pCalc21:jq_calc21, pCalc31:jq_calc31, pCalc41:jq_calc41, pCalc51:jq_calc51, pCalc61:jq_calc61, pCalc71:jq_calc71, pCalc81:jq_calc81});
});
My question now is, how can I re-use the values of these variables for a different AJAX call? I don't think having another potential 99 lines to be generated via php for another function is a good idea, so I looked into possibility of placing these values in a seperate function, and call it from inside the $('#ts_addfields').change(function() or another function.
I've tried various variations of the following, yet I cannot find a way how to run the function that would read the variables;
jQuery.fn.calcVars = function(){
var jq_calc11=$('#tb_calc11').val();
var jq_calc21=$('#tb_calc21').val();
var jq_calc31=$('#tb_calc31').val();
var jq_calc41=$('#tb_calc41').val();
var jq_calc51=$('#tb_calc51').val();
var jq_calc61=$('#tb_calc61').val();
var jq_calc71=$('#tb_calc71').val();
var jq_calc81=$('#tb_calc81').val();
};
$('#ts_addfields').change(function()
{
var comp_select=$('#ts_addfields').val();
$(this).calcVars();
$('#calculator_input').load('/elements/AJAX-addfields.php',{addFields: comp_select, pCalc11:jq_calc11, pCalc21:jq_calc21, pCalc31:jq_calc31, pCalc41:jq_calc41, pCalc51:jq_calc51, pCalc61:jq_calc61, pCalc71:jq_calc71, pCalc81:jq_calc81});
});
Any code I've tried returns "jq_calc*xx*" not defined error on firebug.
Could someone point me to the right direction?
Well, you could try this:
var str = $("form").serialize();
http://api.jquery.com/serialize/
Related
all my problem is that I wanna send data from my website to this website's page :
http://www.womo.com.au/external-review.php?id=MDAxMTcyNjcw
how I can do this ? and is it possible ? cuz as I have seen this website forms validation's all in javascript and dunno how to handle it ?
thanks.
This is how you can do that, just make a testPosting.html file,
Create your form using all the inputs that are required to send.
See the screenshot for the posted fields.
This data is posted when i submitted the form after filling it.
Now as you can see 14 fields are posted, so you need to make 13 inputs and 1 textarea.
use click function for the button of submit e.g
$('#buttonID').click(function(e){
e.PreventDefault();
//store values of inputs in a variable
var data = {
FirstName = $('#FirstName').val(); // you can more better then that if you know how
//Add the rest of the data
};
});
then you can use jQuery Ajax to send data.
$.ajax({
url: "http://www.womo.com.au/external-review.php?id=MDAxMTcyNjcw",
data:data, //this data will be the variable that you create in which all the forms inputs datas are stored.
type: "POST"
}).done(function(result) {
//do stuff if some result has returned
});
i just gave the rough idea.
Oh you must use this line in script on top of you JS scrips
jQuery.support.cors = true; // force cross-site scripting (as of jQuery 1.5)
My code is not perfect but you get the idea what i am trying to say, you might can start from here, and do stuff of your own..
I am trying to find the best method for passing a large array of IDs from one page to the next.
I've built a simple downloadable image site that allows users to select any number of images to download. Right now, when a user selects an image its ID is stored in a JSON string inside a cookie. The problem I've been having is finding the best way to pass the JSON to the review before downloading page.
Currently, I'm sending the JSON as a URL parameter but I'm not sure if this is the smartest solution since the number of IDs in the JSON could reach into the hundreds.
I've looked in PHP sessions but I don't really understand how can I enable the user ability to add/subtract from the variable once the page has been loaded.
$(function(){
$('.download_cart').click(function(){
var urlArray = [];
obj = JSON.parse(getCookie("downloads"));
if(obj != null){
if(obj.items.length !== 0){
$.each( obj.items, function( i, value ) {
urlArray.push(obj.items[i].id);
});
}
}
window.location = cart_url+'?array='+urlArray;
})
});
Try POSTing your data to the new PHP page:
var data = 'urlArray='+urlArray
$.ajax({
type: "POST",
url: 'new_php_page.php',
data: data
});
Now you'll be able to get your variable at $_POST['urlArray'] on your new page.
http://api.jquery.com/jQuery.post/
Consider to pass them in a set of ajax-requests, by 200 (for example, to not overflow input limit) IDs in each request.
Assign urlArray to a hidden field then submit the form, it can parse large no of array to another page
I've dealt with javascript in the past, but I'm trying to relearn it. For that reason I'd like to come up with a javascript solution without the use of libraries like JQuery.
I've come across several threads, and they have been close but not a perfect match to my situation.
I have a form generated dynamically by PHP, it grabs info from the database, and echoes out all the form inputs. They are all checkboxes representing the entry in the database. Normally I would use name="id[value]" where value is the id of the current entry being looped through.
So I would have something like this:
<input type="checkbox" name="del[1]"/>
<input type="checkbox" name="del[2]"/>
<input type="checkbox" name="del[3]"/>
When I would post this on form submit, I would just get the value of $_POST['del'] and call it a day. However, I'm trying to send it to a PHP page with an AJAX function so i can perform the functions without changing the page or refreshing.
My question is: How do I get all of the checkboxes(that are checked) and send them to the PHP page so it can understand which ones were checked. My understanding is that this will require some kind of conversion. My first though was to loop through each checked box, and grab its index (or give them all Ids and grab the id) and put it into a string that I could then explode PHP side.
Any thoughts? Thanks, sharf.
var i, child, str='', arr = Array(),
form = document.getElementById('form')
for(i=0; i<form.childNodes.length; i++) {
// grab the element
var child = form.childNodes[i];
// make sure it is an input and a checkbox
if(child.tagName!='INPUT' || child.getAttribute('type')!='checkbox') continue
// if the checkbox is checked, add the name and value to a url string
if(child.checked)
arr.push(child.getAttribute('name')+'='+encodeURIComponent(child.value))
}
}
// make the URL string
str = arr.join('&')
// now you can use this as a url:
SomeAjaxUrl + str
Then, in PHP:
<?php
$checked_options = $_REQUEST['del'];
print_r($checked_options);
?>
You can use jquery like you said and loop though
http://api.jquery.com/attribute-starts-with-selector/
But for ease i would look at something similar to backbone forms https://github.com/powmedia/backbone-forms
which manages your model for you and lets you send by ajax easily.
Their github has much more info on there along with some examples. This puts the checkboes in an array which you can handle php side easily
edit: pure javascript
var pairs = [];
var form = document.getelementbyid("form");
for ( var i = 0; i < form.elements.length; i++ ) {
var e = form.elements[i];
pairs.push(encodeURIComponent(e.name) + "=" + encodeURIComponent(e.value));
}
var output= pairs.join("&");
You should be able to modify that pretty easy
Use JSON.stringify()(MDN) to fix your problem.
You can convert an Array or an Object to a valid JSON Object which can be sent through AJAX.
I have a main page (topic.php) with GET information in the URL, like this:
http://studio.byuipt.net/topic.php?topic=Debugger&desc=Helps%20find%20and%20solve%20problems%20with%20others%27%20code.
I have a div, "currLeader" in topic.php into which I load another page, getCurrLeader.php. getCurrLeader.php is supposed to use the topic variable in the $_GET info of the url to do a mysql search and return the relevant info. The problem is that while, scripts on topic.php are able to successfully use extract($_GET), I am not able to retrieve any variables out of the getCurrLeader.php extract($_GET) statement. I thought both pages would be able to access the currently showing url. Is there another way I can get this information out of the current url?
(consequently, the "topic" info is actually present in an element with an id on the page, and I'm able to successfully retrieve it using jquery, but I can't figure out a way to then, within the same file, pass that value to my php script).
I'm not really sure I understand what you're asking. On first read I assumed you were trying to do this with jquery, but now I'm not so sure I'm on the same page at all. Here's an easy way to extract the parameters in javascript:
<script type="text/javascript">
var ourlocation = location.href;
var thisstuff = ourlocation.split("?");
var id = thisstuff[1];
var idary = id.split("&");
var param2 = idary[0];
var param3 = idary[1];
var param4 = idary[2];
</script>
Which probably has nothing to do with what you're trying to do.
On 2nd read it seems like you're trying to get the originating url in a php script, when another one loads first.
One way you could do that is use sessions. Either store the parameters you're trying to extract, and stuff them in a session to be retrieved by the other file, or you could actually just store the url itself, then pull it out and split it.
session_start();
$_SESSION['ourUrl'] = $_SERVER["REQUEST_URI"];
// do stuff on next page
unset($_SESSION['ourUrl']);
session_destroy();
If none of this makes sense feel free to explain further and we'll see if we can get you going. Hopefully this helps a little.
im trying to adapt this little snippet:
$("#checkbox_id").change(function(){
/* CODE HERE */
});
I have a series of checkboxes that are dynamically generated and their id's are always like "hug3443" were "hug" is the column in the DB and "3443" is the unique id for each row.
My objective would be that every time the checkbox changes state to update it own state in the DB.
Can it be accomplished with jQuery?
Thank you.
I just found a script for this stuff and thought to post it here as I was checking this page a while ago until I finally came across to this script. Tested it and worked like a charm and I have inserted it in my coding library. Enjoy, folks.
http://www.jooria.com/Tutorials/ajax-20/jquery-live-checkbox-inputs-with-animation-effects-158/
Yes. Use live events to attach the change event handler to your checkboxes (so that dynamically added checkboxes will be handled also). Then simply do a AJAX request inside the event handler passing your script the new state and the name/id of the checkbox (you can then "parse" the id and column name in the script).
Not without a server side script that would deal with the data changes.
jQuery is a client side javascript framework and doesn't have direct access to mysql, which is a server side daemon.
Have a look into pairing jQuery with php and mysql.
Code in javascript you write with the use of jQuery is executed on the client-side in a browser. A solution is from your script to make a call to a server page that will execute a MySQL update . For example like this.
$("#checkbox_id").change(function(){
$.ajax({
type: "POST",
url: "/page-that/makes/update.php",
data: {param1:value1}
});
});
You should write some server-side code for managing database (php, ruby, whatever).
You should create something like API, which means, that server-side script needs to get some variables, which sended to it from clients (id's of rows, name and value of columns for example).
And after that you should write your jQuery frontend script, which will request server-side script for managing database tables. For requests you can use AJAX technology, something like this:
$.ajax({
url: 'http://somesite.com/path/to/server/side/script',
type : 'POST',
success: function (data, textStatus) {
alert('yahoo! we get some data from server!' + data);
}
});
You can get the value of the id of the checkbox using javascript you can then split the name into the field name and id value. For this example I've added a - into id to give a seperator
(I think you may need to use the click event rather than change, think change may only work for drop down menus)
$("#checkbox_id").click(function(){
var checkbox_id = $(this).attr("id");
var id_bits = checkbox_id.split("-");
// this would split hug-3443 into hug and 3443 setting id_bits[0] = hug and id_bits[1] = 3443
$.post("update,php",
{
row: id_bits[0],
id: id_bits[1]
}
);
});