Ajax Dropdown to populate Province and City - javascript

I am using Ajax for my dropdown to select Province and City.
I wanted the City to be populated after I choose Province.
I already have my code but unfortunately it doesn't work.
Here are my codes
javascript
<script type="text/javascript">
function provChange(){
var province = $("#province_id").val();
$.ajax({
url: "<?php //echo $this->Html->url('/front/ajax_city_id'); ?>/"+province+"/<?php //echo $this->request->data('Car.city_id'); ?>",cache: false,
success: function(msg){$("#city_id").html(msg); },
"statusCode": {
403: function() {
window.location.href="<?php //echo $this->Html->url(array('controller'=>'front','action'=>'index')); ?>"
},
500: function() {
alert('Error Server Side occured');
}
}
});
}
</script>
view.ctp
<div class="emBeli form large-9 medium-8 columns content">
<?php echo $this->Form->input('provinsi',array('type'=>'select','empty'=>'Provinsi','options'=>$provinsis,'id'=>'province_id','class'=>'form-control form-control-custom','label'=>false,'onChange'=>'provChange()')); ?>
<?php echo $this->Form->input('kota',array('type'=>'select','empty'=>'Kota','options'=>$kota,'class'=>'form-control form-control-custom','label'=>false)); ?>
</div>
ajax_city_id.ctp
<?php
if ($key==null) echo "<option value=\"\">Kota</option>";
foreach($types as $i):
if($i['Kota']['id']==$key) echo "<option value=\"".$i['Kota']['id']."\" selected>".$i['Kota']['name']."</option>";
else echo "<option value=\"".$i['Kota']['id']."\">".$i['Kota']['name']."</option>";
endforeach;
?>
controller.php
public function ajax_city_id($id = null, $key = null, $cur = null)
{
$this->layout = 'ajax';
$this->set('types', $this->Kota->find('all', array('conditions' => array('display' => 1, 'Kota.province_id =' => $id), 'order' => array('Kota.name' => 'asc'))));
$this->set('key', $key);
}
all i got is ReferenceError: Can't find variable: $
which means it can't find variable $("#province_id") on my javascript code.
please somebody help......

Related

How to pass data from Javascript to PHP using ajax

I am working on to receive data in JSON format from a remote server and save it into database. The remote server updates the data each one minutes.
I have written a JavaScript program that receives the jason data from the remote server. Now the problem is I am not able to pass this data to PHP file to be saved in database.
I tried the solution from same threads on stackoverflow but those do not work so far.
I am trying to print the data received from the js in php to find if data is received. The code I have written runs, but nothing happens. It shows no error when pressing F12.
Here is my code. What is wrong I am doing in it.
EDIT
One more problem I figured out is it's not printing the echo. That mean if I try to simply echo "test";, it doesn't print anything. I add full code under to see how/where I am using echo to print the results. Why echo don't get print ?
Javascript:
<script>
var humArray = [];
var temArray = [];
var N = 24;
for (i = 0; i < N; i++) {
humArray.push(0);
temArray.push(0);
}
function loadChart() { //fetches json data & calls dspChart() to render graph
var wData, hum, tem;
var requestURL = 'https://cors.io/?http://api.holfuy.com/live/?s=759&pw=h1u5l4kka&m=JSON&tu=C&su=m/s'; //URL of the JSON data
var request = new XMLHttpRequest({
mozSystem: true
}); // create http request
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
wData = JSON.parse(request.responseText);
hum = wData.humidity;
tem = wData.temperature;
humArray.shift();
humArray.push(hum);
temArray.shift();
temArray.push(tem);
//dspChrt(humArray, temArray);
$.ajax({
url: 'index.php',
type: 'GET',
data: { temArray : temArray, humArray : humArray },
success: function (data) {
console.log( data );
},
error: function (data) {
console.log(data);
},
});
}
}
request.open('GET', requestURL);
request.send(); // send the request
//dspChrt(hum);
}
var myVar = setInterval(loadChart, 60000);
</script>
index.PHP
<?php
if (isset($_GET['data']))
{
$WData = $_GET['data'];
$Humidity = data.humArray;
$Temprature = data.temArray;
echo "Hum".$Humidity."Temp".$Temprature;
}
?>
FULL CODE
<div class="container">
<div class="row">
<div class="col-sm" style="background-color: #FFFFFF">
<h2 style="color:#B93B8F;">Data from JS</h2>
<?php
$servername = "localhost";
$username = "postgres";
$password = "test123";
$dbname = "testDB";
class TableRows extends RecursiveIteratorIterator {
function __construct($it) {
parent::__construct($it, self::LEAVES_ONLY);
}
function current() {
return "<td style='width:150px;border:1px solid grey;'>" . parent::current(). "</td>";
}
function beginChildren() {
echo "<tr>";
}
function endChildren() {
echo "</tr>" . "\n";
}
}
?>
</div>
<?php
if (isset($_GET['data']))
{
$WData = $_GET['data'];
$Humidity = $WData.humArray;
$Temprature = $WData.temArray;
echo "Hum".$Humidity."Temp".$Temprature;
}
?>
<h2>JS Update</h2>
<div>
<canvas id="myChart"></canvas>
</div>
<div class="col-sm" style="background-color: #FFFFFF">
<?php
echo "<h3>WeatherData</h3>";
echo "<table class='table table-hover table-bordered table-reponsive'>";
echo "<thead class='table-dark'>";
echo "<tr><th>humidity</th><th>temprature</th></tr>";
try {
$conn = new PDO("pgsql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT humidity, temprature FROM weatherdata");
$stmt->execute();
// set the resulting array to associative
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
echo $v;
}
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
echo "</thead'>";
echo "</table>";
?>
<div id="form">
<div id="login">
<form action="" method="post">
<input type="text" name="humidity" id="humidity" required="required" placeholder="Enter humidity"/>
<input type="text" name="temprature" id="monikulmio_gps" required="required" placeholder="Enter temprature"/>
<input type="submit" value="Insert" name="submit12"/><br />
</form>
<hr/>
</div>
<?php
if(isset($_POST["submit12"])){
try {
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
$sql = "INSERT INTO weatherdata (humidity, temprature)
VALUES ('".$_POST["humidity"]."','".$_POST["temprature"]."')";
echo "<meta http-equiv='refresh' content='0'>";
if ($conn->query($sql)) {
echo "<script type= 'text/javascript'>alert('New Record Inserted Successfully');</script>";
}
else{
echo "<script type= 'text/javascript'>alert('Data not successfully Inserted.');</script>";
}
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
$conn = null;
?>
</div>
</div>
</div>
</div>
</div>
</body>
in your php you are checking if isset $_GET['data'] but it will always fail. You don't send data you send temArray and humArray. So use isset on $_GET['humArray'] or $_GET['temArray']
So your code will be:
<?php
if (isset($_GET['humArray'])){
$Humidity = $_GET['humArray'];
$Temprature = $_GET['temArray'];
echo "Hum".$Humidity."Temp".$Temprature;
}
?>
I also assume that:
your js is sending data to php.
even if you say humArray and temArray you are fetching just variables and not arrays.
if these are arrays you need to do (instead of using echo):
print_r($Humidity);
print_r($Temprature);
Try to separate your code into at least two files:
index.php - with html and javascript;
fetchWeatherRequest.php - with code below.
Update your javascript code with:
$.when( $.ajax({
type: 'POST',
url: 'fetchWeatherRequest.php',
dataType: 'json'
})
).then( function( response ) {
// Code so render results on index.php;
});
fetchWeatherRequest.php:
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://cors.io/?http://api.holfuy.com/live/?s=759&pw=h1u5l4kka&m=JSON&tu=C&su=m/s",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"Cache-Control: no-cache"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
// Here code to save $response into database;
echo $response;
}

PHP running AJAX script works only once

I have this strange issue, happening to my PHP script, On page load the AJAX script runs and also after the second time the AJAX script runs it works and sends data to PHP, but i seem to not understand why the PHP script doesn't process the incoming POST request the second time it is sent in when i clean the input text box and type again, i get a blank response.My code for more expatiation.
index.php :
<input type="text" onkeyup="searchmedia(this)" placeholder="Search for seller with UNIQUE ID or Name.">
<div id="resut" style="margin-top:-24px!important;">
//where the ajax result is returned
</div>
<div style="margin-top:-24px!important;" id="normal">
//bla bla data here
</div>
<div id="hui" style="display:none;"><img src="../ajax5.gif">
</div>
<script>
function searchmedia(e) {
var tuq = $(e).val();
if (tuq == "") {
$('#resut').hide();
$('#normal').show();
$('#hui').hide();
} else {
$('#normal').hide();
$('#hui').show();
$.ajax({
type: 'POST',
url: 'sellersmessageajax.php',
data: {tuq: tuq},
timeout: 5000,
cache: false,
success: function (r) {
//console.log(r);
$('#resut').html(r);
$('#normal').hide();
$('#hui').hide();
},
error: function () {
alert("Could not search, reload the page and try again.");
$('#normal').show();
$('#hui').hide();
}
});
}
}
</script>
sellersmessageajax.php :
<?php include('../connect.php'); ?>
<?php
if (isset($_POST['tuq']))
{
$term = $_POST['tuq'];
$term = mysqli_real_escape_string($con,
$term); //WHEN I ALERT HERE THE SECOND TIME I SEE THE INPUT TEXT DATA THAT CAME IN BUT PLEASE CHECK AFTER THE **FOREACH**
$condition = '';
$query = explode(" ", $term);
foreach ($query as $text)
{
$condition .= "name LIKE '%" . mysqli_real_escape_string($con,
$text) . "%' OR reign_uniqeer LIKE '%" . mysqli_real_escape_string($con, $text) . "%' OR ";
}
//WHEN I ALERT HERE I GET NOTHING
$condition = substr($condition, 0, -4);
$zobo = "ORDER BY name";
$sql_query = "SELECT * FROM sellers_login WHERE " . $condition . $zobo;
$result = mysqli_query($con, $sql_query);
if (mysqli_num_rows($result) > 0)
{
while ($row = mysqli_fetch_array($result))
{
$v_ida = $row['id'];
$v_namea = $row['name'];
$v_reign_uniqeera = $row['reign_uniqeer'];
?>
<div style="border-bottom:0.1px solid #eee;padding-bottom:20px;margin-top:20px;">
<a class="zuka" title="<?php echo $v_ida ?>" id="<?php echo $v_ida ?>"
style="color:#666;text-decoration:none;outline:none!important;cursor:pointer;">
<b style="color:blue;"><?php echo $v_namea ?></b>
<br/>
<div style="height:auto;max-height:30px;">
<b>UNIQUE ID :</b> <b style="color:red;"><?php echo $v_reign_uniqeera ?></b>
</div>
</a>
</div>
<?php
}
}
else
{
?>
<h1 class="zuka" style="text-align:center;margin-top:20%;"> No result found.</h1>
<?php
}
}
?>
Second time after clearing the data result set to hide. second time data is returning but it's hide
Add this line in ajax success block
$('#resut').show(); // Add this line
you are sending the var tuq wrongfully. Try this:
data : {"tuq": tuq}

Onchange populate different dropdown based on value

I'm trying to populate the second dropdown after I select the first option, nothing appears in the second dropdown.
My first select:
<select name="inst" class="form-control" required="" id="inst">
<option value=0 selected=1>Select...</option>
<?php
$sql="SELECT * FROM sapinst";
$myData=mysqli_query($GLOBALS['con'],$sql);
if (mysqli_num_rows($myData) > 0){
while ($row = mysqli_fetch_array($myData))
{
echo '<option value="' .$row["nbd"]. '">' .$row["nome"]. '</option>';
}
}
else{echo "No categories were found!";}
?>
</select>
My second select:
<select id= "sub" name="sub" class="form-control"></select>
My Script:
<script type="text/javascript">
$("#inst").change(function () {
//get category value
var cat_val = $("#inst").val();
// put your ajax url here to fetch subcategory
var url = '/ajax.php';
// call subcategory ajax here
$.ajax({
type: "POST",
url: url,
data: {
cat_val: cat_val
},
success: function (data)
{
$("#sub").html(data);
}
});
});
</script>
My Ajax.php file:
<?php
require_once 'edp/configdbedp.php';
$prod_cat = $_POST['cat_val'];
$sql = "SELECT * FROM " . $dbname . ".sappainel WHERE nbd = '$prod_cat'";
$result = mysqli_query($conn, $sql);
$msg = '';
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$msg =. '<option value="' . $row["nome"] . '">' . $row["nome"] . '</option>';
}
} else {
$msg .= "No categories were found!";
}
echo $msg;
mysqli_close($conn);
?>
if I try to print some thing in the Ajax php I can't...seems ajax.php won't run.
Am I calling it correctly?
Is your second ajax being called properly?
Check the console messages(in developer options, F12) for errors in ajax call.
you might want to do this as both cat_val are same. It might be giving an error. -
data: {
cat_val: cat_val_local //different variable names here.
},
Also "Select * from $TABLE_NAME(not #dbname)"
and next remove extra .[dot] here -> ".sappainel WHERE"
you can also try put console.log() in success callback and see if the success is returning any elements.
success: function (data)
{
console.log(data);
$("#sub").html(data);
}
If nothing is shown then your php might be wrong. Add an eror callback too! like this -
error: function (e)
{
console.log(e);
}
Hope this helps.
I already solved
Diferences on scrip:
<script type="text/javascript">
$("#inst").change(function(){
//get category value
var cat_val = $("#inst").val();
// put your ajax url here to fetch subcategory
var url = 'ajax.php';
// call subcategory ajax here
$.ajax({
type:"POST",
url:url,
data:{
cat_val : cat_val
},
success:function(data)
{
$("#sub").html(data);
}
});
});
</script>
On ajax.php
<?php
require_once 'edp/configdbedp.php';
$prod_cat = $_POST["cat_val"];
$sql = "SELECT * FROM ".$dbname.".sappainel WHERE nbd = '$prod_cat'";
$result = mysqli_query($GLOBALS['con'], $sql);
$msg ='';
if (mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_array($result))
{
$msg .='<option value="'. $row["nome"] .'">'. $row["nome"] .'</option>';
}
}
else{$msg .="No categories were found!";}
echo ($msg);
mysqli_close($GLOBALS['con']);
?>

Codeigniter Jquery : I want reload this page same

I want when I add a product to the cart and reload the same page, but the problem did not this product.
The controller
public function detail()
{
$data=array('title' =>'Ecommerce Online | Detail Product',
'username' => $this->session->userdata('id'),
'categories' => $this->categories_model->get_categories(),
'details' => $this->categories_model->get_details($this->uri->segment(3)),
'isi' =>'member/detail');
$this->load->view('template_home/wrapper',$data);
}
function addtocart()
{
if($this->cart_model->validate_add_cart_item() == TRUE){
if($this->input->post('ajax') != '1'){
redirect('member/detail/'); // this problem
}else{
echo 'true';
}
}
}
I add my models
function validate_add_cart_item()
{
$id = $this->input->post('product_id');
$cty = $this->input->post('quantity');
$this->db->where('productID', $id);
$query = $this->db->get('product', 1);
if($query->num_rows > 0){
foreach ($query->result() as $row)
{
$data = array(
'id' => $id,
'qty' => $cty,
'price' => $row->price,
'name' => $row->productName
);
$this->cart->insert($data);
return TRUE;
}
}else{
return FALSE;
}
}
I add my view
<?php foreach ($details as $s) { ?>
<div class="col-md-5">
<div class="box text-center">
<img src="<?php echo base_url('upload/'.$s->photo); ?>" width="150px" height="150px">
<br><?php echo $s->productName; ?>
<br><strong>Rp. <?php echo $s->price; ?></strong>
<br>
<?php echo form_open('member/add'); ?>
<fieldset>
<label>Quantity</label>
<?php echo form_input('quantity', '1', 'maxlength="2"'); ?>
<?php echo form_hidden('product_id', $s->productID); ?>
<?php echo form_submit('add', 'Add'); ?>
</fieldset>
<?php echo form_close(); ?>
</div>
</div>
<?php } ?>
Jquery script
<script type="text/javascript">
$(document).ready(function() {
/*place jQuery actions here*/
var link = "<?php echo site_url('member/detail')?>/"; // Url to your application (including index.php/)
$(".detail-product").submit(function(){
var id = $(this).find('input[name=product_id]').val();
var qty = $(this).find('input[name=quantity]').val();
$.post(link + "member/add", { product_id: id, quantity: qty, ajax: '1' },
function(data){
if(data == 'true'){
$.get(link + "member/detail", function(cart){ // Get the contents of the url cart/show_cart
$("#cart_content").html(cart); // Replace the information in the div #cart_content with the retrieved data
});
}else{
alert("Product does not exist");
});
return false; // Stop the browser of loading the page defined
});
});
</script>
This is problem url: http://localhost/scientificwriting/member/detail/ and productid can not be invoked. Do I need to replace the IF statement on my controller and my jquery?
Please help me thanks

How to get a value from select with Ajax and use in PHP

As I wrote in the title I have this part of code in page page.php that is in a subfolder admin. So the path of page is ../admin/page.php:
<select name="my_select" id="my_select" onchange="function(this.value);">
<?php
include "../db/db_config.php";
$conn = mysql_connect($host,$user,$password)or die(mysql_error());
mysql_select_db($db, $conn);
$query="Query";
$res=mysql_query($query,$conn);
while($row=mysql_fetch_array($res)){
$id=$row['id'];
$text=$row['text'];
echo "<option value='$id'>$text</option>";
}
}
?>
</select>
$var = $_POST['my_select'];
echo "I have selected $var";
I use a function that I have found on internet:
function fetch_select(val)
{
$.ajax({
type: 'post',
url: 'page.php',
data: {
get_option:val
},
success: function (response) {
document.getElementById("my_select").innerHTML=response;
}
});
}
What I have to do to take value in $var? Because I need this value to build other things. Is it possible?
EDIT:
Probably I don't explain very well my problem. I don't have very good with ajax because I never use it. I have a deadline so I can't study it now.
Now I have this situation:
I have a select-form with an input submit. After click on the button I use $_POST['myoption'] and I get the value.
Then I do it:
if($var == 1)
//a query from database
else if($var == 2)
//another different query
else
//other but no query
This work correctely. I need to change it and use in the same page. How can I do the same?
You don't to do a POST to do this you can do it with jQuery.
<?php
include "../db/db_config.php";
$conn = mysql_connect($host,$user,$password)or die(mysql_error());
mysql_select_db($db, $conn);
$query="Query";
$res=mysql_query($query,$conn);
?>
<select name="my_select" id="my_select">
<?php
while($row=mysql_fetch_array($res)){
$id=$row['id'];
$text=$row['text'];
echo "<option value='$id'>$text</option>";
}
?>
</select>
<span id="selected"></span>
<script>
$("#my_select").change(function() {
$("#selected").html($("#my_select option:selected").text());
});
</script>
This will give the select value to PHP:
<?php
include "../db/db_config.php";
$conn = mysql_connect($host,$user,$password)or die(mysql_error());
mysql_select_db($db, $conn);
$query="Query";
$res=mysql_query($query,$conn);
if (isset($_POST['my_select'])) {
$var = $_POST['my_select'];
} else {
$var = '';
}
?>
<form id="my_form" action="" method="POST">
<select name="my_select" id="my_select">
<?php
while($row=mysql_fetch_array($res)){
$id=$row['id'];
$text=$row['text'];
echo "<option value='$id'>$text</option>";
}
?>
</select>
</form>
<span id="selected">I have selected <?php echo $var; ?></span>
<script>
$("#my_select").change(function() {
$('#my_form').submit();
});
</script>

Categories

Resources