Element requiring 2 clicks until it shows - php

I am trying to make a quote form appear on click, the element is first prepended it then needs to run through ajax to get the content for the element
HTML
<input type="button" class="used_result_icon used_result_nav_enquire" car="'.$full_listing_name.'" />
CSS
#used_car_quote {background:#fff; border:2px solid #bebebe; border-radius:5px; display:none; font-size:20px; left:500px; min-height:350px; position:fixed; width:640px; z-index:100;}
AJAX
$(document).on("click", ".used_result_nav_enquire", function() {
car = $(this).attr('car');
$('#used_car_quote').show();
$('#used_results_sort').prepend('<div id="used_car_quote"></div>');
$.ajax({
type : 'POST',
url : 'http://localhost/carprice/ajax/used-quote-results.php',
data : 'car='+car,
success : function(data) {
$("#used_car_quote").html(data);
}
});
});
Its very strange, I click on the button once, and nothing happens, then I click again, and the form appears.

Use this code in AJAX Success $('#used_car_quote').show();
$(document).unbind("click").bind('click', ".used_result_nav_enquire", function() {
car = $(this).attr('car');
$('#used_results_sort').prepend('<div id="used_car_quote"></div>');
$.ajax({
type : 'POST',
url : 'http://localhost/carprice/ajax/used-quote-results.php',
data : 'car='+car,
success : function(data) {
$("#used_car_quote").html(data);
$("#used_car_quote").show();
}
});
});

I am trying to style it as well, but this is very strange, if I click on it once, then it is not positioned right, close it then click again, and it is
$(document).on("click", ".used_result_nav_enquire", function() {
win_width = $(window).width();
form_width = $('#used_car_quote').width();
left = (win_width-form_width)/2;
win_height = $(window).height();
form_height = $('#used_car_quote').height();
top = (win_height-form_height)/2;
car = $(this).attr('car');
$('#used_results_sort').prepend('<div id="used_car_quote">test</div>');
$('#used_car_quote').css({'left':left,'top':top});
$.ajax({
type : 'POST',
url : 'http://localhost/carprice/ajax/used-quote-results.php',
data : 'car='+car,
success : function(data) {
$("#used_car_quote").html(data);
$('#used_car_quote').show();
}
});
});

Related

How do you pull a php variable into a js object's property via jQuery AJAX?

I want the user to type an answer ('zebra') in the input area. If they get it correct, then they are alerted that it is correct.
This answer will be pulled from a database eventually. For this simple example, I'm just pulling it into the object from another php file via jQuery AJAX.
It seems to pull in the php variable okay, but it still says 'incorrect answer' in the example I'm doing here =
https://michael-r-oneill.ie/development/random/Testing/testing.php
https://michael-r-oneill.ie/development/random/Testing/collectDataTesting.php
Below is the html / php file
<!-- head -->
<head>
<!-- jQuery library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js">
</script>
<title>Testing</title>
</head>
<script>
var AnswerSubmitted;
var quizes;
function quizesFunction(animal)
{quizes = [{bigPicture: animal},{bigPicture: 'tokyo'}]}
$(function() {
$.ajax({type: "POST",
url: 'collectDataTesting.php',
data: {},
dataType: "text",
success: function(data) {
quizesFunction(data);
}
});
$(document).on('click', '.submit', function() {
AnswerSubmitted = $('#typedAnswer').val();
if (AnswerSubmitted == quizes[0].bigPicture)
{
$('.test').html('correct answer').css("color", "green");;
$('.AnswerSubmitted')
.html('Answer submitted is ' + AnswerSubmitted);
$('.objectProperty')
.html('Object property is now ' + quizes[0].bigPicture);
}
else
{
$('.test').html('incorrect answer').css("color", "red");
$('.AnswerSubmitted')
.html('Answer submitted is ' + AnswerSubmitted);
$('.objectProperty')
.html('Object property is now ' + quizes[0].bigPicture);
}
});
});
</script>
<p class="objectProperty"></p>
<p class="AnswerSubmitted"></p>
<p class="test"></p>
<input type="text" id="typedAnswer" />
<button class="submit" id='AS'>enter</button>
Below is the 'collectDataTesting.php' php file I'm going to to collect the data
<?php
echo 'zebra';
?>
If I am reading this right, then it looks like the data passed to quizesFunction(data) when the ajax request is completed is not of the type that you expect.
Remember that if you don't provide the dataType setting to $.ajax (which you don't), jQuery will try to "guess" the type for you (https://api.jquery.com/jQuery.ajax/).
You can either set the dataType to text or simply follow the advice given by the other members and have PHP return JSON (which jQuery will interpet as a JavaScript object).
So as recommended by a contributor above, I managed to begin solving this issue by replying back to AJAX with JSON.
Here are the updated testing pages =
https://michael-r-oneill.ie/development/random/Testing/testing3.php
https://michael-r-oneill.ie/development/random/Testing/collectDataTesting3.php
and code below =
html =
<p class="AnswerSubmitted"></p>
<p>Type 'dog' in the input area and hit enter</p>
<input type="text" id="typedAnswer" />
<button class="submit" id='AS'>Enter</button>
js =
var AnswerSubmitted;
var AnswerCollected;
var quizes = [{bigPictureAnsw: 'answer here', bigPHint : 'hint here'},
{bigPictureAnsw: 'answer here', bigPHint : 'hint here'}]
$(function() {
$.ajax({
type: 'GET',
url: 'collectDataTesting3.php',
data: { get_param: 'value' },
dataType: 'json',
success: function (data) {
var x = 0;
$.each(data, function(index, element) {
quizes[x].bigPicture = element.answer;
quizes[x].bigPHint = element.hint;
x++;
});
}
});
$(document).on('click', '.submit', function() {
AnswerSubmitted = $('#typedAnswer').val();
if (AnswerSubmitted == quizes[0].bigPicture)
{
$('.AnswerSubmitted').html('correct answer');
}
else
{
$('.AnswerSubmitted').html('not correct');
}
});
});
external page ('collectDataTesting3') =
[ { "answer" : "dog", "hint" : "not a cat" },
{ "answer" : "dublin", "hint" : "capital city" }]

need help for proper way to write codes for create "loadmore" button and "like" button for posts

I create a load more button for load more posts from the database but when I add like button for that if one time clicks on load more button and then click on the like button, like.php file runs two times and adds two lines in likes table. if I click 2 times on load more then like.php file runs 3 times and...
I want to know how I should create a loadmore button and like the button to works fine.
this is simple of my codes:
posts.php :
<div id="comnts2"></div>
<button id="btn2" >load more</button><script>
$(document).ready(function() {
var comco2 = 2;
var offset2 = 0;
$("#btn2").click(function() {
$.ajax({
method: "POST",
url: "ld_comco.php",
data: { comnco2 : comco2, offset2 : offset2}
})
.done(function(msg2) {
$("#btn2").hide();
} else {
$("#comnts2").append(msg2);
});
offset2 = offset2 + comco2;
});
$("#btn2").trigger("click");
});
</script>
ld_comco.php:
<?php
$comnco2=$_POST['comnco2'];
$offset2=$_POST['offset2'];
$rzp=mysqli_query($conn,"SELECT * FROM `tbl_users_posts` WHERE uid = '$uid' ORDER BY id DESC limit $offset2, $comnco2");
while($rp=mysqli_fetch_assoc($rzp)){
$sid=$rz['id'];
$lik=$rz['lik'];
echo $sid."<br>";
/*like*/
echo'<img class="li_ik1" data-id="'.$sid.'" src="pc3/up.png">'.$lik.' Likes</img>';
?>
</span>
<?php }?>
<script type="text/javascript">
$(document).ready(function() {
var uid=<?php echo $uid;?>;
$(document).on("click", ".li_ik1", function() {
var psid = $(this).data('id');
$.ajax({
method: "POST",
url: "like.php",
data: {psid: psid, uid: uid}
}).done();
});
});
</script>
like.php:
<?php
$id=$_POST['psid'];
$uid=$_POST['uid'];
$Y=mysqli_query($conn,"INSERT INTO `t_plik` (pid,uid) VALUES ('$id','$uid')");
$Q=mysqli_query($conn,"UPDATE `tbl_users_posts` SET lik=lik+1 WHERE id='$id'");
?>
thanks
I think the problem is, that you bind your like button multiple times globally. Each time you load the content from ld_comco.php you also call $(document).on("click", ".li_ik1", ...) in the $(document).ready block, which means you bind all ".li_ik1" buttons on the entire document (but some of them has already been bind).
I would remove the $(document).ready(...) block from the ld_comco.php and move the logic into the posts.php right before you render your content. A further positive aspect is you have your business logic at one place.
KEEP IN MIND: You get a response of buttons in msg2, thats why you do not need to filter $msg2 anymore. But if you wrap your buttons with further html tags in ld_comco.php, your buttons will be on a deeper level, so you need to use a selector again, like you did with .on("click", ".li_ik1", ...).
posts.php
...
var $msg2 = $(msg2);
// Now you bind only the loaded buttons instead of
// the buttons in the entire document for multiple times
$msg2.on("click", function() {
var $element = $(this);
var psid = $element.data('id');
var uid = $element.data('uid');
$.ajax({
method: "POST",
url: "like.php",
data: {psid: psid, uid: uid}
}).done();
});
$("#comnts2").append($msg2);
...
In your ld_comco.php you need to add the data-uid="'.$uid.'" and remove the script block. Then your file should look like this:
<?php
$comnco2=$_POST['comnco2'];
$offset2=$_POST['offset2'];
$rzp=mysqli_query($conn,"SELECT * FROM `tbl_users_posts` WHERE uid = '$uid' ORDER BY id DESC limit $offset2, $comnco2");
while($rp=mysqli_fetch_assoc($rzp)){
$sid=$rz['id'];
$lik=$rz['lik'];
echo $sid."<br>";
/*like*/
echo'<img class="li_ik1" data-id="'.$sid.'" data-uid="'.$uid.'" src="pc3/up.png">'.$lik.' Likes</img>';
}
?>
$("#btn2").trigger("click");
this in posts.php means click the #btn2
so after clicking it, you click it again
$(document).ready(function() {
var comco2 = 2;
var offset2 = 0;
$("#btn2").click(function() {
$.ajax({
method: "POST",
url: "ld_comco.php",
data: { comnco2 : comco2, offset2 : offset2}
})
.done(function(msg2) {
$("#btn2").hide();
} else {
$("#comnts2").append(msg2);
});
offset2 = offset2 + comco2;
});
$("#btn2").trigger("click");
});
</script>

Suggestion box not showing for nearest input

I cannot seem to get my suggestion box to show for the nearest input after adding more inputs dynamically.
The below code is where I am currently, I can see the suggestion box for a new input and add to that new input but if I go back to edit the input data the suggestion box fails to show.
<div id="tester"></div>
<button id="add_test">ADD</button>
$(document).ready(function() {
$("#add_test").on("click", function() {
var input = '<div class="flavhey"><div class="flavourInput"><input class="ftext form-control flavour-name-input" type="text" name="flav-name-input" value="" placeholder="Flavour Name" /><div class="suggestion-box"></div></div></div>';
$('#tester').append(input);
});
$(document).on('keyup', '.flavhey input', function(e){
var token = '<?php echo json_encode($token); ?>';
var search = $(this).val();
$.ajax({
type: "POST",
url: "controllers/recipeControl.php",
data: { token: token, search: search },
beforeSend: function(){
$(".flavour-name-input").css("background","#FFF no-repeat 165px");
$(".suggestion-box").css("background","#FFF no-repeat 165px");
},
success: function(data){
$('.flavhey input').closest('flavourInput input').next('.suggestion-box').show();
$('.flavhey input').next('.suggestion-box').html(data);
$(".suggestion-box").css("background","#FFF");
}
});
return false;
});
$(document).on("click",".search-flavour",function(e) {
e.preventDefault();
$(this).closest('.flavourInput').find('.flavour-name-input').val($(this).text());
$('.suggestion-box').hide();
return false;
if(isset($_POST['search'])) {
if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' && isset($_POST['token'])
&& json_decode($_POST['token']) === $_SESSION['token']){
$search = $_POST['search'];
$html = '<ul>';
$content = $flavours->getAllFlavoursSearch($search);
foreach ($content as $con) {
$html .= '<li class="search-flavour"><b>'.$con['flavour_name'].'</b> - <i>'.$con['flavour_company_name'].'</i></li>';
}
$html .= '</ul>';
echo $html;
}
}
Ok short version:
Use var box = $(e.target).next(".suggestion-box"); to aquire a reference to the correct suggestion box in the success handler of the ajax request.
Long version:
I replaced the php parts with static placeholders to get a runnable example.
$(document).ready(function() {
$("#add_test").on("click", function() {
var input = '<div class="flavhey"><div class="flavourInput"><input class="ftext form-control flavour-name-input" type="text" name="flav-name-input" value="" placeholder="Flavour Name" /><div class="suggestion-box"></div></div></div>';
$('#tester').append(input);
});
$(document).on('keyup', '.flavhey input', function(e) {
var token = "[token]";
var search = $(this).val();
var box = $(e.target).next(".suggestion-box");
box.show();
box.html("TestData");
box.css("background", "#FFF");
return false;
});
$(document).on("click", ".search-flavour", function(e) {
e.preventDefault();
$(this).closest('.flavourInput').find('.flavour-name-input').val($(this).text());
$('.suggestion-box').hide();
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="tester"></div>
<button id="add_test">ADD</button>
<ul>
<li class="search-flavour">
<b>flavour_name_1</b> - <i>flavour_company_name_1</i>
</li>
<li class="search-flavour">
<b>flavour_name_2</b> - <i>flavour_company_name_2</i>
</li>
<li class="search-flavour">
<b>flavour_name_3</b> - <i>flavour_company_name_3</i>
</li>
</ul>
Now being able to execute your code I was able to reproduce the described error. Please try to provide a runnable example next time.
I realized that your box was only appearing once because the call to .show() wasn't working at all. It was visible from the beginning just without any content so you couldn't see it, then after setting html() it had content and it looked like the call to show() worked as intended.
Afer you clicked on a .search-flavour all boxes were correctly hidden and thus never appeared again.
So to fix this, replace the success handler of the ajax request with this:
success: function(data){
// e.target is the currently active input element
var box = $(e.target).next(".suggestion-box");
box.show()
.html(data)
.css("background", "#FFF");
}

How to get dynamically created javascript div id by jquery and store in php?

var count=0;
function createOne() {
var divTag = document.createElement("div");
dynamically created div
var br= document.createElement("br");
count++;
divTag.id = "div1"+count;
Id increment +1
divTag.setAttribute("align", "center");
divTag.style.margin = "0px auto";
divTag.style.width="430px";
divTag.style.height="35px";
divTag.style.background="olive";
divTag.className = "dynamicDiv";
divTag.innerHTML = "This HTML Div tag created "
+ "using Javascript DOM dynamically.";
document.body.appendChild(divTag);
document.body.appendChild(br);
}
> Need to save in php using Jquery.
<body>
<h1 align="center">
Click it
<input type="button" id="dev" onClick="createOne()" value="GET">
</h1>
</body>
If you are using jQuery then use it. Convert your function to jQuery and use jQuery's ajax functions.
JavaScript
jQuery(function($){
$('#dev').click(function(){ createOne(); });
window.count = 0;
function createOne() {
var new_id = 'div1' + (++count);
$('body').append('<div class="dynamicDiv" id="' + new_id + '" style="margin: 0px auto; width: 430px; height: 35px; background-color: olive;">This HTML Div tag created using Javascript DOM dynamically.</div><br/>');
$.get('/div-id-saver.php', { 'id': new_id }, function(response){
console.log('post response:' + response);
});
}
});
HTML
<body>
<h1>
Click it
<input type="button" id="dev" value="GET">
</h1>
</body>
More info: http://api.jquery.com/category/ajax/shorthand-methods/
In your createOne() function, you can do an AJAX post back to a PHP script passing through the ID of the element you just created.
You can find more information on JQuery's AJAX here
You haven't specified what you want to do with the information or when so this should help to get started.
In the ajax call, the data will look like:
var mydata = new Array ();
$("div[id^='div']").each (function (){
mydata.push ({$(this).attr ("id") : $(this).text ()});
});
I use the text of the div as the value, but you can change it to your needs...
I suggest you post the data by Ajax
createOne = function() {
var $div = $('#div1'+count);
$.ajax({
type: "POST",
url: "some.php",
data: { id: "div1"+count, html: $div.html() }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
}
** Using jQuery **
// Within your createone() function
// Location of your PHP file
var url = 'savemyvar.php';
$.post(url, { div : divTag.id }).success(function(data, status, xhr)
{
// Do something on success
}).error(function(data)
{
// Do something on error
});
Info on $.post a helper function for $.ajax
$.ajax documentation
This will send your divTag object to the PHP script that you can use
$_REQUEST['div']
to access.

button click event not working after append data from php

I am loading html with javascript from php to a div using $.get() to a div. the button click event is working fine. then adding again same thing again to different div with different id, but it is not working. can anyone can help me. my code is this
<style>
.loadWindow {
width:333px;
height: 202px;
padding: 5px 5px 0 5px;
font: 12px Arial, Helvetica, sans-serif;
border:double;
}
#loadWindow {
display:none;
}
<div id="main-box">
<div class="loadWindow" id="loadWindow"></div><button id="make">make</button>
My javascript code is below
$(function(){
$('#make').click(function(){
var id = $('.loadWindow').length;
var aw = $('#loadWindow').clone().attr("id", "window"+id);
//load data from php
$.get("mydata.php", function(data) {
aw.html(data);
$('#main-box').append(aw);
aw.show();
}, 'json');
});
});
`
My mydata.php code is below
echo '<div><button id="closeBtn">Close</button></div><script>$("#closeBtn").click(function(){alert("Close button Clicked!");});</script>';
I want click event work for each window separately(individually) and display the alert. In this code click event is not working according to the window. What can I do?
Working demo http://jsfiddle.net/QYEWs/13/
Please use .on API to it attaches an event handler function for one or more events to the selected elements.
API: http://api.jquery.com/on/
Plz Note: your append will make the DOM invalid as your id will always be same make it a class
to attach click event on dynamically added html in DOM
This should help, :)
like this
Attaché click event to close button like this:
$("#main-box").on("click",".closeBtn", function() {
alert("Close button Clicked!");
});​
$(function(){
$('#make').on('click', function(){
var id = $('.loadWindow').length;
var aw = $('#loadWindow').clone().attr("id", "window"+id);
//load data from php
$.get("mydata.php", function(data) {
aw.html(data);
$('#main-box').append(aw);
aw.show();
}, 'json');
});
});
$(function(){
$('#make').click(function(){
var id = $('.loadWindow').length;
var aw = $('#loadWindow').clone(true).attr("id", "window"+id);
//load data from php
$.get("mydata.php", function(data) {
aw.html(data);
$('#main-box').append(aw);
aw.show();
}, 'json');
});
});

Categories