My ajax script
function filter(){
var input1 = $("#advanced-search1").val();
$.ajax({
dataType: 'html',
url: "php/filter.php",
type: "POST",
data: input1,
success: function(response){
$('#result').html(response);
}
});
}
The html form
<form>
<select id="advanced-search1" name="taskOption">
<option value="apple">Apple</option>
.
.
.
</select>
<input type="submit" onclick="filter()" value="Filter">
</form>
<div id="result"></div>
My question is how to pass the "select" id into an ajax so that it can be processed in the other php file (filter.php)
The way data works is by using an object... What you are doing is wrong. Replace the data part with:
data: {"key": input1},
And in the server side you should be able to access it using:
$_POST["key"]
Related
I am new to code igniter and I have searched the following question in number of StackOverflow threads but none of them seem to solve my problem.
I have the following view code:
<select name="select1" id="select1">
<option value="0">None</option>
<option value="1">First</option>
</select>
<scriptsrc="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
// Ajax post
$(document).ready(function() {
$("#select1").change(function(event) {
event.preventDefault();
var id = $(this).val();
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "index.php/mycontroller/method",
dataType: 'json',
data: {id: id},
success: function(res) {
}
});
});
});
</script>
Ok when I change the drop down list selection nothing happens, which should actually call my controller method. Can you please help me resolve this problem?
Thanks
You are using <select> id as category
But In jquery you are calling $("#select1").change(function(event) like this .
You just need to change $("#select1").change(function(event) to
$("#category").change(function(event)
Check in console if your script contains any errors.
if no errors with script, check your function getting called after change, by adding alert or console statement.
if function getting called, check base_url. As per latest comment '/' missing.
You can also try Following snippet :
//Add J Query Library here
<select name="select1" id="select1" onchange="funName(this);">
<option value="0">None</option>
<option value="1">First</option>
</select>
<script type="text/javascript">
function funName(element)
{
var id = element.value;
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "/index.php/mycontroller/method",
dataType: 'json',
data: {"id" : id},
success: function(res) {
console.log(res);
}
});
}
</script>
There is mistake with your jquery selector.
you are using $("#select1").change(function(){});
you don't have any id reffered in this name in your section.
$("#category").change(function(event) {
//ur code here
});
You used id selector in the jquery code but that id is mentioned as a name attribute in html dropdown tag. So try the following code.
Change this following:-
<select name="select1" id="category">
<option value="0">None</option>
<option value="1">First</option>
</select>
<scriptsrc="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
// Ajax post
$(document).ready(function() {
$("#category").change(function(event) {
event.preventDefault();
var id = $(this).val();
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "index.php/mycontroller/method",
dataType: 'json',
data: {id: id},
success: function(res) {
}
});
});
});
I'm trying to get post id and insert it into database after user click on add to favorite button.
The problem that all the post are return id 30 which is the last id in the database.
My php/html code
while($row = mysqli_fetch_array($get_posts)) {
<i style="float:right;" class="fa fa-pinterest-square">
<form id="pin_post" method="post"> ';
if (isset($_SESSION['user_id'])){
<input type="hidden" value="'. $_SESSION['user_id'].'" name="user_id" />
}
<input type="hidden" value="'.$row['post_id'].'" name="post_id[]" />
</form>
</i>
The jQuery / Ajax code
<script>
$(document).on("click",".fa-pinterest-square",function(e) {
$.ajax({
url: "includes/test.php",
type: "POST",
data: $('#pin_post').serialize(),
success: function(data) {
alert(data);
}
});
});
</script>
I'm getting last id in the database when I click any post.
Please help me to get the id of each post when I click on the
Since you are using #pin_post when serializing it you will get the last hit when jQuery is looking for #pin_post. Either you should use a unique id or something like this
$(document).on("click",".fa-pinterest-square",function(e) {
var form = $(this).find('form'); //Since the form is child to <i>
$.ajax({
url: "includes/test.php",
type: "POST",
data: form.serialize(),
success: function(data) {
alert(data);
}
});
});
I have such code
<form>
<input type="text" value="" name="someval">
<button id="ajax-button">ajaxButton</button>
</form>
<script>
$(document).ready(function(){
$('#ajax-button').click(function(e){
e.preventDefault();
$.ajax({
type: "GET",
url: "action.php",
data: { text : $('input[name=someval]').val() },
dataType: "text",
success: function (data){
alert(data);
}
});
});
});
</script>
Now I try to echo the Ajax returned value in php.
I try
echo json_encode($text);
echo $text;
echo $_GET['text'];
Al are wrong.
How to get it in PHP.
Thanks
Set attributes for the form to get semantic correct html
<form action="action.php" id="someForm" method="POST">
<input type="text" value="" name="someval">
<select id="someSelect">
<option value="some_1">some 1</option>
<option value="some_2">some 2</option>
<option value="some_3">some 3</option>
</select>
<button id="ajax-button">Send</button>
</form>
Your script
<script>
$(function(){
var form = $("#someForm"),
select = $("#someSelect"),
url, formData;
form.submit(function(event){
event.preventDefault();
url = form.attr("action");
formData = form.serializeArray();
$.post(url, data, function(response){
console.log($.parseJSON(response));
});
});
select.change(function(){
url = form.attr("action");
formData = form.serializeArray();
$.post(url, data, function(response){
console.log($.parseJSON(response));
});
});
});
</script>
Your php file(path to file set in action attribute of the form).
<?php
var_dump($_POST);
?>
Use data: 'text=' + $('input[name=someval]').val() , instead. And in PHP you can directly access it using echo $_GET['text']; only without the need of json encoding it.
Otherwise the syntax of json is data: { "text" : $('input[name=someval]').val() },.
I am trying to pass the form value "New Value" from jQuery to a PHP script, and then update the "to_change" div from "Old value" to "New value". It seemed like the AJAX call succeeded, but the POST variables are not being sent to the PHP script, and when I use getJSON, I do not succeed. How could I resolve this issue?
Javascript/HTML code:
<html>
<head>
<script src = 'jquery-1.10.2.js'></script>
<script>
$(document).ready(function() {
$("#form_tmin").submit(function(event) {
var values = $(this).serialize();
$.ajax({
type: "POST",
url: "parameters_form2.php",
data: values,
dataType: "json",
success: function(data){
$.getJSON("parameters_form2.php", function(tmin) {
document.getElementById("to_change").innerHTML = tmin[1];
});
}
});
return false;
});
});
</script>
</head>
<body>
<div id="to_change">Old value</div>
<form id="form_tmin" name="form_tmin">
<input type="hidden" id="tmin_value" name="tmin_value" value="New value">
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
PHP code:
<?php
header('Content-Type: application/json');
if ($_POST["tmin_value"]) {
$tmin[1] = $_REQUEST["tmin_value"];
}
else {
$tmin[1] = "FAILURE";
}
echo json_encode($tmin);
?>
You already have json response in data just set this data in where ever you want to display. you don not need $.getJSON again.
try like this:
$(document).ready(function() {
$("#form_tmin").submit(function(event) {
var values = $(this).serialize();
$.ajax({
type: "POST",
url: "parameters_form2.php",
data: values,
dataType: "json",
success: function(data){
document.getElementById("to_change").innerHTML = data[1];
}
});
return false;
});
});
You already have the response of query, no need to use $.getJson again
Instead just use:
success: function(data){
$("to_change").html(data[1]);
}
I need to feed cities based on country of selection. I did it programmically but have no idea how to put JSON data into the select box. I tried several ways using jQuery, but none of them worked.
The response I am getting (I can format this differently if necessary):
["<option value='Woodland Hills'>Woodland Hills<\/option>","<option value='none'>none<\/option>","<option value='Los Angeles'>Los Angeles<\/option>","<option value='Laguna Hills'>Laguna Hills<\/option>"]
But how can I put this data as options inside a HTML <select></select> tag?
The code I tried:
<form action="" method="post">
<input id="city" name="city" type="text" onkeyup="getResults(this.value)"/>
<input type="text" id="result" value=""/>
<select id="myselect" name="myselect" ><option selected="selected">blank</option></select>
</form>
</div>
<script>
function getResults(str) {
$.ajax({
url:'suggest.html',
type:'POST',
data: 'q=' + str,
dataType: 'json',
success: function( json ) {
$('#myselect').append(json);
}
});
};
$( '.suggest' ).keyup( function() {
getResults( $( this ).val() );
} );
</script>
I also tried to use this tutorial on auto-populating select boxes using jQuery and AJAX, but this never did anything except filling my select with "UNDEFINED" for me even though I got the response in the format the tutorial suggested.
<script type="text/javascript" charset="utf-8">
$(function(){
$("select#city").change(function(){
$.getJSON("/select.php",{id: $(this).val(), ajax: 'true'}, function(j){
var options = '';
for (var i = 0; i < j.length; i++) {
options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';
}
$("select#myselect").html(options);
})
})
})
</script>
Why not just make the server return the names?
["Woodland Hills", "none", "Los Angeles", "Laguna Hills"]
Then create the <option> elements using JavaScript.
$.ajax({
url:'suggest.html',
type:'POST',
data: 'q=' + str,
dataType: 'json',
success: function( json ) {
$.each(json, function(i, value) {
$('#myselect').append($('<option>').text(value).attr('value', value));
});
}
});
Given returned json from your://site.com:
[{text:"Text1", val:"Value1"},
{text:"Text2", val:"Value2"},
{text:"Text3", val:"Value3"}]
Use this:
$.getJSON("your://site.com", function(json){
$('#select').empty();
$('#select').append($('<option>').text("Select"));
$.each(json, function(i, obj){
$('#select').append($('<option>').text(obj.text).attr('value', obj.val));
});
});
You should do it like this:
function getResults(str) {
$.ajax({
url:'suggest.html',
type:'POST',
data: 'q=' + str,
dataType: 'json',
success: function( json ) {
$.each(json, function(i, optionHtml){
$('#myselect').append(optionHtml);
});
}
});
};
Cheers
Take a look at JQuery view engine and just load the array into a dropdown:
$.ajax({
url:'suggest.html',
type:'POST',
data: 'q=' + str,
dataType: 'json',
success: function( json ) {
// Assumption is that API returned something like:["North","West","South","East"];
$('#myselect').view(json);
}
});
See details here: https://jocapc.github.io/jquery-view-engine/docs/ajax-dropdown
zeusstl is right. it works for me too.
<select class="form-control select2" id="myselect">
<option disabled="disabled" selected></option>
<option>Male</option>
<option>Female</option>
</select>
$.getJSON("mysite/json1.php", function(json){
$('#myselect').empty();
$('#myselect').append($('<option>').text("Select"));
$.each(json, function(i, obj){
$('#myselect').append($('<option>').text(obj.text).attr('value', obj.val));
});
});
I know this question is a bit old, but I'd use a jQuery template and a $.ajax call:
ASPX:
<select id="mySelect" name="mySelect>
<option value="0">-select-</option>
</select>
<script id="mySelectTemplate" type="text/x-jquery-tmpl">
<option value="${CityId}">${CityName}</option>
</script>
JS:
$.ajax({
url: location.pathname + '/GetCities',
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (response) {
$('#mySelectTemplate').tmpl(response.d).appendTo('#mySelect');
}
});
In addition to the above you'll need a web method (GetCities) that returns a list of objects that include the data elements you're using in your template. I often use Entity Framework and my web method will call a manager class that is getting values from the database using linq. By doing that you can have your input save to the database and refreshing your select list is as simple as calling the databind in JS in the success of your save.