Search box in a jQuery ajax success page - issues in loop - javascript

Firstly, there have some tag links in my main page. click each one, post value to b.php with jquery.ajax and turn back value in div#result.
b.php have a search box. when search something in it. the result data will still show in the div#result.
my problem is: I know if I will do jQuery ajax in the b.php, I shall write the jQuery code in the first success part. but this only can control one time, when I continue search in the search box, the jQuery not work. I think I met a loop problem. How to solve it?
a.php
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.click').click(function(){
var value1 = $(this).text();
$.ajax({
url: "b.php",
dataType: "html",
type: 'POST',
data: "data=" + value1,
success: function(data){
$("#result").html(data);
$('#search').click(function(){
var value = $('#search1').val();
$.ajax({
url: "b.php",
dataType: "html",
type: 'POST',
data: "data=" + value,
success: function(data){
$("#result").html(data);
}
});
});
}
});
});
});
</script>
<a rel="aa" class="click">aa</a>
<a rel="aa" class="click">bb</a>
<div id="result"></div>
b.php
<?php
echo $_POST['data'];
?>
<form name="form">
<input type="text" value="" id="search1">
<a name="nfSearch" id="search">search</a>
</form>

When a new element is introduced to the page the jQuery .click() method becomes useless because it can only see elements that were part of the original DOM. What you need to use instead is the jQuery .live() method which allows you to bind events to elements that were created after the DOM was loaded. You can read more about how to use it at the below link.
.live() – jQuery API
$('#search').live('click', function(e) {
// Prevent the default action
e.preventDefault();
// Your code here....
});

First of all i think you should attach the ajax call to the click on the link: the way you are doing right now just execute an ajax call as soon as the page is loaded.
$(document).ready(function(){
//when you click a link call b.php
$('a.yourclass').click(function(){
$.ajax({
url: "b.php",
dataType: "html",
type: 'POST',
data: "data = something",
success: function(data){
$("#result").html(data);
var value = $('#search').val();
$.ajax({
url: "b.php",
dataType: "html",
type: 'POST',
data: "data =" + value,
success: function(data){
$("#result").html(data);
}
});
}
});
});
});
In this way, each time a link with the class of "yourclass" is clicked an ajax call to b.php is sent and if it succed, another call is made (always to b.php). I don't understand if this is what you are looking fo, if you post your html my answer can be better.
In b.php of course you need to echo some html that can be used in the callback

It's strange how your attempting to do two ajax requests like that, surely one is enough. If you need to support multiple text boxes then you just adjust your selectors.
Your whole code can be shortended down to something like this:
$(document).ready(function() {
$('#result').load('b.php', { data: $('#search').val() });
});
So if you wanted to search for the value when clicking on a link (for links within #container):
$('#container').delegate('a', 'click', function() {
// .text() will get what's inside the <a> tag
$('#result').load('b.php', { data: $(this).text() });
});

Related

Onload Page load extern page

i use this AJAX script to load an extern page (mpt_planningen_overzicht.php) into a div op the mainpage (mainpage.php) when people select or unselect a checkbox.
But i also want to load the data from the extern page in the div when mainpage.php is opened.
How can i do this?
Script:
<script type="text/javascript">
$(document).ready(function(){
$('input[type="checkbox"]').on('click', function(){
var formData = $(":input,:hidden").serialize();
$.ajax({
type: "POST",
url: "mpt_planningen_overzicht.update.php",
data: formData,
success: function(result){ /* GET THE TO BE RETURNED DATA */
$("#resultaat").html(result); /* THE RETURNED DATA WILL BE SHOWN IN THIS DIV */
}
});
});
});
</script>
I thought something like this:
function onLoadSubmit() {
document.nameofForm.submit();
}
But the Ajax script that checks if a selectbox is checked/unchecked is already on mainpage.php, so when i add the script above, it will continue reloading.
If I understood the question correctly, you can try something like this:
<script type="text/javascript">
//separationg the function that loads the page in order to use it multiple times
var loadSepratePage = function(){
var formData = $(":input,:hidden").serialize();
$.ajax({
type: "POST",
url: "mpt_planningen_overzicht.update.php",
data: formData,
success: function(result){ /* GET THE TO BE RETURNED DATA */
$("#resultaat").html(result); /* THE RETURNED DATA WILL BE SHOWN IN THIS DIV */
}
});
}
$(document).ready(function(){
$('input[type="checkbox"]').on('click', loadSepratePage); // without paranthesis () to pass the function as a parameter
loadSepratePage() // with paranthesis () to actually call the function
});
</script>
If this is not what you mean feel free to leave comment

How to make an AJAX call to an html element?

What I want to do is pretty simple. I want to make an AJAX call to a specific html class, so that whenever the html page is loaded, jquery will make an AJAX call to that specific html div class.
For example:
<div class="targeted"></div>
In jquery:
$('.targeted')
I know that the syntax to make an AJAX call is:
$.ajax({
type: "GET",
url: "/api/something",
success: function(data) {
console.log(data);
}
});
But how do I implement this AJAX call to the $('.targeted') whenever the page is loaded?
Thanks
If you mean you want to display the result of the ajax call in the element, you update the element from within the success callback:
$.ajax({
type: "GET",
url: "/api/something",
success: function(data) {
$('.targeted').html(data);
}
});
That example assumes
You want to replace the content of the element (rather than adding to it); more options in the jQuery API.
data will be HTML. If it's plain text, use .text(data), not .html(data). If it's structured data, then of course you'll need to do more work to put the information in the desired form.
window.onload = function() {
yourFunction();
};
function yourFunction(){
$.ajax({
type: "GET",
url: "/api/something",
success: function(data) {
$('.targeted').html(data);
}
});
}
OR Drectly you can pass that method in document ready it will execute automatically
$(document).ready(function(){
//This will execute onload oof your web page what you required
yourFunction();
})
function yourFunction(){
$.ajax({
type: "GET",
url: "/api/something",
success: function(data) {
$('.targeted').html(data);
}
});
}
For when the page is loaded, you use:
$( document ).ready(function() {
console.log( "ready!" );
});
Inside the document ready, you put your AJAX call. If the result you get is in JSON format, you need to include the dataType as well like this:
$.ajax({
method: "GET",
url: "/api/something",
dataType: "json"
})
.done(function( data ) {
$('.targeted').append(JSON.stringify(data));
});
If the result is not JSON, then you can just append the data.
Also note:
The jqXHR.success(), jqXHR.error() and jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail() and jqXHR.always() instead.
Please look at the jQuery documentation.
you can use jquery load like this:
$(".targeted").load('/api/something');
if you want to wait untill after the page is loaded, wrap it with window load like so:
$(window).load(function () {
$(".targeted").load('/api/something');
});
P.S. $(window).load(..) and $(".class").load(url) are two different functions
You can do:
$(function() {
$.ajax({
type: "GET",
url: "/api/something",
})
.done(function(data) {
$('.targeted').text(data);
});
});

Display SQL Query Result using AJAX

I have a news feed on my site, onto which users can post posts. These posts can then be liked by other users (just like facebook for example).
The Problem
I would like to display the users, who liked a post using ajax. Whenever a certain element is hovered.
At the moment the users are correctly displayed but below every post, not just the one which contains the hovered element.
My attempt to solve the problem
<!-- HOVER THIS -->
<span class="likers small link"></span>
<!-- DISPLAY LIKERS HERE -->
<small class="displayLikers"></small>
<!-- AJAX -->
<script>
$(function() {
$(".likers").hover(function(){
$.ajax({
url: "get/likers",
type: "GET",
success: function(response) {
$(this).closest('.displayLikers').html(response);
}
});
});
});
</script>
I would be very thankful for any kind of help!
Inside the $.ajax, $(this) does not refer to $(".likers") just add $(this) to a variable and use it in the ajax response function;
$(function() {
$(".likers").hover(function(){
var likes = $(this);
$.ajax({
url: "get/likers",
type: "GET",
success: function(response) {
likes.closest('.displayLikers').html(response);
}
});
});
});
In your example the .displayLikers is a sibling so you should probably use next(). Moreover this will refer to the actual context of the success function, so you have to create a reference before.
$(function() {
$(".likers").hover(function(){
var self = $(this);
$.ajax({
url: "get/likers",
type: "GET",
success: function(response) {
self.next('.displayLikers').html(response);
}
});
});
});

div content after html() is not showing

I've got an issue with an ajax call and .html(), as you can see with the javascript below i'm using the geoloc callback to make a ajax call and refresh the content of a div.
The id of the div can be either "result-shops-ajax-desktop" or "result-shops-ajax-mobile" and in my case the php variable $type = "desktop"
The problem is that the content of the div is not reloaded despite the use of .html()
My ajax call is working because msg.response got the content i want. The .html() seems to work because the alert show the content of msg.response but I can't see it on the page :/
Another thing is weird when i put directly the id of the div, the content is shown, but when i echo the $type it's not working despite the fact that the html produced is good (the id of the div is "result-shops-ajax-desktop").
I hoped i made myself clear with my bad english, i would really appreciate any help for this weird issue.
Thanks !
Here is the javascript in my php file :
<script type="text/javascript">
jQuery.noConflict();
jQuery(document).ready(function($){
function geolocShow(position) {
$.ajax({
type: "POST",
url: "<?php echo $this->getUrl('shops/index/checkavailability'); ?>",
dataType : "json",
data: "sku=<?php echo $product->getSku(); ?>&lat="+position.coords.latitude+"&lng="+position.coords.longitude,
success: function(msg){
$("#result-shops-ajax-<?php echo trim($type); ?>").html(msg.response);
alert($("#result-shops-ajax-<?php echo trim($type); ?>").html());
}
});
}
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(geolocShow);
}
});
</script>
The html generated:
jQuery.noConflict();
jQuery(document).ready(function($){
function geolocShow(position) {
$.ajax({
type: "POST",
url: "http://localhost/shops/index/checkavailability/",
dataType : "json",
data: "sku=abc&lat="+position.coords.latitude+"&lng="+position.coords.longitude,
success: function(msg){
$("#result-shops-ajax-desktop").html(msg.response);
alert($("#result-shops-ajax-desktop").html());
}
});
}
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(geolocShow);
}
});
Try this: jQuery(document).ready(function($){ this line change to $(window).load(function(){

How to run jQuery onClick? Need to pass a variable to run .ajax

I'm trying to run .ajax and insert a data element from the onClick of an item from the page. Whats the best way to do this?
Something like this:
function grabinfo(foo){
$.ajax({
url: "infospitter.php",
method: "GET",
data: "id="+foo,
success: function(html){
$(#showstuff).html(html);
}
});
}
<input onClick="javascript:grabinfo(18343)" />
// and on page each item will have this button input
It's usually best to keep your javascript unobtrusive, and out of the DOM.
<input type="button" value="18434"/>
In your javascript file:
$('input[type=button]').click(function(){
$.ajax({
url: 'infospitter.php',
method: 'GET',
data: 'id=' + $(this).attr('value'),
success: function(returnData){
// Do something with returnData
}
});
});
Remove the "javascript:" from your onclick attribute. That's only needed when running code outside a javascript event attribute.

Categories