My project is in PHP / MySQL. I'm using Smarty for a template engine.
I have a < select > tag in my smarty file:
maps.tpl -
<script src="http://code.jquery.com/jquery-1.5.js"></script>
<form method="post" action="maps.php">
<td colspan="3">
<select id="cmdview" name="cmd">
<option value=""></option>
<option value="commdata" {if $cmdOn == "commdata"}selected="true"{/if}>Communications</option>
<option value="contacts" {if $cmdOn == "contacts"}selected="true"{/if}>Contacts</option>
<option value="enrollment" {if $cmdOn == "enrollment"}selected="true"{/if}>Enrollment</option>
<option value="all" {if $cmdOn == "all"}selected="true"{/if}>All Schools</option>
</select>
<input type="submit" name="doSwitch" value="Submit" />
</td>
<div id="append"></div2>
</form>
So far, my jQuery code finds which value is selected:
{literal}
<script>
$('#cmdview').change(function() {
//alert('Handler for .change() called.');
var str = "";
url = "maps_append.php";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$('#append').text(str);
})
.change();
</script>
{/literal}
I need the jQuery to listen for the value of "cmdview" then post that value to file: maps_append.php . I need that file to .append/.change the current file (maps.php/maps.tpl) without reloading.
But, my jQuery is only half working. The jQuery does find the value I'm trying to pass, and I've gotten it to load that correct value in the <.d.i.v.> tag with id #append . The only thing I can't seem to do is that take value and actually post it to maps_append.php
Any help will be very appreciated!
Thank you!
PS: I think the change will be something like this:
This needs to be replaced:
$('#append').text(str);
})
.change();
With something like this:
url = "maps_append.php";
$.post( url, { cmd: cmdview, value: str } ,
function( data ) {
var content = $( data );
$( "#result" ).append( content );
}
);
$term_input.val('');
});
EDIT::
My current file is maps.php. I now have it appending maps_append.php to maps.php with this code:
<script>
$('#cmdview').change(function() {
//alert('Handler for .change() called.');
var str = "";
url = "maps_append.php";
url = "maps_append.php";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$('#append').load(url);
})
.change();
</script>
I just need to post the value of the select tag now!
Closer still... please see this edit:
<script>
$('#cmdview').change(function() {
//alert('Handler for .change() called.');
var str = "";
url = "maps_append.php";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$.post( url, { str: "$cmdOn" } ,
function( data ) {
var content = $( data );
$('#append').load(url);
})
.change();
});
</script>
Now the maps_append.php page only appends to maps.php when I change the value of the select tag. I only need to include the value of the select tag when maps_append.php appears now.
I don't quite understand the details of what you are doing here -- all the code looks fine but the plan seems a little strange.
Typically you don't have a program change the source. Instead you would have code store data in a database and the code would be driven by the database to produce different output.
Maybe this is what you want to do with the content -- store it in a database and have a page that displays it.
To load content via jQuery use the following
function loadContent(elementSelector, sourceUrl) {
$(""+elementSelector+"").load("http://yoursite.com/"+sourceURL+"");
}
See this link: http://frinity.blogspot.com/2008/06/load-remote-content-into-div-element.html
Related
I have a problem whit my dropdown list,
I need to change location page when option selected using value option attribute, but the first option element not functional,
This is the html code:
<form>
<select class='language-select' name='URL' id='URL'>
<option value="index.php?lan=EN" selected> English</option>
<option value="index.php?lan=FR">Français</option>
</select>
</form>
and this is the Js function:
$('#URL').on('change', function(event){
event.preventDefault();
event.stopPropagation();
var $this = $(this);
window.location.href = $(this).val();
alert($(this).val());
});
also there an error ' uncaught exception: out of memory'
One thing, when i add an empty option element it works well, i can toggle bettwen two links: index.php?lan=FR and /index.php?lan=EN
Thanks
Your html marks the first option as selected no matter what. So, for example, when the French page is loaded, your dropdown still says "English". Instead, what you need to do is detect on page load which option should be selected. You can use a function like this:
function GetURLParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}
And your markup would be:
<form>
<select class='language-select' name='URL' id='URL'>
<option id="EN" value="index.php?lan=EN"> English</option>
<option id="FR" value="index.php?lan=FR">Français</option>
</select>
</form>
Finally, in your jQuery on ready function, you would have:
$(function() {
var lan = GetURLParameter('lan');
$('#' + lan).prop('selected', true);
});
Hope it helps!
In my HTML page i have 2 select.
When i change the value into the first select the second select must be change is option value.
Error in console :
Uncaught ReferenceError: Invalid left-hand side in assignment
If i add console.log(result) i see the object in console.
JS code
<script type="text/javascript">
function changeoption() {
$.getJSON('users.php', {nameUser:$('#nameUser').val()}, function(result) {
var select = $('#email');
var options = select.attr('options');
$('option', select).remove();
$.each(result, function(index, array) {
$('option', select) = new Option(array['email']); // the line error
});
});
}
$(document).ready(function() {
changeoption();
$('#userName').change(function() {
changeoption();
});
});
</script>
PHP code
<?php
$result = array();
if(isset($_GET['userName'])) {
$query = $dbh->prepare("SELECT email FROM tbl_users WHERE username = ? ORDER BY userId");
$query->execute(array($_GET['userName']));
$result = $query->fetchAll(PDO::FETCH_ASSOC);
}
echo json_encode($result);
?>
HTML code
<form>
<!-- first select populated by another query inside this page-->
<select name="userName" id="userName">
<option>Name1</option>
<option>Name2</option>
<option>Name3</option>
</select>
<!-- second select -->
<select name="email" id="email">
</select>
</form>
You're trying to assign to a jQuery object. Try creating the new option a different way.
instead of
$('option', select) = new Option(array['email']);
try
$('<option />', {
html: array['email'],
value: array['email']
}).appendTo('#email');
JSFiddle
You might use string append:
$('<option value="new">newOption</option>').appendTo("#email");
$('<option value="'+array['email']'+">'+array['email']+'</option>')
.appendTo("#email");
If you are a more php than jquery guy
you can put the select in a div
<div id='selecthtml'>
<select name="username" id="username">
<option>Name1</option>
<option>Name2</option>
<option>Name3</option>
</select>
</div>
then instead of getjson just use $.get
var url = "users.php?username"+$("#username").val();
$.get( url, function( data ) {
$( "selecthtml" ).html( data );
});
and of course your php users.php should return an html select (not json)
like this
<select name="username" id="username">
<option>New name 1</option>
<option>new name 2</option>
</select>
$('option', select) = new Option(array['email']); // the line error
In this line the $(...) is a function. You may be so used to using jQuery that you have lost sight of this. You cannot perform $(...) = ...; just like you cannot perform alert() = ...;
Change:
$('option', select).remove();
$.each(result, function(index, array) {
$('option', select) = new Option(array['email']); // the line error
});
});
to:
$(select).html('');
$.each(result, function(index, array) {
$(select).append(new Option(array['email']);
}
Im trying to trigger an asynchronous JSON request when I select an option from an HTML selector box using mootools.
I have the following form element:
<form method="post" id="sel">
<select id = "_selecor_id" size=3>
<option value = "value_a" id = "option_a">OptionA</option>
<option value = "value_b" id = "option_b">OptionB</option>
</select>
<p id="response"></p>
</form>
I'm using the following javascriipt/mootools to send a JSON request carrying the form info
window.addEvent('domready', function()
{
$('_selecor_id').addEvent('click', function(){
new Request.JSON({
url: "my_php_script.php",
onSuccess: function(response)
{
$('response').set('html', response.params)
}
}).get($('sel'));
})
});
to the following php script
$result['params'] = $_GET;
echo json_encode($result);
However, I'm told in Chrome's developer tools 'cannot read property "params" of null'
I don't see why request should be 'null' here.
Any ideas would be greatly appreciated
Hey man the answer to your question is in the question itself.
Your triggering the event when you are clicking on the select when like you said "select an option"
Click on the select would be wrong, however so would click on an option with in the select what your looking for is the onChange event the code would be as follows:
HTML
// Notice no form tag needed unless you are serializing other items
<select id = "_selecor_id" size=3>
<option value = "value_a" id = "option_a">OptionA</option>
<option value = "value_b" id = "option_b">OptionB</option>
</select>
<p id="response"></p>
JAVASCRIPT
window.addEvent('domready', function(){
$('_selecor_id').addEvent('change', function(){
new Request.JSON({ // This must return a valid json object
url: "my_php_script.php",
data: {
'value': this.get('value')
}
onSuccess: function(responseJSON, responseText){
$('response').set('html',responseJSON.params);
}
}).send();
})
});
PHP
$result['params'] = isset($_GET['value']) ? $_GET['value'] : 'Not Set';
echo json_encode($result);
The responseJson variable will now contain something like {"params":"value_b"}
Try this code:
window.addEvent('domready', function(){
$('_selecor_id').addEvent('click', function(){
new Request.JSON({
url: "my_php_script.php",
onSuccess: function(response){
$('response').set('html',(response || this.response || this.responseText || {params: ''}).params)
}
}).get($('sel'));
})
});
I got a page with a form to fill it with custormers info. I got previous custormers data stored in a php array. With a dropdownlist users can fill the form with my stored data.
what i have is a jquery function that triggers when the value changes and inside that function i whould like to update the form values with my stored data (in my php array).
Problem is that i dont know how to pass my php array to the jquery function, any idea ??
this is how i fill the array:
$contador_acompanantes = 0;
foreach ($acompanantes->Persona as $acomp)
{
$numero = $acomp->Numero;
$apellidos = $acomp->Apellidos;
$nombre = $acomp->Nombre;
$ACOMPANANTES[$contador_acompanantes] = $ficha_acomp;
$contador_acompanantes++;
}
got my select object:
<select name="acompanante_anterior" id="acompanante_anterior">
<option value="1" selected>Acompañante</option>
<option value="2">acompanante1</option>
<option value="2">acompanante2</option>
</select>
and this is my code for the jquery function (it is in the same .php page)
<script type="text/javascript">
$(document).ready(function()
{
$('#acompanante_anterior').on('change', function()
{
});
});
</script>
var arrayFromPHP = <?php echo json_encode($phpArray); ?>;
$.each(arrayFromPHP, function (i, elem) {
// do your stuff
});
You'll likely want to use json_encode, embed the JSON in the page, and parse it with JSON-js. Using this method, you should be aware of escaping </script>, quotes, and other entities. Also, standard security concerns apply. Demo here: http://jsfiddle.net/imsky/fjEgj/
HTML:
<select><option>---</option><option>Hello</option><option>World</option></select>
<script type="text/javascript">
var encoded_json_from_php = '{"Hello":[1,2,3], "World":[4,5,6]}';
var json = JSON.parse(encoded_json_from_php);
</script>
jQuery:
$(function() {
$("select").change(function() {
$(this).unbind("change");
var val = json[$(this).val()];
var select = $(this);
$(this).empty();
$.each(val, function(i, v) {
select.append("<option>" + v + "</option>");
});
});
});
try this one..
<script type="text/javascript">
$(document).ready(function()
{
$('#acompanante_anterior').on('change', function()
{
my_array = new Array();
<?php foreach($array as $key->val)?>
my_array['<?php echo $key?>'] = '<?php echo $val;?>';
<?php endif; ?>
});
});
</script>
I'm learning how to apply ajax to my jquery/php/mysql script for the purpose of callback firing. This question is probably from my ignorance when it come to the name of this term.
The Question: Is there a way to reset ajax callback without reloading the page script.
The Goal: I have a mysql query displaying on jQuery Accordian 1, 2, and 3. The goal is to click a query result href from Accordian and display the results in jQuery UI Tab 3 without a page reload...So far the script fires on my first callback but it doesn't fire a second time. Is there a term or jquery command that will reset jquery/ajax?
index.php
<?php
...script... include'right.content.php';
?>
<script type="text/javascript" >
$(function() {
$("#submit").click(function(){ // when submitted
var name = $('#string2').val();
var lname = $('#string3').val(); // // POST name to php
$('#stage').load('test.arena/test.php', {'string2':name, 'string3':lname,} );
});
$( "#tabs" ).tabs().find( ".ui-tabs-nav" );
$( "#accordion" ).accordion();
});
</script>
index.php - html section
<div id="stage">
<?php include'test.arena/test.php';?>
</div>
right.content.php
while ($row = mysql_fetch_array($result)){
if($row['stats'] == "1"){
$data .= "<tr><td colspan='2'>".$row['order_number']."</td>
<td colspan='2'>
<input type='hidden' id='string3' value='".$row['details']."'>
<input type='hidden' id='string2' value='".$row['order_number']."'>
<input type='button' id='submit' value='View'></td>
<td>info</td></tr>";
test.arena/test.php
if(!isset($_POST['string2'])){
$_POST['string2'] = "";
}else{
$string3 = "PO Number:" .$_POST['string3'];
$string2 = "Order:" .$_POST['string2'];
echo $string3 ."</br>";
echo $string2 ."</br>";
}
Is the element with ID 'submit' inside the one with ID 'stage'? If so, try changing $("#submit").click(function(){ to $("#submit").live('click', function(){.
The problem is probably because your submit button is inside of the 'stage' div. This means that when you load the new 'stage' content, it will delete the old button and add a new one and the new one won't have any click thing attached.
The quick fix for this is to use a 'live' handler.
$(function() {
$("#submit").live('click', function(){ // when submitted
var name = $('#string2').val();
var lname = $('#string3').val(); // // POST name to php
$('#stage').load('test.arena/test.php', {'string2':name, 'string3':lname,} );
});
$( "#tabs" ).tabs().find( ".ui-tabs-nav" );
$( "#accordion" ).accordion();
});
But the other solution, which might make the problem clearer, is to re-add the click handler after the load finishes.
$(function() {
function submitClicked() {
var name = $('#string2').val();
var lname = $('#string3').val(); // // POST name to php
$('#stage').load(
'test.arena/test.php',
{ 'string2':name, 'string3':lname },
function() {
addClickHandler();
}
); // display results from test.php into #stage
}
function addClickHandler() {
$('#submit').click(submitClicked);
}
addClickHandler();
$( "#tabs" ).tabs().find( ".ui-tabs-nav" );
$( "#accordion" ).accordion();
});