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()
Related
I'm working on a profile page that auto-populates email field, would like to get text value and then use it as variable on PHP.
To get the text value, using jquery:
jQuery(document).ready(function(){
var str = jQuery(".user_email").text();
});
Is there a way to echo variable "str"?
Thanks in advance.
You can't do that on the same page since php is executed on the server while javascript runs from the browser. However, where is the auto populate value coming from ?
If it is from a DB or an external API resouce (e.g in json or xml) then you can directly assign that to a php variable without passing it through javascript
log it to the browser javascript console
console.log('str', str);
how to display the console varys amongst browsers
EDIT ok... apparently this wasn't what the OP wanted at all..
probably wants to jQuery.ajax('/url', {str:str}); to send the value to the server.
My question: if these values are on the page.. where did they come from... did they not originate server-side/php ?
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 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 reading a rss feed with php and creating html DOM from the same. Now I have a bunch of <li>'s with news feed. when a user clicks on a particular <li> I want to post certain data to another php file which performs some other function.
How I want the data is tricky. I have a URL for all the feed elements. When a user clicks on a particular feed, I need to retrieve the URL associated with that particular feed.
I want to run a $.click() function in which I am going to $.post to the next php script.
How do I get that URL without storing it in the HTML itself. I do not want to store the URL in the html document for security puposes.
I am new with PHP.
You will need to assign unique id (uid) to each list element that corresponds to the url. A good way of handling this would be a database. You send the list item's identifier, look up in the database the associated url, perform some magic, and send the response back to the client. You can use jQuery's data method that leverages the html5 data attribute to store the information. Here is the basic pseudocode.
html
<li class="feed" data-uid="12345">Go</li>
javascript
$('li.feed').click( function() {
$.post({ id: $(this).data('uid') }, function(data) {
//do something with data
});
});
php
$uid = $_POST['uid'];
//db lookup of url
//do something with url
//return data to page
you could encrypt the url being sent from the server and then decrypt when it's sent back from the client. Just use a simple salt encryption method. I assume you're going to use ajax or the like to post back from the client to the server in which case, this methodology would work for you.
alternatively, you could create an array and store the urls in a collection with an associative key that you send to the client, then look up the url on the server side by that key. You could also implement a database solution to do this same thing where the key is the ID in the db.
U have to encode the variable url...
PHP
var url = ...;
JavaScript
$(function (){ var d1 = <?php echo json_encode(array($url)); ?>;});
I'd like to ask you how can i dinamically get a username from ldap. As you can see below, i entered the username 'smith2'
$_SERVER["REMOTE_USER"] = 'smith2';
$param = $_SERVER["REMOTE_USER"]
And I can get his first name, like this:
$ldap1 = new ldapl;
$fname=$ldap1->getFname($param);
This is useful because I have some forms with some fields which are filled by default (name, first name, etc).
It must be dynamic. Each person has a PC, so the person Y should see his name, first name, etc The person X his name, first name, etc.
But i don't know how to get the username dinamically. Can you explain it to me?
Thanks
You can request the username via an AJAX call:
var remote_user = '';
$.get('path/to/server-side.php', function (response) {
remote_user = response;
/*you can populate your forms with information returned from your PHP script*/
});
This code will request information from a PHP script. Your PHP script could just output $_SERVER['REMOTE_USER'] and that will be the response variable in the AJAX callback.
A good way to communicate between PHP script and JavaScript is to use the PHP function json_encode() to output your server response. Then use the jQuery method $.getJSON() which will automatically parse the response into a JavaScript object that can be iterated through.
Documentation for $.get(): http://api.jquery.com/jquery.get
Documentation for json_encode(): http://www.php.net/json_encode