Getting the output but also getting undefined first in AJAX - javascript

I have a dropdown and when it's changed then I am calling the ajax depending upon the dropdown value. If the dropdown value is 2 then it will call the ajax and display the data.
Now my issue is, 1) I am getting the output but also i am getting undefined.
2) After getting the output I have to display inside if-else condition but it's only displaying undefined.
Controller
public function getRMname(){
$result= $this->Employee_model->getRMname();
if($result)
{
foreach ($result as $key => $value) {
$data[] = array('rmfirstname' =>$value->firstname , 'rmlastname'=>$value->lastname,'rmid'=>$value->id);
}
}
else
{
$data = "false";
}
echo json_encode($data);
}
Script
$(document).on('change', '.pp_Status', function(event) {
var addrm;
if ($(this).val() == '2') {
$.ajax({
type: "POST",
url: baseUrl + "/Employee_control/getRMname",
//data: {},
dataType: 'json',
success: function(response) {
addrm += '<select name="addrm" class="input-wrapper"><option value="" selected disabled>Select</option>';
$.each(response, function(key, data) {
addrm += '<option value="' + data.rmid + '">' + data.rmfirstname + ' ' + data.rmlastname + '</option>';
});
addrm += '</select>';
}
});
} else {
addrm = '';
}
if (somecondition) {
} else {
echo addrm;
//displaying addrm variable here
}
});

use =''; in defing variable
var addrm=''; instead of
var addrm;
beacause Variable means anything that can vary, you should have to first declare empty String and then after String Concatenate with += symbol.

To be on the safe side, define the variable as
var addrm = '';
Take out the else state so it only runs when selected option is 2.
Finally, the block which checks if selected option is 2 gets executed irrespective of the selected option because you aren't targeting properly.
It should be:
if( $(this).find(':selected').val() == '2' ) {}
Because what you have there doesn't check for the selected value, try console logging to check the value returned:
console.log($(this).find(':selected').val());

Related

How to display data value in real time without refreshing the page with PHP/Javascript?

This is a survey system. I have a dynamic dropdown that displays one column 'questiontitle' from my table database. How do I display its other columns 'Option_1 to Option_10' (I assumed the maximum options are 10), depending on the 'answer_type' column when it's clicked in real time without refreshing the page? Like if it the 'answer_type' is checkbox it will display it as checkbox and if it's radiobutton it will display radiobuttons. Here's my code of displaying the 'question_title' in the dropdown
$query=mysqli_query($con, "SELECT question.* FROM question LEFT JOIN category AS subcategory on subcategory.category_id = question.question_subcat WHERE question.question_category = $question AND (question.question_subcat IS NULL OR subcategory.category_id IS NOT NULL)");
echo "<b id='labelquestion_dropdown".$i."'>Question #". $i."</b>";
echo "<select id='question_dropdown".$i."' class='form-control-static' name='question_dropdowns".$i."'>";
echo "<option selected>"; echo "Select"; echo "</option>";
while($row=mysqli_fetch_array($query))
{
echo "<option value='$row[question_id]'>";
echo $row["questiontitle"];
echo "</option>";
}
echo "</select>";
echo "<br />";
And here's my database table.
Do some thing like this.
<script>
$.ajax({
url:'ajax.php?id=<?php $row['id']; ?>',
success:function(data){
if(data){
// do what ever you want to do
}
}
});
</script>
on AJAX.php
First you get record against this id that you send in ajax url.
prepare your desired result
Use Ajax Technology then do this in your JS
$(document).on('change','.dynamic-qst',function(){
// ajax question possible answers or rather ajax your database where id = question id
/* $.ajax({
url: 'getPossibleAnswers.php',
data: {id: $(this).val()},
success: function(response){
//insert the var output = '';
// to $('#possible-ans').html(output);
}
}) */
// assuming we had successfully ajax it and the response is
// for question 1 example
var response2 = {'answer_type':'checkbox', 'option_1':'Cellphone', 'option_2':'Computer', 'option_3':'Laptop', 'option_4':'', 'option_5':'', 'option_6':'', 'option_7':'', 'option_8':'', 'option_9':'', 'option_10':''};
// for question 2 example
var response = {'answer_type':'radio', 'option_1':'Sushi', 'option_2':'Maki', 'option_3':'Sashimi', 'option_4':'Teriyaki', 'option_5':'Misono', 'option_6':'', 'option_7':'', 'option_8':'', 'option_9':'', 'option_10':''};
var output = '', x;
for(x = 1; x <= 10 ; x++)
{
var cur_ans = eval("response.option_" + x);
if(response.answer_type == 'checkbox')
{
if(cur_ans != '')
{
output += '<input type="checkbox" name="ans" value="' + cur_ans + '">' + cur_ans;
}
}
else if(response.answer_type == 'radio')
{
if(cur_ans != '')
{
output += '<input type="radio" name="ans" value="' + cur_ans + '">' + cur_ans;
}
}
}
$('#possible-ans').html(output);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="dynamic-qst">
<option value selected disabled>-- Select One --</option>
<option value="1">What gadget do you usually use?</option>
<option value="2">What is your favorite food?</option>
</select>
<div id="possible-ans"></div>

How to convert an object from PHP to an Array in Javascript?

I'm trying to convert an object that I get from PHP into an array in Javascript but I don't know how to solve this, I try some solutions I read before do this question but it doesn't work, I got something like this in PHP
$data = explode(',', $articles);
$length = count($data);
for ($i = 0; $i < $length; $i++) {
$products = explode('-', $data[$i]);
$product_key = $products[0];
$quantity = $products[1];
$get_data_product = mysqli_query($connection, "SELECT * FROM articles WHERE id_article = '".$product_key."' AND id_user = '".$id_user."'") or die (mysqli_error($connection));
$get_data_product = mysqli_fetch_assoc($get_data_product);
$article_name = $get_data_product['name'];
$article_price = $get_data_product['price'];
$info[$i] = array('name' => $article_name, 'quantity' => $quantity, 'price' => $article_price);
}
echo json_encode($info);
And in Javascript
success: function(info) {
var data = JSON.stringify(info);
console.log(data);
}
Console log show this
[{"name":"prueba 2","quantity":"4","price":"100"}]
I tried to read them all with ths code but it is showing data, only when I use console log or alert
$.each(data, function(i) {
$('#content').append('<tr class="text-center">' +
'<td>' + data[i].quantity + '</td>' +
'<td>' + data[i].name + '</td>' +
'</tr>');
});
As prodigitalson notes in the comments - and is effectively the answer - you converted your data into a JSON object in PHP, but then convert it needlessly into a string, so you then can't manipulate it at all.
E.g: JSON.stringify([{test: 1}]) becomes "[{test: 1}]".
Removing that, you will then be able to loop on it in your original way, or you can loop on it using a standard javascript foreach where data is your response in your callback containing [{"name":"prueba 2","quantity":"4","price":"100"}]:
data.forEach(function (e) {
$('#content').append(
'<tr class="text-center">\n' +
'<td>' + e.quantity + '</td>\n' +
'<td>' + e.name + '</td>\n' +
'</tr>\n'
);
});
PHP End Sample Code:
<?php
for ($i = 0; $i < 3; $i++) {
$quantity=rand(5,10);
$price=rand(500,1000);
$info[$i] = array('name' =>'prueba'.$i, 'quantity' =>"$quantity", 'price' => "$price");
}
echo json_encode($info);
?>
JQuery End:
<!DOCTYPE html>
<html>
<head>
<title>Json</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({ type:"POST", url: "array.php", dataType: "json", success: function(result){
console.log(result);
for(i=0; i<result.length;i++)
{
console.log(result[i]);
console.log(result[i].name);
console.log(result[i].quantity);
console.log(result[i].price);
}
}});
});
</script>
</head>
<body>
</body>
</html>
Sample Response in the test:
[{"name":"prueba0","quantity":"8","price":"574"},{"name":"prueba1","quantity":"8","price":"555"},{"name"
:"prueba2","quantity":"7","price":"901"}]
Reference :
http://www.jsoneditoronline.org/?id=5e23cd942a949e86545fa320a65ff0e7
Hope this solves your problem. Thanks.
I think your code is fine, if you do this in javascript code:
success: function(info) {
var data = JSON.stringify(info);
alert(data[0].name);
}
That alert should show the expected value of name property of data object.
your console.log(data); show json arry that is
[{"name":"prueba 2","quantity":"4","price":"100"}]
try this
$dataobj = data1=json_decode(data);
$arry = (array) $dataobj;
try this code

Cant get PHP value in jquery

my Php code;
$sql = "SELECT * FROM login_speak";
if ($result = mysqli_query($con, $sql))
{
$resultArray = array();
$tempArray = array();
while($row = $result->fetch_assoc())
{
$tempArray[] = $row;
}
$resultArray = json_encode($tempArray);
echo $resultArray;
}
mysqli_close($con);
?>
my jquery code;
$.getJSON("url.php", function(data){
$("ul").empty();
$.each(data.result, function(){
$("ul").append("<li>Name:"+this['Name']+"</li>");
alert("kj");
});
});
I have done several things ,But nothing works.I php is correct and I have problem in script ,I guess.
Please give me the answer ,What wrong is done.
Thanks
json_encode from php can be accessed easily in a Javascript varible
There are many ways of doing this, however consider the simple way first if it works with the array you are sending.
in your example - assuming jquery:
var valu = [];
$.ajax(url: "url.php",
success: function(data){
valu=data;
});
see: http://www.dyn-web.com/tutorials/php-js/json/array.php
works for numeric and associative arrays.
I think you want change your code to something like this..
$.each(data.result, function(index,value){
$("ul").append("<li>Name:"+value.name+"</li>");
alert("kj");
});
Heres what I would do.
$.ajax({
url: "url.php",
type: "GET",
dataType: 'json'
}).done(function (data) {
$.each(codes, function(key,value){
$("ul").append('<option value="' + key + '">' + key + ' - ' + value + '</option>');
});
}).fail(function (jqXHR, textStatus, error) {
alert("error message");
console.log("error message: " + error);
});

return multiple values from php to jquery

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");

No response from jQuery .post even though PHP is returning correct data

Here is my jQuery:
function SelectSubCats(cat_num) {
console.log("Select SubCats..");
$.post("ajax.php", {
_populateSubCats : 1,
cat_num : cat_num
},
function(data){
console.log("Data: " + data );
});
}
I am not reaching the console.log statement is the problem.
in ajax.php:
else if(array_key_exists('_populateSubCats', $_POST)) { // {{{
$cat_num = $DB->escape($_POST['cat_num']);
print GetSubCats($cat_num);
} // }}}
function GetSubCats($cat_num) {
global $DB;
$returnHTML = '';
$query = "SELECT sc_i_num, sc_s_subcategory FROM subcat "
. "WHERE sc_i_c_num = {$cat_num} "
. "ORDER BY sc_s_subcategory";
$result = $DB->query($query);
$returnHTML .= "<option value=''></option>";
while($obj = $DB->next($result)) {
$returnHTML .= "<option value='{$obj->sc_i_num}'>{$obj->sc_s_subcategory}</option>";
}
return $returnHTML;
}
The return generates <option>s for a <select>. The idea is, there are categories and subcategories. The jQuery function above is called in the onchange of the category <select>. Eventually I'd like to replace that console.log with an append to add the new data to the sub-category select. But right now, I am just trying to get a response. I have logged the php side and am getting the exact response I need. What else is going on?
Specify the type of response you want by adding , 'html'.
i.e.:
function SelectSubCats(cat_num) {
console.log("Select SubCats..");
$.post("ajax.php", {
_populateSubCats : 1,
cat_num : cat_num
},
function(data){
console.log("Data: " + data );
}, 'html' );
}

Categories

Resources