return multiple values from php to jquery - javascript

i have api that returns a list of cities and the relevant geo zone when i type the post code.
eg:
postcode -3000 returns 9 cities and geo zone - A012
postcode -3008 returns 12 cities and geo zone - C01
So i have written the below code. Once the post code is entered it will append the cities into a dropdown. which works great
php
if($response == NULL || $response < 1 )
{
echo "wrong Postcode";
} else{
foreach ($response as $q)
{
$cty = $q['city'];
$geozone = $q['geozone'];
echo '<option value="'.$cty.'">'.$cty.'</option>';
}
jquery
<script type="text/javascript">
$(document).ready(function()
{
$(".postcode").change(function()
{
var dataString = 'postcode='+ id;
$.ajax
({
type: "POST",
url: "load.php",
data: dataString,
cache: false,
success: function(val)
{
$(".city").html(val);
}
});
});
});
</script>
the problem is i need to append the $geozone which is returned in the php to a input box
since i have echoed the option values, i can easily append it
echo '<option value="'.$cty.'">'.$cty.'</option>';
but how do i return $geozone = $q['geozone']; to my main page so i can use it with a text field

I think that is better build the select from json data. Try to change the php for somthing like this
if($response == NULL || $response < 1 )
{
echo "wrong Postcode";
} else{
echo json_encode($response);
}
This will return a json array with the complete response with the cities and geozone, then you need to build the form with JS
$.ajax({
type: "POST",
url: "load.php",
data: dataString,
cache: false,
dataType: "json"
success: function(val)
{
options = "";
for(x in val){
options += '<option value="'+val[x].city+'">'+val[x].city+'</option>'
}
$(".city").html(options);
$(".form").append('<input type="text" value="'+val[x].geozone+'">');
}
});
This will build the form for you. You will have to adapt this code to json response and the .form for the parent selector of your form.

I would do like this
first make one array to return. At index 0 you concatenate options and at index 1 concatenate $geozone in a ipnut hidden (if that is useful).
$dataReturn = array();
$dataReturn[0] = '';
$dataReturn[1] = '';
if($response == NULL || $response < 1 )
{
echo "wrong Postcode";
} else{
foreach ($response as $q)
{
$cty = $q['city'];
$geozone = $q['geozone'];
$dataReturn[0] .= '<option value="'.$cty.'">'.$cty.'</option>';
$dataReturn[1] .= '<input type='hidden' value="'.$geozone.'"';
}
echo json_encode(array($dataReturn);
json_encode(array($dataReturn)
Now parse it at success
success: function(val)
{
parsed = $.parseJSON(val);
$(".city").html(val[0][0]);
$(".hidden").html(val[0][1]); //a div
}
I did not test, but I already did something like that. Hope my memory has helped.

You can use extra attribute in option tag like this.
echo '<option value="'.$cty.'" geozone="'.$geozone.'" >'.$cty.'</option>';
This will echo as
<option value="Mumbai" geozone="A012" >Mumbai</option>
and Use jquery's .attr() method to get the value from option
var myTag = $(':selected', element).attr("geozone");

Related

How can i call a php function on a dynamically created html element in .js file

This is my product.php file which include the following php function
<?php
function getOfferName($conn,$companyID){
$sql="SELECT `id`, `offer_name`, `offer_discount` FROM `oiw_product_offers`
WHERE `company_id`='$companyID'";
if ($result=mysqli_query($conn,$sql)) {
while ($row=mysqli_fetch_assoc($result)) {
?>
<option value="<?php echo $row['id'] ?>"><?php echo $row['offer_name'] ?></option>
<?php
}
}
}
?>
This product.php file include the custom-js.js file in which i am creating a html element dynamically (Select dropdown).
$('.offerCheckBox').on('change', function() {
var id=$(this).data('id');
if (!this.checked) {
var sure = confirm("Are you sure want to remove offer ?");
this.checked = !sure;
}else{
$(this).parent().parent().append('<select name="" id=""><?php getOfferName($conn,$companyID) ?></select>');
}
});
Here i call php function getOfferName but it is showing me output like this
enter image description here
<select name="" id=""><!--?php getOfferName($conn,$companyID) ?--></select>
You can do by below code
getdata.php
if($_POST['action'] == 1){
$companyID = $_POST['id'];
$sql="SELECT `id`, `offer_name`, `offer_discount` FROM `oiw_product_offers`
WHERE `company_id`='$companyID'";
if ($result=mysqli_query($conn,$sql)) {
$html = '';
while ($row=mysqli_fetch_assoc($result)) {
$html .= '<option value="'.$row['id'].'">'.$row['offer_name'].'</option>';
}
}
echo json_encode($html);
exit(0);
}
?>
Ajax Call to Get Data
$('.offerCheckBox').on('change', function() {
var id=$(this).data('id');
if (!this.checked) {
var sure = confirm("Are you sure want to remove offer ?");
this.checked = !sure;
}else{
$.ajax({
url: "getdata.php",
type: 'POST',
data: {id:id,action:1},
dataType: "json",
contentType: false,
cache: false,
processData: false,
success: function(response) {
if (response) {
$(this).parent().parent().append('<select name="" id="">'+response+'</select>');
} else {
//Error
}
return true;
}
});
}
});
the JavaScript file is on the client side writing code in this file will not will not create a server call that runs the PHP file.
if you want to combine JavaScript with a server call you should use ajax.
JavaScript:
$('.offerCheckBox').on('change', function() {
var id=$(this).data('id');
if (!this.checked) {
var sure = confirm("Are you sure want to remove offer ?");
this.checked = !sure;
} else {
let fd = new FormData();
let companyID = $(this).val();
fd.append('companyID', companyID);
$.ajax
({
url: "getOffer.php",
type: "POST",
data: fd,
processData: false,
contentType: false,
complete: function (results) {
let response = JSON.parse(results.responseText);
my_function.call(this, response);
}
});
}
});
// in this function you will put the append of the select box that php has created
function my_function(response) {
console.log("response", response);
}
PHP code (the file name is : getOffer.php)
<?php
$companyID = $_REQUEST['companyID'];
$options = array[];
$sql="SELECT `id`, `offer_name`, `offer_discount` FROM `oiw_product_offers`
WHERE `company_id`='$companyID'";
if ($result=mysqli_query($conn,$sql)) {
while ($row=mysqli_fetch_assoc($result)) {
$options[$row['id']] = $row['offer_name'];
}
}
$resBack = (json_encode($options, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
echo ($resBack);
?>
Now in the callback function my_function as we wrote above you have an array of key value pair from the PHP.
iterate on this array in JavaScript build your option select items and append them to the select box.

AJAX request working, but no data inserted in to database

I tried to insert data into database by using ajax and php. However, I have no idea why it is not working. I have tested the html file, all the itemName, category, price are valid and the php file return me "success" just the data inserted to database is empty.
$(document).ready(function(){
var url = "http://domain/addProduct.php?callback=?";
$("#addProduct").click(function() {
var itemName = $("#itemName").val();
var category = $("#select_category").val();
var price = $("#price").val();
var dataString = "$itemName=" + itemName + "&category=" + category + "&price=" + price + "&addProduct=";
if ($.trim(itemName).length > 0 & $.trim(category).length > 0 & $.trim(price).length > 0) {
$.ajax({
type: "POST",
url: url,
data: dataString,
crossDomain: true,
cache: false,
beforeSend: function() {
$("#addProduct").val('Connecting...');
},
success: function(data) {
console.log(data);
if (data == "success") {
alert("Successfully add item");
} else if(data="failed") {
alert("Something Went wrong");
}
}
});
}
return false;
});
});
<?php
header("Access-Control-Allow-Origin: *");
require("config.inc.php");
$name = mysql_real_escape_string(htmlspecialchars(trim($_POST['itemName'])));
$category = mysql_real_escape_string(htmlspecialchars(trim($_POST['category'])));
$price = mysql_real_escape_string(htmlspecialchars(trim($_POST['price'])));
$date = date("d-m-y h:i:s");
$statement = $pdo->prepare("INSERT INTO product(name, category, price, date) VALUES(:name, :category, :price, :date)");
$statement->execute(array(
"name" => $name,
"category" => $category,
"price" => $price,
"date"=>$date
));
if($statement)
{
echo "success";
}
else
{
echo "failed";
}
?>
replace this code:
dataString="$itemName="+itemName+"&category="+category+"&price="+price+"&addProduct=";
to:
dataString="itemName="+itemName+"&category="+category+"&price="+price+"&addProduct=";
and replace this code too:
if($.trim(itemName).length>0 & $.trim(category).length>0 & $.trim(price).length>0)
to:
if($.trim(itemName).length>0 && $.trim(category).length>0 && $.trim(price).length>0)
Because & is a Bitwise Operator But && is Logical Operator, So in this condition we always use logical operator.
You can't use date as your table column. date is a predefined/reserved keyword. Change the name of your date column into your database and modify your sql query and try again.

Ajax not submitting $_Post

I have this section of code that is suppose to get the Values of the input fields and then add them to the database. The collection of the values works correctly and the insert into the database works correctly, I am having issue with the data posting. I have narrowed it down to the data: and $__POST area and im not sure what I have done wrong.
JS Script
$("#save_groups").click( function() {
var ids = [];
$.each($('input'), function() {
var id = $(this).attr('value');
//Put ID in array.
ids.push(id);
console.log('IDs'+ids);
});
$.ajax({
type: "POST",
url: "inc/insert.php",
data: {grouparray: ids },
success: function() {
$("#saved").fadeOut('slow');
console.log('Success on ' + ids);
}
});
});
PHP Section
<?php
include ('connect.php');
$grouparray = $_POST['grouparray'];
$user_ID = '9';
$sql = "INSERT INTO wp_fb_manager (user_id, group_id) VALUES ($user_ID, $grouparray)";
$result=mysql_query($sql);
if ($result === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysql_error();
}
?>
You cannot send an array trough an ajax call.
First, use something like:
var idString = JSON.stringify(ids);
And use it: data: {grouparray: idString },
On the PHP side:
$array = json_decode($_POST['grouparray']);
print_r($array);

JQuery Ajax Error {"readyState":0,"responseText":"","status":0,"statusText":"OK"}

I try to get the cities according to the country which is passed as parameter and sent via ajax. But for some countries I can get cities and update my form with these cities, for against for other I have this error
{"readyState":0,"responseText":"","status":0,"statusText":"OK"}
When I look in logs for those countries that returns me an error I have the names of the cities retrieved from the database.
I do not understand why this error.
how can I fix it?
Please find below my code
Model
function get_ville_depart($country = null){
$this->db->select('NUMVILLEDEPART, NOMVILLEDEPART')->from('villedepart');
$this->db->join('pays','pays.NUMPAYS=villedepart.numpays');
$this->db->where('pays.NUMPAYS', $country);
$this->db->order_by("NOMVILLEDEPART","asc");
$query = $this->db->get();
$cities = array();
if($query->result()){
foreach ($query->result() as $city) {
$cities[$city->NUMVILLEDEPART] = $city->NOMVILLEDEPART;
}
return $cities;
}else{
return FALSE;
}
}
Controller
function get_ville_depart($country){
foreach($this->ville_model->get_ville_depart($country) as $ville){
log_message('debug',json_encode($ville));
}
header('Content-Type: application/json; charset=utf-8');
echo json_encode($this->ville_model->get_ville_depart($country));
}
View
$('#paysdepart').on("change",function(){
$("#villedepart > option").remove();
var country_id = $('#paysdepart').val();
var base_url="<?= site_url('annonce');?>";
$.ajax({
type: "GET",
url: base_url+"/get_ville_depart/"+country_id,
dataType:'json',
success: function(cities)
{
if(!jQuery.isEmptyObject(cities))
{
$("#ifnotvilledepartindatabase").hide();
$("#dynamicvilledepart").show();
$.each(cities,function(NUMVILLEDEPART,NOMVILLEDEPART)
{
var opt = $('<option />');
opt.val(NUMVILLEDEPART);
opt.text(NOMVILLEDEPART);
$('#villedepart').append(opt);
});
}else
{
$("#dynamicvilledepart").hide();
$("#ifnotvilledepartindatabase").show()
}
},
error:function(error)
{
alert("Error "+JSON.stringify(error));
$("#dynamicvilledepart").hide();
$("#ifnotvilledepartindatabase").show()
}
});
});
Error in those country which does not have any City.
if($query->result()){
foreach ($query->result() as $city) {
$cities[$city->NUMVILLEDEPART] = $city->NOMVILLEDEPART;
}
return $cities;
}else{
return new stdClass; /* Only this line have to change */
}
Use direct URL to see the error for the particuler Country ID.
I have tested in local everything if fine .
Everything seems fine to me, but here my guess about your code :
==> MAKE SURE THE COUNTRY ID IS NEVER EQUAL TO NULL
1 - in your Model, change this,
if($query->result()){
foreach ($query->result() as $city) {
$cities[$city->NUMVILLEDEPART] = $city->NOMVILLEDEPART;
return $cities;
}
else{
return FALSE;
}
to this :
if($result = $query->result_array())
$cities = array_column($result, 'NOMVILLEDEPART', 'NUMVILLEDEPART');
return $cities;
2 - in your Controller, change this :
function get_ville_depart($country){
foreach($this->ville_model->get_ville_depart($country) as $ville){
log_message('debug',json_encode($ville));
}
header('Content-Type: application/json; charset=utf-8');
echo json_encode($this->ville_model->get_ville_depart($country));
}
to this :
function get_ville_depart($country){
$countries = $this->ville_model->get_ville_depart($country);
return $this->output->set_content_type('application/json')
->set_output(json_encode($countries));
}
3 - In your View, Change this :
var country_id = $('#paysdepart').val();
to this :
var country_id = $(this).val();
Note : you can access directly to this page "http://{mywebsite}/get_ville_depart/{country_id}"
with {country_id} equal to the country ID you have a problem with, and check if everything's OK before using the Ajax Query.

best option to get php array variable in Javascript produced by php script that requested through an ajax call

Currently I am trying to create a live search bar that only produce 5 results max and more option if there is over 5 results. So what I have done so far is a jquery ajax script to call a php script that runs asynchronously on key up in textbox I have.
I want to get the php array then I will code it further using javascript.
This is my code now:
Javascript code
<script type="text/javascript">
function find(value)
{
$( "#test" ).empty();
$.ajax({
url: 'searchDb.php',
type: 'POST',
data: {"asyn": value},
success: function(data) {
return $lala;
var lala = $lala;
$( "#test" ).html($lala);
}
});
}
</script>
SearchDb PHP code:
<?php
function searchDb($abc, $limit = null){
if (isset($abc) && $abc) {
$sql = "SELECT testa FROM test WHERE testa LIKE '%$abc%'";
if($limit !== null){
$sql .= "LIMIT ". $limit;
}
$result = mysql_query($sql) or die('Error, insert query failed') ;
$lists = array();
while ( $row = mysql_fetch_assoc($result))
{
$var = "<div>".$row["testa"]."</div>";
array_push($lists, $var);
}
}
return $lists;
}
$abc = $_POST['asyn'];
$limit = 6;
$lala = searchDb($abc);
print_r($lala);
?>
How can I get $lala
Have you considered encoding the PHP array into JSON? So instead of just echoing the array $lala, do:
echo json_encode($lala);
Then, on the Javascript side, you'll use jQuery to parse the json.
var jsonResponse = $.parseJSON(data);
Then you'll be able to use this jsonResponse variable to access the data returned.
You need to read jQuery .ajax and also you must view this answer it's very important for you
$.ajax({
url: 'searchDb.php',
cache: false,
type: 'post'
})
.done(function(html) {
$("#yourClass").append(html);
});
In your searchDb.php use echo and try this code:
function searchDb($str, $limit = null){
$lists = array();
if (isset($str) && !empty($data)) {
$sql = "SELECT testa FROM test WHERE testa LIKE '%$data%'";
if(0 < $limit){
$sql .= "LIMIT ". $limit;
}
$result = mysql_query($sql) or die('Error, insert query failed') ;
while ( $row = mysql_fetch_assoc($result))
{
$lists[] = "<div>".$row["testa"]."</div>";
}
}
return implode('', $lists);
}
$limit = 6;
$data = searchDb($_POST['asyn'], $limit);
echo $data;
?>
If you dont have or your page searchDb.php dont throw any error, then you just need to echo $lala; and you will get result in success part of your ajax function
ALso in your ajax funciton you have
//you are using data here
success: function(data) {
return $lala;
var lala = $lala;
$( "#test" ).html($lala);
}
you must try some thing like this
success: function(data) {
var lala = data;
$( "#test" ).html($lala);
}

Categories

Resources