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.
Related
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 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/
I am trying to send values to an mysql database using ajax from a form. I am selecting the value by taking the parent article of the form and then taking the child element with id="email" as you can see here...
var email = $(this).parent("article").children("#email").val() //gets the user's email
However when I send the data onto the php file for uploading to the mysql database it seems to be doing something wrong, and instead of the value typed in being stored a function (shown below) is being stored... What is going on here!?
function (a) {var c,d,e,g=this[0];{if(!!arguments....
you can try find() method:
The .children() method differs from .find() in that .children() only travels a single level down the DOM tree while .find() can traverse down multiple levels to select descendant elements (grandchildren, etc.) as well.
var email = $(this).parent("article").find("#email").val()
Seems a bit confusing. You're using #email, which implies an id, of which you can only have one on the page. jQuery will recognize the hashtag and default to using the native "getElementById" browser method.
So this:
var email = $(this).parent("article").children("#email").val()
Can be converted to this:
var email = $("#email").val()
I am making a web form and I am validating the inputs via ajax. For every keypress on an input tag, the value is sent to a php file where its checked for numeric value etc. This was easy, I just have it echo back a error message response which is displayed.
On this same keypress, I also want it to check if ALL the input values are != "" so that the person can't leave an entry blank. I am trying to have it control whether or not the submit button works. This is where I get stuck.
Is there a way to send two things back in an ajax request? I tried using the php session object but it wouldn't work the way I wanted (since ajax isn't updating the entire page.)
Yes you can. Two options:
1 - quick and dirty - you could send a string back with the two items you need. You would need to concatenate the two items you need to send back into one string. Your onSuccess function would then split the string into the two items you want.
2 - elegant solution - you can create a JSON object in the server and send it back. A JSON string is something like foo = { "var1" : "response1" , "var2" : "response2" }. In your client-side script you would reference var1.response1 and var2.response2. See below one example using Mootools (a well-known javascript library) and PHP:
javascript code (client):
var params = "id=123&page=1&product=12"; //anything you need to pass to the server
var myRequest = new request.JSON({url:"url of your server script", onSuccess: function(result) {alert(result.response1); alert(result.response2);}).post(params);
PHP code (server):
$a["response1"] = response1; //first thing you need to pass back
$a["response2"] = response2; //second thing you need to pass back
echo json_encode($a); // this will convert $a array to a json string
I hope this helps. Good luck!
You should use json for this one.
$errors = array('Error1', 'Error2');
echo json_encode($errors);
You could attach an onsubmit handler to the form that returns a boolean for success/failure.
<script>
function myValidation(){
/*
Your AJAX validation call here.
*/
if(valid){
return true;
}else{
return false;
}
}
</script>
<form onsubmit="return myValidation();">
<input type="submit" name="submit" value="Submit" />
</form>
If the validation returns false, the form will not submit. A return of true allows the form to process as necessary.
Why aren't you doing this with straight jQuery? It seems ridiculous to make an ajax call to validate a form through PHP while the user is filling it out. Validate the data after submission with PHP, not during.
That is unless you need to match the input to something in the database, but it doesn't sound like that's the case here.
I'm trying to create an event handler (jQuery) that will pick all elements of specific class, each unique ID value, post json array, loop through php, finally update view.
I have no problem with selecting one instance.
**Mostly looking how to create the array of id,value to pass for processing.
Thank You
You can do something like this (As a strting point):
$('.class').each(function(){
// do somthing with $(this)
});
Of course, if you post some more details, I can expand on this.
To get an array of all selected elements
var elArray = $('.classToSelect').get();
After this you may use
$.each(elArray, function(el){
var id = el.id;
var value = el.value;
//code goes here
}
A small plugin script from http://code.google.com/p/jquery-json/ is perfect for JSON encoding and decoding:
var postdata = $.toJSON(elArray);
generates a well formatted JSON string.
This snippet will give you an array of the ids of the elements with class myclass:
var id_array = $.map($(".myclass"),function(el){return el.id;});
You can then send the array to your server as JSON, or as a comma separated string, or any other way you want.