I have a problem in my script.
I have a loop in php who show this in html, this work good :
<?php foreach ($locations as $key => $value) : ?>
<div class="storelocator-info" data-id="<?= $value['codepostal']; ?>"
style="display: block;">
<p class="title-depot"><?= $value['name']; ?></p>
</div>
<?php endforeach ; ?>
Now i have a searchbar who i enter a zip code like 11 or 11111 send in ajax in my controller, i return the result in json format like this :
try {
jQuery.ajax({
url: url,
dataType: 'json',
type: "POST",
data: form.serialize(),
success: function(data) {
if (data['success'] === false){
var index;
var a = data.zip;
for (index = 0; index < a.length; ++index) {
jQuery('.storelocator-info').hide();
jQuery('.storelocator-info[data-id='+a[index]+']').show();
}
jQuery('.storelocator-error').hide();
} else{
jQuery('.moulinroty-loader').hide();
jQuery('.storelocator-info').hide();
jQuery('.storelocator-error').fadeToggle();
}
}
});
} catch (e) {
console.log('error' + e);
}
data.zip is an array like this ['85000,85001'];
I want to show only "" where data.zip == data-id attribute with javascript or jquery .
the result show only the last result in my array with data-id = 85001,
so i want to show 85000 and 85001
can you explain me where is my mistache or error please?
Thank for help
You are hiding all elements in every iteration of your loop. Hide them before and then show those which need to be shown:
var a = data.zip;
jQuery('.storelocator-info').hide();
for (var index = 0; index < a.length; ++index) {
jQuery('.storelocator-info[data-id=' + a[index] + ']').show();
}
Related
I have a problem wherein I cannot put the data inside select element and make an option using the ID to append on what is inside my ajax. I got the data and it is showing in an input element but when I switched it into select element it doesn't work.
Here is the image of my form
JQuery / Ajax code
function ToolsChange(element) {
let tools_id = $(element).val();
if (tools_id) {
$.ajax({
type: "post",
url: "form_JSON_approach.php",
data: {
"tools_id": tools_id
},
success: function(response) {
var dataSplit = response;
console.log(response);
var shouldSplit = dataSplit.split("#");
var shouldNotSplit = dataSplit.split();
console.log(shouldSplit);
console.log(shouldSplit[0]);
console.log(shouldSplit[1]);
console.log(shouldSplit[2]);
$("#sel_control_num").val(shouldSplit[0]);
var specs = [];
for (i = 1; i < shouldSplit.length; i += 3) {
specs.push(shouldSplit[i])
}
$("#sel_tools_spec").val(specs.join(', '));
$("#sel_tools_id").val(shouldSplit[2]);
}
});
}
}
HTML code(I had to comment select element because it is not showing the data)
<div class="form-group">
<label> Tools Specification: </label>
<input id="sel_tools_spec" class="form-control" name="tools_specification"
data-live-search="true" readonly>
<!-- <select id="sel_tools_spec" class="form-control selectpicker" data-live-search="true">
</select> -->
</div>
PHP code
<?php
include("../include/connect.php");
if(isset($_POST['tools_id'])){
$ID = $_POST['tools_id'];
$query = "SELECT tools_masterlist.control_no, tools_masterlist.tools_id,
tools_masterlist.tools_name,
tools_spec.model_num,tools_spec.model_num_val, tools_spec.status
FROM tools_masterlist LEFT JOIN tools_spec ON tools_masterlist.tools_id = tools_spec.tools_id
LEFT JOIN tools_registration ON tools_masterlist.control_no = tools_registration.reg_input
WHERE status = 1 AND tools_name = '$ID'";
$con->next_result();
// $result=mysqli_query($con, "CALL GetAjaxForToolsRegistration('$ID')");
$result=mysqli_query($con, $query);
if(mysqli_num_rows($result)>0)
{
while($row = mysqli_fetch_assoc($result))
{
// echo $row['control_no'] . "#" . $row['model_num'] . "#" . $row['tools_id'] ."#";
echo $row['control_no'] . "#" . '<option value="'.$row['tools_id'].'">'.
$row['model_num'] .'</option>' . "#" . $row['tools_id'] ."#";
}
}
else
{
}
}
?>
Don't need to split() or even return your response using echo ... #... #... .. Ok here is what you should do
The main idea in my code is: returning all the data from php/database
then control it in js/ajax and this will happen by using dataType : 'json' and echo json_encode($data)
in php
$return_result = [];
if(mysqli_num_rows($result)>0)
{
while($row = mysqli_fetch_assoc($result))
{
$return_result[] = $row;
}
}
else
{
$return_result['error'] = 'error';
}
echo json_encode($return_result);
in javascript (ajax)
$.ajax({
type: "post",
url: "form_JSON_approach.php",
dataType : 'json', // <<<<<<<<<<< here
data: {
"tools_id": tools_id
},
success: function(response) {
if(!response.error){
//console.log(response);
$.each(response , function(index , val){
// here you can start do your stuff append() or anything you want
console.log(val.control_no);
console.log(val.tools_id);
});
}else{
console.log('You Have Error , There is Zero data');
}
}
});
You are appending all datas at onces instead inside for-loop you can directly append options inside your selectpicker and refresh it.
Demo Code :
$("#sel_tools_spec").selectpicker() //intialize on load
ToolsChange() //just for demo..
function ToolsChange(element) {
/*let tools_id = $(element).val();
if (tools_id) {
$.ajax({
type: "post",
url: "form_JSON_approach.php",
data: {
"tools_id": tools_id
},
success: function(response) {*/
//other codes....
$("#sel_tools_spec").html('');
//suppose data look like this...
var shouldSplit = ["1", "<option>A</option>", "1001", "2", "<option>B</option>", "1001"]
for (i = 1; i < shouldSplit.length; i += 3) {
//append options inside select-box
$("#sel_tools_spec").append(shouldSplit[i]);
}
$("#sel_tools_spec").selectpicker('refresh'); //refresh it
/* }
});*/
}
<link rel="stylesheet " type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/css/bootstrap-select.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/js/bootstrap-select.min.js"></script>
<div class="form-group">
<label> Tools Specification: </label>
<select id="sel_tools_spec" class="form-control selectpicker" data-live-search="true">
</select>
</div>
Since you are using bootstrap. Just do the following
$("#sel_tools_spec").empty().append('<option value="ID">LABEL</option>').selectpicker('refresh');
Source: how to append options in select bootstrap?
<script>
$("#submit").click(function () {
var newhour= [];
for (var i = 0; i < arrayNumbers.length; i++) {
newhour.push(arrayNumbers[i].toString().split(','));
console.log("each: " + newhour[i]); // output: each: 07:00,08:30
each: 18:00,19:00
}
console.log("all: " + newhour); //output: all: 07:00,08:30,18:00,19:00
var jsonString = JSON.stringify(newhour);
$.ajax({
type: "POST",
url: "exp.php",
data:{data: jsonString},
cache: false,
success: function(){
alert("OK");
}
});
});
<script>
I want to pass the newhour array values to php and use them to insert into a table.
so php file, exp.php:
$data = explode(",", $_POST['data']);
foreach($data as $d){
echo $d;
$sql = "insert into exp_table (hour) values ('$d')";
mysql_query($sql);
}
However I can not take the values. What is wrong with the code?
Could you please help me?
Thanks in advance.
according to the answers i tried this on php side, but it returns NULL.
$data = json_decode($_POST['data'],true);
//$data = explode(",", $_POST['data']);
echo "data: " .$data;
var_dump($data); // no output
foreach($data as $d){
echo $d; // no output
}
You do not have to stringify an array in the javascript.
.ajax looks after all that.
pass
data: {newhours: newhour},
then you will get $_POST['newhours'] in the PHP code which will be the array you had in javascript.
In Ajax there is not "type" params, use "method".
Beside that everything should works, you might need to decode the json using json_decode($_POST['data']) on in your php file.
Hopes it helps !
Nic
Pass the array without JSON.stringify in ajax data post. And fetch the data in php file using $_POST['data'].
I just have tried below code and it working great.
<?php
if(isset($_POST['data'])){
print_r($_POST);exit;
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
var newhour= [];
arrayNumbers = [['07:00','08:30'],['08:30','18:00','19:00']];
for (var i = 0; i < arrayNumbers.length; i++) {
newhour.push(arrayNumbers[i].toString().split(','));
console.log("each: " + newhour[i]);
// output: each: 07:00,08:30 each: 18:00,19:00
}
console.log("all: " + newhour); //output: all: 07:00,08:30,18:00,19:00
$.ajax({
type: "POST",
url: "abc.php",
data:{data: newhour},
cache: false,
success: function(data){
console.log(data);
}
});
});
</script>
I have the following code, which is a restful json api.
// Program guide Rest
$(document).ready(function() {
$.ajax({
cache: false,
url: "http://engridmedia.com/next/api/epg/scheduler/id/200",
type: 'GET',
crossDomain: true,
dataType: 'json',
success: function() {
alert("EPG Success");
},
error: function() {
alert('EPG Failed!');
},
})
.then(function(data) {
for (var i = 0; i < 6; ++i)
{
var prefix = (i == 0 ? "" : i.toString());
$('.programtitle' + prefix).append(data[i].program_title);
$('.ch-start' + prefix).append(data[i].start_time);
$('.ch-end' + prefix).append(data[i].end_time);
$('.ch-programdesc' + prefix).append(data[i].desc);
}
});
I want to use the data in my phonegap html . that means i would have to call each data by doing this a bunch of times since i will have over 20 data in the array and sometimes less. is there a for each loop in javascript to do this easily like echoing data from the database in php?
<?php foreach ($query as $row)
{ ;?>
<h3><?php echo $row -> program_title; ?> | <?php echo $row -> start_time; ?> | <?php echo $row -> end_time; ?></h3>
<div>
<p>
<?php echo $row -> desc; ?>
</p>
</div>
<?php } ?>
As ja408 sayed you should use this syntax in javascript :
for(var k in yourJson) {
console.log(k, result[k]);
}
Thanks
Hello i have this code server side to show online users:
header('Content-Type: application/json');
$array = array();
include 'db.php';
$res = mysqli_query($db, "SELECT * FROM `chatters` WHERE status = 1");//users are online
if(mysqli_num_rows($res) > 0){
while($row = mysqli_fetch_assoc($res)){
$array[]= $row; }
}
echo json_encode($array);
As response i get this:
[{"row_id":"40","name":"Krishan kumar","sex":"male","age":"24","country":"India","seen":"20:58:14", "status": "1"}]
So i on the show page i have this code to show the users:
$(document).ready(function() {
setInterval(function(){
$.ajax({
url: 'json.php',
dataType: "json",
type: 'GET',
success: function(data) {
if (data) {
var len = data.length;
var txt = "";
for (var i = 0;i<len; i++) {
txt += "<p>"+data[i].name + "</p>";
}
$(".showUsers").append(txt);
console.log(txt);
}
}
});
}, 2000);
});
But the problem is in every 2 second i get name printed like this:
Krishan kumar
Krishan kumar
Krishan kumar
Krishan kumar
and it continues....
I want to show the users name printed only one time while still opening the request with setinterval() to check if new users are online. How to fix this issue?
Please clear previous user list before append new list. Use following code
setInterval(function(){
$(".showUsers").html('');
$.ajax({ ....
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");