GET-variable called brand.
A few hours ago when I had not implemented the ajax search box, everything worked fine.
The js part looks like this:
$('.mutliSelect input:checkbox').change(function() {
var brand = $("#brand_select input:checkbox:checked").map(function() {
return this.value;
}).get().join(',');
$(".submit_checkboxes").find("a").attr('href', 'index.php?brand=' + brand);
}).change();
Now, having implemented the ajax search box, the var brand does not seem to get filled with any value anymore.
This is the corresponding part of index.php:
<div class="mutliSelect" id="brand_select">
<ul>
<div class="search_view">
<section class="drop_search">
<input type="text" placeholder="Suche" id="search_brand" name="search_brand">
</section>
</div>
<div id="results">
//ajax-php result gets posted in here
</div>
<div class="button submit_checkboxes_button submit_checkboxes">
<a href""><span>Anwenden</span></a>
</div>
</ul>
</div>
and this is a part of search.php (this is the script that is called by ajax and posts the results):
$result = mysql_query($query);
while($brand = mysql_fetch_array($result)){
echo
'<li><input type="checkbox" id="'.$brand['Brand'].'" value="'.$brand['Brand'].'"'; if(strpos($_SESSION['brand'],''.$brand['Brand'].'') !== false){ echo 'checked="checked"';} echo' />
<label for="'.$brand['Brand'].'" class="checkbox_title">'.$brand['Brand'].'</label></li>';
It seems like the very last two lines (everything between <li></li> tags) does not get "noticed" by the upper js-function. When I put exactly these <li></li> tags into index.php - along with all php parts - however, it works fine.
Please let me know if this is clear.
Does anybody have an idea on how to fix this issue?
Thank you!
ajax call:
$(document).ready(function() {
// Live Search
// On Search Submit and Get Results
function search() {
var query_value = $('input#search_brand').val();
$('b#search-string').text(query_value);
$.ajax({
type: "POST",
url: "php/search_brand.php",
data: { query: query_value },
cache: false,
success: function(html){
$("div#results").html(html);
}
});
}
[...]
Related
I am trying to make a form page in adding new client in a database. The form consist of a selection tag that has options for adding house number. But there are circumstances like house number is not yet placed on the database, so I decided to create a button for adding new house no (using modals).
Form:
<div class="col-md-3 form-group" id="autoload">
<label>
Household: <a data-toggle="modal" data-target="#addHousehold"
style="cursor: pointer; text-decoration: none;">
<i class="fa fa-plus" >Add</i></a>
</label>
<select class="form-control select2" style="width: 100%;">
<option selected="selected">Select Household</option>
<?php foreach($result3 as $row): ?>
<option><?=$row['house_no']?></option>
<?php endforeach ?>
</select>
</div>
Script for adding new house number, and refresh the selection when new house number is successfully added:
$('#addHouseholder').click(function(){
var householder = $('.householder').val()
var street = $('.strsel1').val();
$.ajax({
method: "POST",
url: "insert.php",
data: {householder:householder,street1:street}
}).then(()=>{
$("#autoload").load(" #autoload");
alert('Household Added')
})
This function successfully, the only problem is the division of the selection is deformed. I also forgot to say that I reload the div, but I wonder if it is possible to just reload the selection. I am not sure how to execute this. Looking forward for your help. Thank you very much!
Are you using select2 (https://select2.org/)?
If so, you can use the ability to programmatic control the select.
https://select2.org/programmatic-control/add-select-clear-items
By using:
var data = {
id: 1,
text: 'Barn owl'
};
var newOption = new Option(data.text, data.id, false, false);
$('#mySelect2').append(newOption).trigger('change');
You could return the option in the ajax response and populate the select.
You just need to echo json format of your data in insert.php file then modify your js script to
$.ajax({
type: "POST",
url: "path/insert.php",
data: {householder:householder,street1:street},
success: function(data){
// Parse the returned json data
var opts = $.parseJSON(data);
// Use jQuery's each to iterate over the opts value
$.each(opts, function(i, d) {
// You will need to alter the below to get the right values from your json object. Guessing that d.no / d.anyOtherInfo are columns in your data
$('#autoload').children(".orm-control.select2").append('<option value="' + d.no + '">' + d.anyOtherInfo + '</option>');
});
}
});
Good luck.
Edit 1: adding source.
check Populate Select box options on click with Javascript/Jquery with Json data
In my project, sheet processing data will be append to a timeTagDiv div(just like A and B are talking, and the content will show in the dialog).The new message send to dialog will append to timeTagDiv div. After that I want the whole timeTagDiv html content stores in the DB with ajax. Next time, these dialogue content will show in the div, So I konw what is going on.
Here is my js code:
var newCnt="<span class='dlgRsp'><label id='dlgRspTime'></label> <label id='dlgCharge'></label> accept sheet</span><br />";
$('#timeTagDiv').append(newCnt);
//var tmTgDvHtml=$('#timeTagDiv').innerHTML;
var tmTgDvHtml=document.getElementById("timeTagDiv").innerHTML;
var slcId = 2;
$.ajax({
dataType:'json',
type:"POST",
url:"get_ajax_csc.php",
data: {slcId:slcId,htmlCnt:tmTgDvHtml},
success:function (data)
{}
});
Here is my html code:
<div class="timeTag" id="timeTagDiv">
<span class="dlgDate" id="firDlgDate"></span><br />
<span class="dlgStTrl"><label id="dlgTime1"></label> <label id="dlgPrpsr"></label> create new sheet</span><br />
<div id="dlgDiv1"></div><br />
</div>
Here is get_ajax_csc.php code:
<?php
include ("DB.php");
if(isset($_POST['htmlCnt']))
{
$sql="update IDC SET shProcess='".$_POST['htmlCnt']."' where id='".$_POST['slcId']."';";
$sel = $conn->exec($sql);
}
?>
But unfortnately, these date of timeTagDiv can not be updated. I have tested that tmTgDvHtml=document.getElementById("timeTagDiv").innerHTML can get the div html content.But i have no idea about that. Who can help me ?
The div contect of htmlCnt should be formatted by stripslashes()
$htcnt=stripslashes(".$_POST['htmlCnt'].");
It works fine.
Can someone tell me why this code don't work? I am trying post a value from form in a php file that make a select in my DB using this value. Return a Json array to ajax and print all results.
SELECT query:
...
$sql= "SELECT * FROM incidente WHERE (titulo LIKE '%':buscar'%' OR
descricao LIKE '%':buscar'%')";
...
$recebeConexao->bindParam(':buscar', $_POST['busca'],
PDO::PARAM_STR);
HTML code:
//here I am creating a form whit text input and a button that call
the function enviar()
<form id="buscar">
<input id="busca" name="busca" type="text"
placeholder="Buscar incidente" />
<input onclick="enviar()" type="button" value="ok" />
</form>
//creating a array that will receive values from SQL consult
<div id="content" class="content">
<article class="underline">\
<a href="incidente.html"><img id="incidente"\
src="img/buraco.jpg" alt="Incidente" /></a>\
<h2>'+tit+'</h2>\
<p id="desc">'+desc+'</p>\
<div class="date" id="date">'+dateVal+'</div>\
<img class="tick" alt="não resolvido" src="img/no-tick.png">\
<img class="apoio" alt="apoiar" src="img/apoio.png">\
</article>'
</div>
Function enviar():
<script>
function enviar(){
function viewData(data, el) {
var content='';
for (var i in data) {
var tit =data[i].titulo;
var desc =data[i].descricao;
var dateVal=data[i].data;
content+= '<article class="underline">\
<a href="incidente.html"><img id="incidente"\
src="img/buraco.jpg" alt="Incidente" /></a>\
<h2>'+tit+'</h2>\
<p id="desc">'+desc+'</p>\
<div class="date" id="date">'+dateVal+'</div>\
<img class="tick" alt="não resolvido" src="img/no-tick.png">\
<img class="apoio" alt="apoiar" src="img/apoio.png">\
</article>';
}
$('#'+el).html(content);
}
$(function(){
$.ajax({
var formula = $('#buscar').serialize();
type: "POST",
data:formula,
url: "http:/ip/connect/www/buscar.php",
dataType: "json",
success: function (data) {
viewData(data,'content');
}
});
});
}
</script>
I am receiving the error: enviar is not defined...
First, the variable content is not properly formatted, where you do the concatenation. Second, it looks like you also have mismatched braces. Third, $.ajax() should take key/value pairs to set up the AJAX request you are trying to make, but you have a variable declaration. You should recheck your whole code.
I'm trying to figure out if what I'm doing is the right way. I have a comment form and when it gets clicked I'm appending the comment into a div element through Ajax. When the page is refreshed then of course that would disappear and instead of it I have a foreach loop that runs and echos the comments. Since they both have the same CSS attributes they look the same to the user. The reason I'm doing it this way is because the foreach loop gets updated only after a refresh. Is there a better way? Can I update the page directly from the database without refresh? I basically need that every time a user clicks on the comment button that the foreach loop will run again but I couldn't find how to do it. I feel like I'm covering a gun shot with bandage the way I do it at the moment.
Loop:
#foreach($comment as $comments)
#if($comments->image_id == $image->id)
<div id="{{$comments->id}}" class="col-md-5 ajaxrules">
<div class="deletecomment">
<i class="fa fa-trash-o"></i>
</div>
<div class="col-md-2">
<img src="{{$comments->user_avatar}}" class="img-circle buddy">
</div>
<div class="hello col-md-10">
<h4>{!! $image->user_name !!}</h4>
<p class="left">{!!$comments->body!!} </p>
</div>
</div>
#endif
#endforeach
//Where I append the comments through Ajax until the refresh that replaces it with the loop
<div class="man">
</div>
Ajax:
<script>
$(document).ready(function(){
$('.send-form').click(function(e){
e.preventDefault();
var username = "{{ $username }}";
var one = $('textarea[id="{{$image->id}}"]').val();
var value = "{{$image->id}}";
var begin = '<div class="col-md-5 addavatar">'+'<div class="deletecomment">'+'<i class="fa fa-trash-o">'+'</i>'+'</div>'+'<div class="col-md-2">'+'<img src="{{$profile}}" class="img-circle">'+'</div>'+'<div class="hello col-md-10">'+'<h4>' + username +'</h4>'+'<p>'+one+'</p>'+'</div>'+'</div>';
if(one.length > 0){
console.log(username);
$('textarea[id="{{$image->id}}"]').val('');
$.ajax({
url: 'comment',
type: "post",
beforeSend: function (xhr) {
var token = $('meta[name="csrf_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
data: {'id': value, 'comment': one},
success:function(data){
$( ".man" ).append([begin]);
},error:function(){
console.log("error!!!!");
}
});
}
});
});
</script>
You are killing yourself.
Manipulate the DOM via javascript code like you do it's really hard work!
You are not suppose to write html inside javascript strings, there must be another way!
And there is... Welcome to AngularJS!
In angular you can write your html and assign a javascript controller to it, perform ajax request and after the ajax complete you can bind the returned data to the html automatically! That means the angular refresh your html and do all the work for you. Even perform loop of let's say, row in a table, etc...
I need to call some python function and show its results (actually a couple of list objects) in the div id="places" section. I'm trying to do this in Javascript function show_sec() but i can't find out how to catch the data from server and process it on client.
My task is really simple and basic but since it's my first web project I need some help with ajax. Please, help me.
This is a part of my code:
.html
{% include "header.html" ignore missing %}
<!-- contents of nearest banks page -->
<section id="ask_user">
<div id="question">Разрешить приложению определить Ваше место расположения для нахождения ближайших банков?</div>
<div id="buttons">
<input type="button" name="yes" value="Да, разрешить" onclick="show_sec()"/>
<input type="button" name="no" value="Нет, не разрешать" onclick="dnt_show_sec()"/>
</div>
</section>
<section id="allowed" style="display:none;">
<div id="map_canvas"></div>
<div id="nearest_banks">
<form action="/nearest_banks/radius" method="get" id="send_radius">
Курс ближайших банков на сегодня в радиусе
<input type="text" name="radius" id="radius" size="5" value={{radius}} >
<input type="submit" class="button" value="V">
метров
</form>
<div id="check"> {{output}}</div>
<div id="places"> </div>
</div>
</section>
<section id="not_allowed" style="display:none;">
<div class="question"> Приложение не имеет возможности определить близ лежащие банки.<div>
</section>
</body>
<script type="text/javascript">
/* frm.submit(function () {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serializeArray(),
cache: false,
success: function () {
$("#check").html("OK!!!");
},
error: function(data) {
$("#check").html("Something went wrong!");
}
});
return false;
}); */
function show_sec() {
document.getElementById('allowed').style.display = "block";
document.getElementById('ask_user').style.display = 'none';
$.ajax({
type: "get",
url: "/nearest_banks/radius",
}).success(function(data) {
$("#places").html(data);
/*alert ("OK !!!"); */
});
}
function dnt_show_sec() {
document.getElementById('not_allowed').style.display = "block";
document.getElementById('ask_user').style.display = 'none';
}
$(document).ready(function(){
$("button#yes").click(function(){
//alert("demo_test");
$("section#allowed").show();
});
});
</script>
python function i try to call:
*def get(self):
default_radius = 1000
radius = get_radius(self)
exceptions = [u'', 'error', 0] # invalid values for radius
if any([radius in exceptions]):
radius = default_radius
#warning = "Вы ввели неверный радиус. Система автоматически заменила его на стандартный."
output = radius # заменить на вывод банков
else:
#warning = ''
output = radius # заменить на вывод банков
names, location = Findplaces(self, radius)
body_values = {
'names': names,
'location': location,
'radius': radius,
'output': output,
#'warning': warning,
}
template = jinja_env.get_template('nearest_banks.html')
self.response.out.write(template.render(body_values))*
In short my goal is to display names and location in the tag div id="places" after clicking on Yes button.
Or maybe i can initiate displaying specific tags from server side by using jinja2 in my python function.
Please, help me. I've spent time on it still can't get it working nicely. Thanks in advance !
EDIT:
When I click on Yes button the show_sec function loads section with id allowed.
The problem: the action in form is not processed. So Only html is shown but data from server is not received.
Since the url is "/nearest_banks/radius" and it's a get, try opening that in a browser to see what appears. You may need to view source on the page returned to view it properly. You should verify functionality of the web service first, that it returns something, and returns the correct thing.
Following that, in your show_sec function, do trial and error to see what happens. If you move the requested content to the same path as the executing page, does that make a difference?