Passing HTML INPUT field ID to PHP completion program in jQuery Autocomplete - php

I want to pass the id of the INPUT field to the PHP file providing options. Here's my HTML & jQuery code. But the PHP program gets the id as undefined. Thanks for helping.
jQuery :
$('.classfield').autocomplete({
//define callback to format results
source: function(req, add){
//pass request to server
$.getJSON("ajax/ajax_suggestions.php?id="+$(this).attr('id')+"&callback=?", req, function(data) {
//create array for response objects
var suggestions = [];
//process response
$.each(data, function(i, val){
suggestions.push(val.name);
});
//pass array to callback
add(suggestions);
});
},
//define select handler
change: function(e) {
$("#spill").html("change "+$(this).val()+e.type);
}
}); // autocomplete
HTML:
<input type="text" class="classfield" id="hello" value="there"></input><br>

the value of $(this).attr('id') is undefined because this is the object that is put in the parameter of autocomplete (the parameter of autocomplete accepts an object, so if you use $(this).attr('id'), you are referencing the object that was passed in the parameter on the autocomplete)
therefore you cannot use $(this).attr('id').
You have to store the id of the text field, may be as a global variable... Hope this helps a little bit

Try getting the id from this.element:
//pass request to server
$.getJSON("ajax/ajax_suggestions.php?id="+this.element.attr('id')+"&callback=?", req, function(data) {
Also see this example.

Related

Using $.each in AJAX Success Callback

I have the following console.log(data):
[{"optionPropertyID":"287","optionID":"106","optionBedrooms":"2","optionSleeps":"1","optionDescription":"1"},{"optionPropertyID":"287","optionID":"105","optionBedrooms":"2","optionSleeps":"1","optionDescription":"1"}]
I am trying to use this data in a $.each function inside my AJAX success callback but it continually errors out on me:
success:function(data){
alert(data);
console.log(data);
$.each(data, function(){
alert("ID: " + this.optionID);
});
},
I receive the following error:
Uncaught TypeError: Cannot use 'in' operator ...
In doing some research on the error I need to use $.getJSON ? But I am using an $.ajax call to get this data in the first place ... little confused ..
I just want to iterate through this returned data and create fields for each piece of data.
input type="text" value="'+this.optionID+'"
Im just trying to alert the data back currently to ensure it is looping through.
You need to add the option:
dataType: "json",
to the $.ajax call. This tells it to parse the JSON automatically.
Alternatively, the server script could use
header("Content-type: application/json");
Because it is raw text. data in callback is always raw text when received.
You must make Object from it to use with $.each. You can do this with jQuery.parseJSON()
success:function(data){
var dataObject = $.parseJSON(data);
$.each(dataObject, function(){
alert("ID: " + this.optionID);
});
},
if your returning an object in other way around please try below code. this works for me. hopes this help.
success : function (data) {
$.each(data, function( index, value ) {
var sampleId = value.optionPropertyID;
...
});
}

jquery : pass an array in ajax

I have a form with several identical fields:
<input type="text" id="qte" value="" name="qte[]">
How transmetre the array in my file processing?
I noticed that the array sent ajax became a string.
$("#form_commande").submit(function(event){
var qte = $("#qte").val();
if(qte== '')
{
$('#qte_message').html("KO QTE");
}
else
{
$.ajax({
type : "POST",
url: $(this).attr('action'),
data: $(this).serialize(),
success : function(){
$('#form_commande').html('<p>OK</p>');
},
error: function(){
$('#form_commande').html("<p>KO</p>");
}
});
}
return false;
}
Get value in jquery like:
$("#form_commande").submit(function(event){
var qte_array = new Array();
$('input[name="qte[]"]').each(function(){
qte_array.push($(this).val());
});
if(qte_array.length== 0)
{
$('#qte_message').html("KO QTE");
}
else
{
$.ajax({
type : "POST",
url: $(this).attr('action'),
data: {qte:qte_array},
success : function(){
$('#form_commande').html('<p>OK</p>');
},
error: function(){
$('#form_commande').html("<p>KO</p>");
}
});
}
});
and get it in php like:
$qte = $_POST["qte"];
here qte an array
This returns the input textbox object:
$("#qte");
This returns the value of the input textbox object:
$("#qte").val();
Remember you asked for DOM object by id, and this by definition returns only one.
Please read this topic:
JQuery - Reading an array of form values and displaying it?
In short you should iterate with tag name="qte[]" instead of using ids. In DOM you cannot have two different objects with different ids.
var qte_array = new Array();
$('input[name="qte[]"]').each(function(){
qte_array.push($(this).val());
});
After this you have all the values of qte[] array in one object - qte_array. You can later serialize this array to JSON and then pass it as a string.
ALTHOUGH - you shouldn't need to do all those things. You can send ajax request directly with your form, all those data in these inputs will be transferred anyway. You just need to handle them correctly server-side.
id is unique, you can't have more fields with the same ID.
By the way you should convert values to JSON and pass them to Ajax

Pass a variable from a get query in javascript

I am trying to pass the value of a parameter outside a $.get jQuery in javascript. I read that I should somehow do that in synchronous mode but I couldn't find a solution.
Here is my code:
var flag;
var t = $.get("mutalyzer.php?id="+variation.value, function(data) {
flag=data;
});
document.write(flag);
where I get undefined as a result.
Thanks!
write it inside the callback function
try this
var t = $.get("mutalyzer.php?id="+variation.value, function(data) {
//this is the callback function and runs when get gets completed
flag=data;
document.write(flag);
});

Fetch input value from certain class and send with jquery

<input id="u1" class="username">
<input id="u2" class="username">
<input id="u3" class="username">
...
How to fetch input value with "username" class and send with ajax jquery to php page.
i want to recive data like simple array or simple json. (i need INPUT values and not ids)
var inputValues = [];
$('input.username').each(function() { inputValues.push($(this).val()); });
// Do whatever you want with the inputValues array
I find it best to use jQuery's built in serialize method. It sends the form data just like a normal for submit would. You simply give jQuery the id of your form and it takes care of the rest. You can even grab the forms action if you would like.
$.ajax({
url: "test.php",
type: "POST",
data: $("#your-form").serialize(),
success: function(data){
//alert response from server
alert(data);
}
});
var values = new Array();
$('.username').each(function(){
values.push( $(this).val());
});

How to pick up JSON in PHP from Jeditable Script

I want to create a jeditable text area that posts the values entered in to a database and then returns the new value to the div that replaces the textarea. I found this on Stackoverflow that handles returning the new value to the div.
$(document).ready(function() {
$('.edit_area').editable(submitEdit, {
indicator : "Saving...",
tooltip : "Click to edit...",
type : "textarea",
submit : "OK",
cancel : "Cancel",
name : "Editable.FieldName",
id : "elementid",
});
function submitEdit(value, settings)
{
var edits = new Object();
var origvalue = this.revert;
var textbox = this;
var result = value;
edits[settings.name] = [value];
var returned = $.ajax({
url: "http://jimmymorris.co.uk/xmas/record_xmas_msg.php",
type: "POST",
data : edits,
dataType : "json",
complete : function (xhr, textStatus)
{
var response = $.secureEvalJSON(xhr.responseText);
if (response.Message != "")
{
alert(Message);
}
}
});
return(result);
}
});
My problems is I don't know what my POST vars are called so I can insert in to my db. Does it even return POST var to php or does it send php json and how do I know what that is called?
Please help, Cheers in advance.
What it sends to the server depends on what you supply to the "post" mamber of the $.ajax options paremeter.
If you pass a query string parementer data : "name=foo&surname=bar" The PHP script would recieve it in the $_POST variable and could be accessed by means of $_POST['name'] $_POST['surname']
However if you passed an object to the data parameter it would be changed to a query string i.e
data : {name : 'foo', surname : 'bar'},
JQuery.ajax would change it into a query string like the example above then It would be sent to the server, and the PHP script would also access it same as mentioned above.
P.S I highly recommend using some type of encoding when sending data to the server, encodeURIComponent(variable) and accordingly decode it in PHP by using urldecode.
You have the id posted which you can retrieve in the PHP page as $_POST['id']. The text is posted as value which you can retrieve in the PHP page as $_POST['value']. You can of course change the default names.

Categories