Select list not getting populated (jQuery Ajax) - javascript

Update: Got this working by disabling CodeIgniter Profiler which was interfering with the Ajax success response. I think it adds a div to the JSON response.
I am trying to populate a dependent select box with data from mysql database. The problem is that the dependent select box is not getting populated in spite of getting data in the correct format in response to Ajax request.
Please help me as I am totally clueless about what's happening here. Below is my JavaScript code.
<script type="text/javascript">
$(document).ready(function(){
$('#country').change(function(){
$("#cities > option").remove();
var form_data = {
country: $('#country').val(),
csrf_token_name: $.cookie("csrf_cookie_name")
};
$.ajax({
type: "POST",
url: "http://localhost/outlets/get_cities",
data: form_data,
dataType : "JSON",
success: function(cities)
{
$.each(cities,function(id,name)
{
var opt = $('<option />');
opt.val(id);
opt.text(name);
$('#cities').append(opt);
});
}
});
});
});
</script>
And here is the HTML. I am using Codeigniter.
<form id="form">
<?php $cities['#'] = 'Please Select'; ?>
<label for="country">Country: </label><?php echo form_dropdown('country_id', $countries, '#', 'id="country"'); ?><br />
<label for="city">City: </label><?php echo form_dropdown('city_id', $cities, '#', 'id="cities"'); ?><br />
</form>
Here is the controller:
function get_cities(){
$country = $this->input->post('country');
$this->load->model('city');
header('Content-Type: application/x-json; charset=utf-8');
echo (json_encode($this->city->get_cities($country)));
}
& the Model:
function get_cities($country = NULL){
$this->db->select('id, name');
if($country != NULL){
$this->db->where('countries_id', $country);
}
$query = $this->db->get('cities');
$cities = array();
if($query->result()){
foreach ($query->result() as $city) {
$cities[$city->id] = $city->name;
}
return $cities;
}else{
return FALSE;
}
}

Change your ajax success callback to:
success: function (cities) {
for (var id in cities) {
var opt = $('<option />');
opt.val(id);
opt.text(cities[id]);
$('#cities').append(opt);
}
}
Because your ajax result is not a array but an json object.

Alright everyone, I managed to get this working by disabling CodeIgniter Profiler. Codeigniter profiler, that otherwise is a handy tool, breaks javascript on any page with Ajax. If you can't do without profiler, use the solution provided on Making CodeIgniter’s Profiler AJAX compatible

Related

How to get another page on ajax?

I've a problem with my page, first code (let said is hompe.php)
<html>
<div id="trackingkp"></div>
</html>
then on my ajax I've code like these
$( document ).ready(function() {
var dataString = '';
$.ajax
({
type: "POST",
url: host+"ajax/tracking/kp",
dataType: 'html',
success: function(html)
{
$('#trackingkp').html($(html).find('#trackingkp').html());
//$("#trackingkp").html($(data).find('#trackingkp').html());
}
});
});
and on my ajax controller, I do like these (I'm using framework laravel)
public function tracking($url)
{
//var_dump("AAA");
$this->view('ajax/tracking/'.$url,[]);
}
on my ajax/tracking view like this
<?php
//$json = array();
$json = "<input type='text'></input>";
echo json_encode($json);
?>
When I try that is showing
Syntax error, unrecognized expression: "<input type='text'>
I have solved the problem, I'm using another option without using jQuery, so on same time, on controller when load view home.php, I try put load view too like these
public function index(){
is_header();
$this->view('home',[]);
$this->view('ajax/tracking/kp',[]); ---> I add these
is_footer();
}
and on ajax/tracking/kp (view) I put these code
<input type='text'></input>
and is working.
The problem would be in this one:
success: function(html) {
// Problem : $(html).find('#trackingkp').html();
$('#trackingkp').html($(html).find('#trackingkp').html());
}
From which this html response is expected to return a json value
in your given [controller]
<?php
//$json = array();
$json = "<input type='text'></input>";
echo json_encode($json);
?>
Thus this is equivalent to:
$("<input type='text'></input>").find('#trackingkp').html();
In this case, I don't think you might need to call another *.html(). You can simplify / solve this by calling it once:
$.ajax({
type: "POST",
url: host+"ajax/tracking/kp",
dataType: 'json', // Kindly replace [html] to [json] since you are returning a [json] value
success: function(html) {
$('#trackingkp').html(html);
}
});
Hope this helps for your case

Get and display results of PHP using jQuery/AJAX

I have a Leaflet map, and a text input. I want to take the address from the textbox, run it through a PHP script, and get the result all through jQuery.
Here is my form:
<form id="mapcheck" method="POST" action="geo.php">
<input id="largetxt" type="text" name="checkAddress">
<input id="button" type="submit" name="submit" value="Check">
</form>
Here is part of the PHP:
<?php
if (isset($_POST["checkAddress"])) { //Checks if action value exists
$checkAddress = $_POST["checkAddress"];
$plus = str_replace(" ", "+", $checkAddress);
$json = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address=' . $plus . '&key=GMAPSKEY');
$obj = json_decode($json);
$mapLat = $obj->results[0]->geometry->location->lat;
$mapLng = $obj->results[0]->geometry->location->lng;
$coords = ('' . $mapLat . ', ' . $mapLng . '');
return $coords;
}
?>
And the jQuery:
$(document).ready(function() {
$("#button").click(function(){
$.ajax({
url: "geo.php",
method: "POST",
data: {
checkAddress: $("#largetxt").val()
},
success: function(response){
console.log(response);
}
});
});
});
I need to listen on submit of the form via jQuery (NOT PHP), run it through a geocode script, then take that result and put it through regular JavaScript (Leaflet map.) I have played around with the AJAX feature of jQuery to no avail. There is a very simple solution to this, but I have not figured it out.
UPDATE: Problem resolved, thanks Vic.
You would need AJAX. Remove the form element but keep the inputs.
$("#button").click(function(){
$.ajax({
url: "geo.php",
method: "POST",
data: {
checkAddress: $("#largeText").val()
},
success: function(response){
console.log(response);
//your script
}
})
});

Retrieving data value from database from ajax function

I have a ajax function that would retrieve data from my database and display it in my textbox. I am using a JQuery Form Plugin to shorten the ajax process a little bit. Now what I want to do is to get the data back from the php script that I called from the ajax function.
The form markup is:
<form action="searchFunction.php" method="post" id="searchForm">
<input type="text" name="searchStudent" id="searchStudent" class="searchTextbox" />
<input type="submit" name="Search" id="Search" value="Search" class="searchButton" />
</form>
Server code in searchFunction.php
$cardid = $_POST['searchStudent'] ;
$cardid = mysql_real_escape_string($cardid);
$sql = mysql_query("SELECT * FROM `users` WHERE `card_id` = '$cardid'") or trigger_error(mysql_error().$sql);
$row = mysql_fetch_assoc($sql);
return $row;
The ajax script that processes the php is
$(document).ready(function() {
$('#searchForm').ajaxForm({
dataType: 'json',
success: processSearch
});
});
function processSearch(data) {
alert(data['username']); //Am I doing it right here?
}
In PHP, if I want to call the data, I would just simply create a function for the database and just for example echo $row['username'] it. But how do I do this with ajax? I'm fairly new to this so, please explain the process.
$('#Search').click(function (e) {
e.preventDefault(); // <------------------ stop default behaviour of button
var element = this;
$.ajax({
url: "/<SolutionName>/<MethodName>",
type: "POST",
data: JSON.stringify({ 'Options': someData}),
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
error: function () {
alert('Unable to load feed, Incorrect path or invalid feed');
},
success: processSearch,
});
});
function processSearch(data) {
var username= ($(data).find('#username'));
}
Change the input type submit to button. Submit will trigger the action in the form so the form will get reloaded. if you are performing an ajax call change it into button.
Everything seems to be fine, except this bit -
function processSearch(data) {
alert(data['username']); //Am I doing it right here?
}
You need to change it to -
function processSearch(data) {
// data is a JSON object. Need to access it with dot notation
alert(data.username);
}
UPDATE
You also need to return a JSON response from your PHP file. Something like -
// Set the Content Type to JSON
header('Content-Type: application/json');
$data = [
"key" => "value"
];
return json_encode($data);
In your case you can directly encode the $row like so -
return json_encode($row);

How to get array from input and select box with jquery?

I'm learning js and jquery. I will post values as array with jquery ajax and in php code I will use it with foreach loop.
<select name="passenger['+i+'][nationality]">
<option value="GRE">GRE</option>
...
</select>
<input name="passenger['+i+'][gsm]" value="">
I have a form like that (for example). In php code I will use this names like that :
$passengers = $_POST['passenger']
foreach ($passengers as $i => $passenger) {
echo $passenger['nationality'] . '<br>';
echo $passenger['gsm'] . '<br>';
}
But to use in php I must post with jquery ajax. But I cant get array passenger with jquery to post as passenger array.
JS CODES
I need a passenger variable.
jQuery.ajax({
url: link,
type: "POST",
data: {passenger : passenger},
dataType: "json",
success: function(s) {
},
error: function() {
}
});
You can use serialize to get all the values within a form. So your JS can be:
$.post( link , $( "#testform" ).serialize() , function() {
alert('Succes');
});

mysql query executed even though fields are empty

I have created a simple tagging system for my schools websites for the students. Now the tagging system is working perfectly now i also have to save tags in a notifications table with respective article id to later notify the students which article they have been tagged in even that i managed to do. But now if by chance you want to remove the tags sometime realizing while typing the article you don't need to tag that person, then the first put tag also gets updated in the db.
//ajax code (attach.php)
<?php
include('config.php');
if(isset($_POST))
{
$u=$_POST['v'];
mysql_query("INSERT INTO `notify` (`not_e`) VALUES ('$u')");
}
?>
// tagsystem js code
<script type="text/javascript">
var id = '<?php echo $id ?>';
$(document).ready(function()
{
var start=/%/ig;
var word=/%(\w+)/ig;
$("#story").live("keyup",function()
{
var content=$(this).text();
var go= content.match(start);
var name= content.match(word);
var dataString = 'searchword='+ name;
if(go.length>0)
{
$("#msgbox").slideDown('show');
$("#display").slideUp('show');
$("#msgbox").html("Type the name of someone or something...");
if(name.length>0)
{
$.ajax({
type: "POST",
url: "boxsearch.php",
data: dataString,
cache: false,
success: function(html)
{
$("#msgbox").hide();
$("#display").html(html).show();
}
});
}
}
return false();
});
$(".addname").live("click",function()
{
var username=$(this).attr('title');
$.ajax({
type: "POST",
url: "attach.php",
data: {'v': username},
});
var old=$("#story").html();
var content=old.replace(word,"");
$("#story").html(content);
var E="<a class='blue' contenteditable='false' href='profile2.php?id="+username+"'>"+username+"</a>";
$("#story").append(E);
$("#display").hide();
$("#msgbox").hide();
$("#story").focus();
});
});
</script>
Looks like your problem appears on the if statement in php code:
even though $_POST['v'] is empty and the sql still get excuted.
There is the quote from another thread:
"
Use !empty instead of isset. isset return true for $_POST because $_POST array is superglobal and always exists (set).
Or better use $_SERVER['REQUEST_METHOD'] == 'POST'
"
Or in my opinion.
Just put
if ($_POST['v']){
//sql query
}
Hope it helps;)
<?php
include('config.php');
$u = $_POST["v"];
//echo $a;
if($u != '')
{
mysql_query("your insert query");
}
else
{
}
?>

Categories