I am using a autocomplete
http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/
And below i have two pages index.php and ajx_page.php
index.php
<form name="send_coup_ajx_form" id="send_coup_ajx_form" method="post">
<select name="member_type" id="member_type">
<option value="customer_type">Customer</option>
<option value="BPartner_type">Business Partner</option>
</select>
<input type="text" name="sel_rad" id="resultant_text" />
<input type="submit" name="submit" value="go" />
</form>
<script type="text/javascript">
$(document).ready(function(){
$("#resultant_text").autocomplete("ajx_page.php", {
width: 260,
matchContains: true,
//mustMatch: true,
//minChars: 0,
//multiple: true,
//highlight: false,
//multipleSeparator: ",",
selectFirst: false
});
});
</script>
And below code for
ajx_page.php
<?php
$select_type = $_GET['member_type'];
$type = $_GET['sel_rad'];
?>
when i type in the textbox, it gives me an error as
Notice: Undefined index: member_type in ajx_page.php on line 2
That means member_type is not going in that page..
And when i comment all this code and put the below code in ajx_page.php
<?php
echo "Name1\n";
echo "Name2\n";
echo "Name3\n"
?>
It displaying autocomplete feature list. but when i want to get the value of that object member_type it is saying an error..
so how do i pass additional values using this autocomplete plugin
I have added an Image to overwriting problem to #veeTrain
I'm not sure if the autocomplete plugin is intended to handle this type of scenario or not.
However, if you want to manually pass these values into your php script, then it would be pretty simple (at least in this scenario where you are only trying to send two fields in).
var memberType = $("#member_type>option:selected").val();
var selRad = $("#resultant_text").val();
$("#resultant_text").autocomplete("ajx_page.php?member_type="+memberType+"&sel_rad="+selRad, {
//...
But this probably isn't the answer answer you're looking for.
Update: I'm glad that syntax for sending the values is working for you.
It looks like you have overlapping ids being printed out -- is that what you mean by 'bold'? Apparently you aren't using the correct delimiter for creating a second auto-complete suggestion. I'm not sure what the autocomplete handler is wanting to delineate between items. Undefined is probably showing up because one of your items couldn't be found. You should use your browser's Developer Tools to debug what is getting sent.
Also, if you wanted the option's text rather than the value then you'll need to access the .text() rather than the .val() of the select drop down.
Update: This post might have something to say about what autocomplete is expecting.
I think to pass in additional parameter for bassistance's autocomplete, the only way is to modify the autocomplete.js file. I did something similar before, but the method is quite hardcoding. Posted below for your reference (it's around line 376):
$.ajax({
// try to leverage ajaxQueue plugin to abort previous requests
mode: "abort",
// limit abortion to this input
port: "autocomplete" + input.name,
dataType: options.dataType,
url: options.url,
data: $.extend({
member_type: ($("#member_type").length != 1)?$("#member_type").val():-1,
q: lastWord(term),
limit: options.max
}, extraParams),
success: function(data) {
var parsed = options.parse && options.parse(data) || parse(data);
cache.add(term, parsed);
success(term, parsed);
}
});
I only added one line to the original code, at line 10: member_type: ....
Take note that I pass in "-1" if the object is not found on that page to prevent javascript error.
Hope it helps!
Related
I have some jQuery/HTML where I accept a single item of user input (text) and want to pass it to PHP, to be stored for later use in a session variable. I've looked at many pages on this type of action, and found the closest accepted answer to what I think I need is the one here Set Session variable using javascript . The following code is broadly based on that, but it seems that the ajax is doing nothing. I've got console.logs all the way through, and at each possible path through the ajax statement (done, fail and always) but none show up. The console log shows:
(document).ready
Take new list name from input
ListA1
passName: ListA1
:
Object {listNamePOST: "ListA1"}
passName function end
returned from passName()
about to echo $_SESSION['listName'] :
end
Which misses out 6. success or 6. fail and 7. always. And the line console.log(< ?php echo $_SESSION['listName'] ?>); doesn't even show a blank line.
Where am I going wrong, please?
Here is test.php
<?php session_start(); ?>
<form method="post" name="newlistform">
<label for="list_name">Input:</label>
<input style="position: relative; " name="list_name" type="text" required />
<span class="button" id="makeIt">Go</span>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script>
/* ƒ: Pass listName out to SESSION variable */
function passName ( listName ) {
console.log('4. passName: ', listName);
var params = {listNamePOST: listName};
console.log("5. :");
console.log(params);
jQuery.ajax({
url: "storesession.php",
type: "POST",
data: params,
dataType : "json",
success: function(data, textStatus, xhr) {
console.log("6. success");
console.log(data);
},
error: function(xhr, textStatus, errorThrown) {
console.log("6. fail");
}
});
console.log('8. passName function end');
}
$(document).ready(function () {
console.log('1. (document).ready');
$( '#makeIt.button' ).click(function () {
console.log('2. Take new list name from input');
var listName = $( 'input[name=list_name]' ).val();
console.log('3.', listName);
passName ( listName );
console.log('9. returned from passName()');
console.log("10. about to echo $_SESSION['listName'] :");
console.log(<?php echo $_SESSION['listName'] ?>);
console.log('12. end');
});
})
</script>
and here is storesession.php
<?php
$_SESSION['listName'] = $_POST['listNamePOST'];
?>
(I'll sanitize the user input later.)
Edit: Just removed 'test.php' at the end of each of the console log lines. I copied them in inadvertently.
2nd edit: For information - This code is an extract of a larger php file which includes another $.ajax call, to get some data from a MySQL db, and that is working.
3rd edit: Changed 'done:' back to 'success:', 'fail:' back to 'error:' and removed 'always:'. This now adds 6. success as the last line, so #FrancescoMM and #Kevin put me right, though I don't understand why it didn't work when I had that originally.
As '6. success' appears at the end of the log, I'm going to try async: false and report back:-
OK, that fixed the sequence problem, but the console log statement between log statements 10. and 12. still does not appear. No 'undefined' or even a blank line.
So the problem is now reduced to getting listName into a session variable.
4th edit: Now solved. When I moved the session_start statement from test.php to storesession.php and found it didn't work, I moved it back, but not as the very first statement. I since found http://www.yourhowto.net/how-to-check-and-create-php-session-variables/ so moved the statement to the very beginning, and now the user data is being passed across to the session variable and shows up correctly at the end of the log between 10. and 12.
If it's really your complete storesession.php, you are missing session_start() in it.
Are you returning data in json format from the AJAX call? I had a similar problem and it was because of the data type, lose the dataType : "json" unless you are actually returning json, and see if that helps.
Ok, so I've gotten most of this thing done.. Now comes, for me, the hard part. This is untreaded territory for me.
How do I update my mysql database, with form data, without having the page refresh? I presume you use AJAX and\or Jquery to do this- but I don't quite grasp the examples being given.
Can anybody please tell me how to perform this task within this context?
So this is my form:
<form name="checklist" id="checklist" class="checklist">
<?php // Loop through query results
while($row = mysql_fetch_array($result))
{
$entry = $row['Entry'];
$CID = $row['CID'];
$checked =$row['Checked'];
// echo $CID;
echo "<input type=\"text\" value=\"$entry\" name=\"textfield$CID;\" id=\"textfield$CID;\" onchange=\"showUser(this.value)\" />";
echo "<input type=\"checkbox\" value=\"\" name=\"checkbox$CID;\" id=\"checkbox$CID;\" value=\"$checked\"".(($checked == '1')? ' checked="checked"' : '')." />";
echo "<br>";
}
?>
<div id="dynamicInput"></div>
<input type="submit" id="checklistSubmit" name="checklistSubmit" class="checklist-submit"> <input type="button" id="CompleteAll" name="CompleteAll" value="Check All" onclick="javascript:checkAll('checklist', true);"><input type="button" id="UncheckAll" name="UncheckAll" value="Uncheck All" onclick="javascript:checkAll('checklist', false);">
<input type="button" value="Add another text input" onClick="addInput('dynamicInput');"></form>
It is populated from the database based on the users session_id, however if the user wants to create a new list item (or is a new visitor period) he can click the button "Add another text input" and a new form element will generate.
All updates to the database need to be done through AJAX\JQUERY and not through a post which will refresh the page.
I really need help on this one. Getting my head around this kind of... Updating method kind of hurts!
Thanks.
You will need to catch the click of the button. And make sure you stop propagation.
$('checklistSubmit').click(function(e) {
$(e).stopPropagation();
$.post({
url: 'checklist.php'
data: $('#checklist').serialize(),
dataType: 'html'
success: function(data, status, jqXHR) {
$('div.successmessage').html(data);
//your success callback function
}
error: function() {
//your error callback function
}
});
});
That's just something I worked up off the top of my head. Should give you the basic idea. I'd be happy to elaborate more if need be.
Check out jQuery's documentation of $.post for all the nitty gritty details.
http://api.jquery.com/jQuery.post/
Edit:
I changed it to use jquery's serialize method. Forgot about it originally.
More Elaboration:
Basically when the submit button is clicked it will call the function specified. You want to do a stop propagation so that the form will not submit by bubbling up the DOM and doing a normal submit.
The $.post is a shorthand version of $.ajax({ type: 'post'});
So all you do is specify the url you want to post to, pass the form data and in php it will come in just like any other request. So then you process the POST data, save your changes in the database or whatever else and send back JSON data as I have it specified. You could also send back HTML or XML. jQuery's documentation shows the possible datatypes.
In your success function will get back data as the first parameter. So whatever you specified as the data type coming back you simply use it how you need to. So let's say you wanted to return some html as a success message. All you would need to do is take the data in the success function and place it where you wanted to in the DOM with .append() or something like that.
Clear as mud?
You need two scripts here: one that runs the AJAX (better to use a framework, jQuery is one of the easiest for me) and a PHP script that gets the Post data and does the database update.
I'm not going to give you a full source (because this is not the place for that), but a guide. In jQuery you can do something like this:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() { // DOM is ready
$("form#checklist").submit(function(evt) {
evt.preventDefault(); // Avoid the "submit" to work, we'll do this manually
var data = new Array();
var dynamicInputs = $("input,select", $(this)); // All inputs and selects in the scope of "$(this)" (the form)
dynamicInputs.each(function() {
// Here "$(this)" is every input and select
var object_name = $(this).attr('name');
var object_value = $(this).attr('value');
data[object_name] = object_value; // Add to an associative array
});
// Now data is fully populated, now we can send it to the PHP
// Documentation: http://api.jquery.com/jQuery.post/
$.post("http://localhost/script.php", data, function(response) {
alert('The PHP returned: ' + response);
});
});
});
</script>
Then take the values from $_POST in PHP (or any other webserver scripting engine) and do your thing to update the DB. Change the URL and the data array to your needs.
Remember that data can be like this: { input1 : value1, input2 : value2 } and the PHP will get something like $_POST['input1'] = value1 and $_POST['input2'] = value2.
This is how i post form data using jquery
$.ajax({
url: 'http://example.com',
type: 'GET',
data: $('#checklist').serialize(),
cache: false,
}).done(function (response) {
/* It worked */
}).fail(function () {
/* It didnt worked */
});
Hope this helps, let me know how you get on!
Sorry in advance everyone for this question as I know the cascading select boxes has been done to death but I can't seem to find any good help. I've tried various things but it all seems to fail and I'm not understanding why.
Here's the jquery I have currently:
function tester() {
$("select#type").attr('disabled', 'disabled');
$("select#cat").change(function(){
var vid = $("select#cat option:selected").attr('value');
var request = $.ajax({
url: "show_type.php",
type: "POST",
data: {id : vid}
});
request.done(function(msg) {
$("#result").html( msg );
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
});
}
Don't mind the first section of the code with the select#type and select#cat as these are for what I was trying to get the code to populate at first, however the .change is my trigger for the .ajax request. The rest of the code I'm merely trying to dump a simple return message into an empty div#result upon a successful ajax request.
I ran a test, and the var vid populates correctly.
Here's the simple PHP file I'm trying to call with the ajax:
<?php
$requ;
if (isset($_POST['id'])) {
$requ = 'Worked';
} else {
$requ = "didn't work";
}
echo $requ;
?>
I thought perhaps the problem was the id wasn't being passed properly so I altered the PHP script to give me any valid output regardless of whether the $_POST was set or not.
I won't post the HTML as I'm just trying to dump this all into a div while I test it. When I run the script I get the 'Request Failed' error message with a message of "error".
Here is the other jquery & PHP I have also tried, using the .post instead of the .ajax:
function tester() {
$("select#type").attr('disabled', 'disabled');
$("select#cat").change(function(){
$("select#type").html("<option>wait...</option>");
var vid = $("select#cat option:selected").attr('value');
$.post("show_type.php", {id:vid}, function(data){
$("#result").empty().append(data);
}, "json");
});
}
And the PHP to accompany this particular jquery:
$requ = $_POST['id'];
$ret = 'You selected: ' . $requ;
echo json_encode($ret);
Again, it all failed. I also tried the above code without using the json encoding/parameters. All I want to do is a simple (so I would think) cascading select dropboxes. The second box to be dependent of the first boxes selection. I'm beginning to think that this all just may not be worth it and just sticking strictly to PHP with links to resubmit the page with a GET and populate a new section or div with the results of the first click. Any help or suggestions you might have would be greatly appreciated, I've spent 2 solid days trying to figure this all out. Thanks in advance
Alright, I got it fixed. Thanks to Mian_Khurram_ljaz for making me take a different look at the hierarchical structure of the file. I was assuming that since the js was calling the php file, by placing the php file in the same folder as the js, I could call the php by using the url: show_type.php but that was actually wrong. The structure is considered from the actual page invoking the js and php, and therefore the url should have been js/show_type.php since I had the show_type.php file in my js folder.
It's always the little mistakes that take you days to figure. For those in the future looking to find decent code for cascading select drop boxes, here is my functioning and fully expanded code (which also includes a tri-level cascade)
jQuery:
function project() {
$("select#model2").attr('disabled', 'disabled');
$("select#brand2").attr('disabled', 'disabled');
$("select#project").change(function(){
$("select#model2").attr('disabled', 'disabled'); // if changed after last element has been selected, will reset last boxes choice to default
$("select#model2").html('<option selected="selected">Choose...</option>');
$("select#brand2").html("<option>Please wait...</option>");
var pid = $("select#project option:selected").attr('value');
$.post("handler/project.php", {id:pid}, function(data){
$("select#brand2").removeAttr("disabled");
$("select#brand2").html(data);
});
});
$("select#brand2").change(function(){
$("select#model2").html("<option>Please wait...</option>");
var bid = $("select#brand2 option:selected").attr('value');
var pid = $("select#project option:selected").attr('value');
$.post("handler/projBrand.php", {proj: pid, bran: bid}, function(data){
$("select#model2").removeAttr("disabled");
$("select#model2").html(data);
});
});
}
Just call the function in the $(document).ready of your js.
Notice the comment, having this 'redundant' call to disable and force the last box to select the default is just in case the user makes a selection in all 3 boxes but goes back to the first box and changes the selection.
Here is the php handler file:
<?php
include_once('../includes/file.inc');
$request = $opt -> getModelvBrand();
echo $request;
?>
The other handler file for the jQuery is nearly exactly the same, only invoking a different method in the class file.
And lastly, the HTML:
<form action="" method="post">
<select id="project">
<option value="0">Choose...</option>
<?php echo $opt -> getProject();?> //populates first box on page load
</select>
<select id="brand2">
<option value="0">Choose...</option>
</select>
<select id="model2">
<option value="0">Choose...</option>
</select>
<br /><br />
<input class="like-button" type="submit" title="Submit" value="" />
</form>
Thanks again Mian for making me take a different look at my file(s).
Hope this code helps someone else in the near future.
I have a simple checkbox on a page that allows a user to say if they'd like to receive email notifications. I am using jquery for this to call some php code when the checkbox changes. However, I am not having much luck even calling the jquery function (clicking the checkbox does nothing) let alone test the backend functionality.
Any help in pointing out the error would be great. Thanks.
The checkbox HTML:
<input id="notify_checkbox" type="checkbox" value="y" name="notify">
The jquery:
$('#notify_checkbox').change(function(){
if($('#notify_checkbox').attr('checked'))
{
$.post("/update_notify", { checked: "y", email: "<?php echo $this->session->userdata('email');?>" });
$( "#notifyresult" ).html( "<p>Awesome, we'll send you an email!</p>" );
}
else
{
$.post("/update_notify", { checked: "n", email: "<?php echo $this->session->userdata('email');?>" });
$( "#notifyresult" ).html( "<p>Okay, we won't email you.</p>" );
}
});
And finally the PHP:
function update_notify()
{
// Passed through AJAX
$notify = $_POST[checked];
$email = $_POST[email];
$this->load->model('musers');
$query = $this->musers->update_user_notify($email, $notify);
}
RESOLUTION: The comments below were helpful but not the ultimate solution. The solution was to add the following around my code.
$(document).ready(function() {
{);
Why not use .click() instead?
JSFIDDLE
Also, as you can see in my JSFiddle example, use .is(':checked') instead of attr('checked').
edit after #Rocket commented on your post:
You should indeed quote your $_POST values in your php! Didn't notice it myself, credits to rocket
What's the name of your controller? You need to put that in the URL.
$.post("/controller/update_notify", ...
The problem is with the redefinition of the attr function in jQuery 1.6, and with the difference between attributes and properties.
With attributes (retrieved with attr), the value of checked="checked" or its absence stays the same, regardless of whether the element is actually checked or not.
With properties (retrieved with prop as of jQuery 1.6), the actual state of the element is found. This is equivalent to checking the checked property of the element (which is preferable because you don't need to do a new jQuery selection). The best soltion would be as follows:
if (this.checked) {
See jsFiddles showing this:
your current solution
using prop
using this.checked
This is a very simple form that I have found on the web (as I am a jQuery beginner).
<!-- this is my jquery -->
<script>
$(document).ready(function(){
$("form#submit_wall").submit(function() {
var message_wall = $('#message_wall').attr('value');
var id = $('#id').attr('value');
$.ajax({
type: "POST",
url: "index.php?leht=pildid",
data:"message_wall="+ message_wall + "&id="+ id,
cache: false,
success: function(){
$("ul#wall").prepend(""+message_wall+"", ""+id+"");
$("ul#wall li:first").fadeIn();
alert("Thank you for your comment!");
}
});
return false;
});
});
</script>
<!-- this is my HTML+PHP -->
some PHP ...
while($row_pilt = mysql_fetch_assoc($select_pilt)){
print
<form id="submit_wall">
<label for="message_wall">Share your message on the Wall</label>
<input type="text" id="message_wall" />
<input type="hidden" id="id" value="'.(int)$row_pilt['id'].'">
<button type="submit">Post to wall</button>
</form>
and down below is my PHP script that
writes to mySQL.
It is a pretty straight forward script. However, it is getting little complicated when I submit it. Since I have more than one form on my page (per WHILE PHP LOOP), thus when I submit - only the FIRST form gets submitted. Furthermore, any other subsequent forms that I submit - data is being copied from the first form.
Is there any jQuery functions that clear the data? - or is there a better solution.
Thanks,
Nick
It's because you're giving each form the same id, and thus it is submitting the first element it finds with that id, i.e. the first form. What you should do is assign a unique id to each form, and then give each form an AJAX submit function that submits the form-specific data. You can use jQuery's $.each() function to loop through all the forms and $(this).attr('id') within the submit function to retrieve the form-specific id.
UPDATE: As revealed by the comment on this answer, you actually don't need the each() function because jQuery applies it to every form element anyway.
Here would be an example script:
$(document).ready(function(){
$("form").submit(function() {
var message_wall = $(this).children('input[type="text"]').attr('value');
var id = $(this).children('input[type="hidden"]').attr('value');
$.ajax({
type: "POST",
url: "index.php?leht=pildid",
data:"message_wall="+ message_wall + "&id="+ id,
cache: false,
success: function(){
$("ul#wall").prepend(""+message_wall+"", ""+id+"");
$("ul#wall li:first").fadeIn();
alert("Thank you for your comment!");
}
});
return false;
});
});
Because we can't see all of your forms, I'm not entirely sure, but given your question I'm going to assume that the other forms all share the same id (form#submit_wall), which is invalid an id must be unique within the document.
Given that you're going to change the id of the other forms (I'd suggest using a class name of, probably, 'submit_wall', but the specifics are up to you), the jQuery needs to be changed, too. From:
$("form#submit_wall").submit(function() {
To:
$("form.submit_wall").submit(function() { // using the class-name instead of the id.
Now, of course, you run into the same problems of duplicate ids.
So I'd suggest, again, changing the id to a class and changing:
var message_wall = $('#message_wall').attr('value');
var id = $('#id').attr('value');
to:
var message_wall = $(this).find('.#message_wall').attr('value');
var id = $(this).find('.id').attr('value');
Given the mess that you've posted, above, I find it hard to believe that this is all you need. It would definitely be worth posting the full page (or a demo at JS Fiddle or JS Bin) that fully reproduces your code.