Codeigniter weird ajax result in controller - javascript

I've started a codeigniter project and now a i have to do an ajax call to a special controller.
It goes something like this:
- I have two select fields: 1 for selecting county's and the other one must populate with the city's in the selected county.
The problem is I get a really weird result when I send the selected county id to the ajax controller.
If I put something like this in the controller : echo "a $county_id" in the controller it will give me the response : a [selected county_id], but if I only echo out the county id it shows some json empty response, and I don't know what's wrong, below is the code:
the ajax(jquery) call.
$(document).ready(function(){
$('#judet').change(function(){
var county = $( "select option:selected" ).val();
$.ajax({
type:'POST',
/*dataType: "json",*/
data:{cou_county:county},
url:'<?php echo base_url("ajax_controller/") ?>',
success:function(){
console.log('id_judet:' + county);
},
error:function(mesaj){
console.log("there's an error");
}
});
});
});
The codeigniter ajax_controller Controller:
public function index()
{ header('content-type text/html charset=utf-8');
$cou_county = $this->input->post('cou_county');
$decodedCounty = $cou_county;
echo "$decodedCounty";
}
The county and city selectors are two simple select inputs with id's I'll post some pictures if you think i haven't explained it well eneugh.
EDIT: the ajax call does access the controller, where i actually echo that id, but in the response i get some weird json thingy instead of the number, like in the picture below:
the response
Thanks for taking the time to read this, and thanks in advance to those of you who take the time to help a brother out.

You can't use PHP code in javascript:
<?php echo base_url("ajax_controller/") ?>
Instead, you should create a js variable like this:
base_url = '<?php echo base_url("ajax_controller/") ?>';
Then use this variable with your function.

In order to use base_url() you have to load url helper in controller like this..
$this->load->helper('url');
Or load in application/config/autoload.php.
Then in your ajax edit url to
url:'<?php echo base_url("ajax_controller/index");?>',
In controller:
public function index()
{
$cou_county = $this->input->post('cou_county');
echo $cou_county;
}
In ajax:
$.ajax({
type:'POST',
/*dataType: "json",*/
data:{cou_county:county},
url:'<?php echo base_url("ajax_controller/index");?>',
success:function(data){
console.log(data); //see your console
},
error:function(data){
console.log("there's an error");
}
});

Related

How to call controller from ajax and send $_POST

I want to call controller from ajax and send POST into database. After POST was sent, i will display database into dropdown list.
but i don't know what to do. here is my code.
ajax script inside view add_produk.php
<script>
function getId(val){
// ajax function
$.ajax({
type: "POST",
url: "<?php base_url();?>index.php/getdata",
data: "id_kategori="+val,
success: function(data){
$("#subcat").html(data);
}
});
}
</script>
i want to load controller getdata.php and send $_POST into this controller, Controller getdata.php :
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Getdata extends CI_Controller
{
public function index()
{
if(!empty($_POST["id_kategori"])){
$idcat = $_POST["id_kategori"];
$sql = "SELECT * FROM sub_kategori WHERE id_kategori = $idcat";
$result = $this->db->query($sql);
foreach ($result as $subcat) {
?>
<option value="<?php echo $subcat["id_sub_kategori"];?>"><?php echo $city["nama_sub_kategori"];?></option>
<?php
}
}
}
}
?>
how i can fix my problem?
i think wrong in here data: "id_kategori="+val
i dont know php, but u can try "data:{id_kategori:val}"
good luck

CakePHP can't get ajax GET working

I can't seem to get AJAX POST or GET working with my CAKEPHP site. I am trying to create autocomplete but can't seem to submit or fetch the data using ajax. I can get auto complete working using tags but I cannot display the data from my table. I am not sure what is going wrong if i'm not using the right url or some other problem.
Here is my search.ctp
<?php use Cake\Routing\Router; ?>
<?php echo $this->Form->input('id', ['type' => 'text']); ?>
<script>
$.ajax({
type: "POST",
url: "<?php echo Router::url(array('controller' => 'Invoices', 'action' => 'search')); ?>",
success: function(response) {
$("#id").autocomplete({ source: response });
}
});
</script>
Here is my search function in my InvoicesController.
public function search()
{
$this->loadComponent('RequestHandler');
if ($this->request->is('ajax'))
{
$name = $this->request->query['term'];
$resultArr = $this->Invoices
->find()
->where(
['Invoices.id LIKE' => ($name . '%')],
['Invoices.id' => 'string']
);
$resultsArr = [];
foreach ($resultArr as $result)
{
$resultsArr[] = (strval($result['id']));
}
$this->set('resultsArr', $resultsArr);
// This line is what handles converting your array into json
// To get this to work you must load the request handler
$this->set('_serialize', ['resultsArr']);
}
}
This is the error that is produced when I try to type in an ID.
This is what i want to produce which I have been able to do by using an array in search.ctp
and here is my table I am trying to fetch the IDs from.
There are two methods.
$this->request->query('term');
$_REQUEST['term'];

AJAX - Javascript array to php

I know that there are so many to find on the internet, however, I have been trying this for hours now, and still not working, Maybe the community could help me out:)
http://jsfiddle.net/dkk2nqyg/14/
I've got a little explanation in the jsfiddle, else, you can take a look in my previous question, JavaScript array splice
Basicly, I want the values from selected ( 3 picked up cards )
in php, because I want to mail those values;)
$.ajax({
url: 'data.php', //I actually want it to be on same page, trying this for debugging
type: 'post',
data: {data : selected},
success: function(data) {
alert("worked");
}
});
in the data.php :
<?php
$data = json_decode(stripslashes($_POST['data']));
foreach($data as $d){
echo $d;
}
?>
I would like that I don't even need that data.php but just 1 page, so in the index.php, is that even possible?
Edit: Please, link a JsFiddle, would really help!
First the ajax request should be within the click handler
$('#mail').click(function () {
console.log($('#dvDest .flipper').get())
var selected = $('#dvDest .flipper').map(function () {
return $(this).data('src')
}).get();
alert(selected)
$.ajax({
url: 'data.php', //I actually want it to be on same page, trying this for debugging
type: 'post',
data: {
data: selected
},
success: function (data) {
alert("worked");
}
});
})
then in server side loop through the array like(Not sure about the PHP syntax)
<?php
foreach($_POST['data'] as $d){
echo $d;
}
?>
you can write a condition as if request object have post values then
$data = json_decode(stripslashes($_POST['data']));
foreach($data as $d){
echo $d;
}
else your homepage display code
So,index.php is enough
For using a single page, eg: index.php
at the top of index.php you do:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Your code goes here
exit();
}

AJAX PHP function onchange select box

I have a problem about which I am very confused. I have a select box with s dynamically generated using a mysqli query:
$result = mysqli_query($db, "SELECT * FROM `users` WHERE `user_id` > 0");
echo '<html><form name="contacts" method="post"><select name="contacts"><option value="Contact list" onchange="func()">Contact List</option>';
while($row = $result->fetch_assoc()){
echo '<option value = '.$row['user_name'].'>'.$row['user_name'] . '</option>';
}
echo '</select></form>';
I am completely new to AJAX, but I need to use jquery and ajax to pass the this.value variable to a php variable for use in a later query.
Here is my script (most of which was found online):
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
$("#contacts").change(function() {
//get the selected value
var selectedValue = this.value;
//make the ajax call
$.ajax({
url: 'function.php',
type: 'POST',
data: {option : selectedValue},
success: function() {
console.log("Data sent!");
}
});
});
</script>
Now, when I click a value in the select box, nothing happens. There are no warnings or errors, etc.
Please help me.
p.s. function.php does exist. It is just a simple echo for now (for testing purposes)
UPDATE: HERE IS FUNCION.PHP:
<?php
/*$val = $_REQUEST['selectedValue'];
echo $val;*/
function function(){
$val = $_REQUEST['selectedValue'];
echo $val;
}
?>
UPDATE: Thank you everyone for all your help. I have now got it to work in that the network section of chrome inspect shows the function.php being requested however I still don't get the echo (I used external .js files to get it to work). My J query function is also successful (the success function echoes into the console)
Your select box has no ID and you are watching the change event of $("#contacts").
Change:
echo '<html><form name="contacts" method="post"><select name="contacts"><option value="Contact list" onchange="func()">Contact List</option>';
to:
echo '<html><form name="contacts" method="post"><select name="contacts" id="contacts"><option value="Contact list">Contact List</option>';
^^^^^^^^^^^^^ here
You also only need one event handler, so I have removed the inline one which doesn't seem to do anything anyway.
Edit: If the select is created using ajax as well, you need event delegation:
$("body").on('change', '#contacts', function() {
^^^^ for example
Edit 2: Your variable is called $_REQUEST['option'] and not $_REQUEST['selectedValue']. You are also not calling your -badly named - function so you will not get any output from php except from an error like Parse error: syntax error, unexpected 'function' ....
Call onchange function in select tag as below
echo '<form name="contacts" method="post"><select name="contacts" onchange="func(this.value)"><option value="Contact list">Contact List</option></form>';
Javascript src should be in head of the html page.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
Add the above one in head of html. Update javacript as below
As onchange function is called in the select tag itself, following is enough
<script>
function func(selectedValue)
{
//make the ajax call
$.ajax({
url: 'function.php',
type: 'POST',
data: {option : selectedValue},
success: function() {
console.log("Data sent!");
}
});
}
</script>
Updated php: If you must want to get value from function, you must call it. Otherwise, simply, you can make as below
<?php
if($_REQUEST['option'])
{
$val=$_REQUEST['option'];
echo $val;
}
?>
In .php file, receive it first-
$val = $_REQUEST['selectedValue'];
echo $val;
set an id attribute in your php code for the select tag and
please don't use the same value for the name attribute in form and select tags !!
just change your function to a 'body'.on, and give your elements an id of 'contacts'
$("body").on('change', '#contacts', function() {
//get the selected value
var selectedValue = $(this).val();
//make the ajax call
$.ajax({
url: 'function.php',
type: 'POST',
data: {option : selectedValue},
success: function() {
console.log("Data sent!");
}
});
});

AJAX returns the complete HTML site instead the JSON object

I finally could receive a response from my AJAX PHP call.
But now in return I get my full HTML site instead of a JSON object or string.
What is wrong here?
var request = $.ajax({
url: "mysite.php",
type: "POST",
data: {select:requestStr},
dataType: "html"
});
request.done(function( data ) {
console.log(JSON.stringify(data));
});
I send a simple string to my php class. This is what I get from the response-text in my developer tool from the browser:
data=Test
On PHP site I just return that respone:
<?php
$myData = array();
$myData['data'] = "test";
if (isset($_POST)) {
$myData['data'] = $_POST;
}
echo json_encode($myData);
exit();
?>
And this is the console.log from the response:
"<!DOCTYPE html>\r\n<html>\r\n<head> ... </html>\"Test\""
EDIT
I only need the end of the response and that is "Test" but not the whole HTML file.
UPDATE
I extracted my PHP class and wrote a Little Version like the PHP code above.
But now my response is an empty object {"data":[]}
Hey put type="Json" instead of the "text"
Put a exit(); after echo json_encode($myData);

Categories