I have two input fields (user-name and lguser) and i want to send all field values to php page, i can just send user-name value. Please help
<script>
// AJAX call for autocomplete
$(document).ready(function(){
$("#user-name").keyup(function(){
$.ajax({
type: "POST",
url: "myphppage.php",
data:'keyword='+$(this).val(),
beforeSend: function(){
$("#user-name").css("background","#FFF url(../assets/media/image/loadings.gif) no-repeat 165px");
},
success: function(data){
$("#suggesstion-box").show();
$("#suggesstion-box").html(data);
$("#user-name").css("background","#FFF");
}
});
});
});
//To select country name
function selectCountry(val) {
$("#user-name").val(val);
$("#suggesstion-box").hide();
}
</script>
<input type="text" class="form-control" id="user-name" name="user-name" >
<input type="hidden" value="lguser" id="lguser">
Please try
data:'keyword='+$(this).val()+'&lguser='+$('#lguser').val(),
Here you use data:'keyword='+$(this).val()
here (this) get value form ** $("#user-name").keyup(function(){**
means get value only user-name
You can grab the values of both inputs and store them in an object. Then assign that object as the data property of the $.ajax(). jQuery will send that data as JSON, which you'll have to deserialize on the PHP side.
$.ajax({
data: {
keyword: $('#user-name').val(),
lguser: $('#lguser').val(),
}
})
Alternatively, put your inputs in a <form> element and use jquery.serialize() to serialize all inputs into a query string, with the name property of each element as key.
const formData = $('#the-form').serialize()
$.ajax({
data: {
url: `myphppage.php?${formData}`
}
})
you can send data in ajax request like this
data: {'username': $('#user-name'.val()), 'userid': $('#lguser').val()}
Related
How to post an AJAX Request when a hidden input value change ?.
The value in hidden input is always change because of Jquery autocomplete.
I tried $("#id_pt_asal").change(function(event){ but nothing post on console log.
is there any way how to do it ?
Here the HTML
<input type="hidden" name="id_pt_asal" id="id_pt_asal" value="" />
Here the AJAX script
$(document).ready(function() {
$("#id_pt_asal").change(function(event) {
var formData = {
'id_pt_asal': $('input[name=id_pt_asal]').val()
};
$.ajax({
type: 'POST',
url: '<?=base_url()?>akademik/prodi_pindah',
data: formData,
dataType: 'json',
encode: true
})
.done(function(data) {
console.log(data);
if (data.hasil_prodi == true) {
$("#id_prodi_asal").html(data.html);
}
})
event.preventDefault();
});
});
First thing you need to get element of Jquery autocomplete. I assume your jquery autocomplete input given id is txt
$(document).ready(function(){
$("#txt").on("keypress",function(){
//$("#id_pt_asal").val($(this).val());
$("#id_pt_asal").trigger('change');
});
$("#id_pt_asal").on("change",function(event){
console.log(event);
//ajax call
});
});
I have a form with several form inputs with the following definition:
<input type="text" name="aname" id="aname" class="form-control dataaccess" data-field="GID" />
<input type="text" name="sname" id="sname" class="form-control dataaccess" data-field="LID" />
Then i have an ajax function whose success function returns a resultset from the controller to display in the page. This is my code
$.ajax({
type: "POST",
url: "controller/method",
data: "id="+data,
success: function(data){
$(".dataaccess").each(function(){
var field=data[0].($(this).data("field"));
$("#"+$(this).attr("id")).val(field);
});
});
However, my resultset is not getting concatenated with the fieldname i get from the respective input data-field attribute. Where am i getting it wrong? Thank you
Data returned by data:
[{"ID":"GR02","Name":"Admins","Valid":"30","Block":"No ","Descr":"Description"}]
For dynamic properties, you shouldn't use property accessor(.), you can use as index notation
$.ajax({
type: "POST",
url: "controller/method",
data: "id="+data,
success: function(data){
$(".dataaccess").each(function(){
var self = this;
var field=data[0][$(self).data("field")];
$("#"+$(self).attr("id")).val(field);
});
});
Define a reference to this as self outside the ajax call, so this can be available when ajax executes.
Try this :
success: function(data){
$(".dataaccess").each(function(){
var field=data[0].($(this).data("field"));
console.log(field);
$(this).val(field);
});
});
In JavaScript or JQuery + Operator used for concatenation:
var field=data[0]+($(this).data("field"));
I was following a tutorial to pass text to search through ajax, and it works good. Now I want to pass also checkboxes values. Can someone point me to the right direction? Right now I have:
function search(){
var term=$("#search").val();
if(term!=""){
$("#result").html("<img src='/img/spin.gif'/ style='margin-top: 30px;'>");
$.ajax({
type:"post",
url:"file.php",
data:"q="+encodeURIComponent(term), /* encodeURI is used to escape things such as plus sign */
success:function(data){
$("#result").html(data);
$("#search").val("");
}
});
}
So, basically I figure the text is sent through the post variable "q". Let's say I have an array of checkboxes, how can I add that to the same post request?
you could use jQuery's serialize.
$('#form').submit(function(e) {
var data = $('#form').serialize();
$.post('form.php',data, function(status) {
if(status == 'success') {
// success
} else {
// error
}
});
e.preventDefault();
});
form.php
<?php
$search = $_POST['search'];
etc...
$.ajax({
type:"post",
url:"file.php",
data: {
q: encodeURIComponent(term), /* encodeURI is used to escape things such as plus sign */
checkboxes: $('input[type=checkbox]').serialize()
}
success:function(data){
$("#result").html(data);
$("#search").val("");
}
});
It will be simpler for you, if you try to serialize your data.
You didn't write how your html looks like, so let's say you have a form like this:
<form id="form">
Search text: <input type="text" name="data[text]"/>
<input type="checkbox" name="data[option]" /> Option 1
<input type="submit" value="Search"/>
</form>
To send this form with ajax request, all you have to do is to serialize your form
$('#form input[type="submit"]').click(function(e) {
e.preventDefault();
$.post("file.php", $("#form").serialize(), function(){
console.log('success');
});
});
Then in your php script you can retrieve data from $_POST variable, for example $_POST['data']['text']
I'm having some trouble getting my form to submit data to my PHP file.
Without the AJAX script that I have, the form takes the user through to 'xxx.php' and submits the data on the database, however when I include this script, it prevents the page from refreshing, displays the success message, and fades in 'myDiv' but then no data appears in the database.
Any pointers in the right direction would be very much appreciated. Pulling my hair out over this one.
HTML
<form action='xxx.php' id='myForm' method='post'>
<p>Your content</p>
<input type='text' name='content' id='content'/>
<input type='submit' id='subbutton' name='subbutton' value='Submit' />
</form>
<div id='message'></div>
JavaScript
<script>
$(document).ready(function(){
$("#subbutton").click(function(e){
e.preventDefault();
var content = $("#content").attr('value');
$.ajax({
type: "POST",
url: "xxx.php",
data: "content="+content,
success: function(html){
$(".myDiv").fadeTo(500, 1);
},
beforeSend:function(){
$("#message").html("<span style='color:green ! important'>Sending request.</br></br>");
}
});
});
});
</script>
A couple of small changes should get you up and running. First, get the value of the input with .val():
var content = $("#content").val();
You mention that you're checking to see if the submit button isset() but you never send its value to the PHP function. To do that you also need to get its value:
var submit = $('#subbutton').val();
Then, in your AJAX function specify the data correctly:
$.ajax({
type: "POST",
url: "xxx.php",
data: {content:content, subbutton: submit}
...
quotes are not needed on the data attribute names.
On the PHP side you then check for the submit button like this -
if('submit' == $_POST['subbutton']) {
// remainder of your code here
Content will be available in $_POST['content'].
Change the data atribute to
data:{
content:$("#content").val()
}
Also add the atribute error to the ajax with
error:function(e){
console.log(e);
}
And try returning a var dump to $_POST in your php file.
And the most important add to the ajax the dataType atribute according to what You send :
dataType: "text" //text if You try with the var dump o json , whatever.
Another solution would be like :
$.ajax({
type: "POST",
url: "xxxwebpage..ifyouknowhatimean",
data: $("#idForm").serialize(), // serializes the form's elements.
dataType:"text" or "json" // According to what you return in php
success: function(data)
{
console.log(data); // show response from the php script.
}
});
Set the data type like this in your Ajax request: data: { content: content }
I think it isnt a correct JSON format.
I have a module where the forms created are dynamic. So the number of inputs can defer always. Also, the array key can also defer.
My current method of posting form is this:
name = form_options[option_1] value = 1
On submitting the form using POST, I get the form as array in $_POST, which looks like this.
form_options(
option_1 => 1
)
But, now I am trying to implement the same thing using AJAX. So, I would need a common module to get all form values.
I found a way to do it.
var objectResult = $('#options_form').serializeArray();
console.log(objectResult);
This gives me a result like this:
0: Object
name: "form_options[option_1]"
value: "1"
How can parse this result to get an array like $_POST array, which I can send as data in AJAX.
P.S: All the form elements have name field as form_options[key]
You should use this for get post data in PHP file.
// You can use like this
var objectResult = $('#options_form').serializeArray();
$.ajax({
type: "POST", // Enter Request type GET/POST
url: 'action.php', // Enter your ajax file URL here,
dataType: 'json', // If you are using dataType JSON then in php file use die( json_encode($resultArray) );
data: objectResult, // Put your object here
beforeSend: function(){
alert('before');
},
error: function(data) {
console.log(data);
},
success: function(response){
console.log(response);
}
});
// In php file get values like this way
$_POST['form_options']
try like this,
In JQuery:
var objectResult = $('#options_form').serializeArray();
$.ajax({
type: 'POST',
url: 'yoururl'',
data: objectResult ,
success:function(data){
alert(data);
}
});
In your php:
<?php echo var_dump($_POST);?>
You can use jquery serialize with ajax directly, there is no need to use serializeArray:
$.ajax({
type:"post",
url:"formHandleSkript.php",
data: $("#options_form").serialize(),
success: function(response){
$(".result").html(response);
}
});
For more information see http://api.jquery.com/serialize/