I want to load my database content using ajax and jquery. I already write a javascript and it works correctly but I can't write correctly for ajax jquery. Anyone please give me some example?
my javascript code:
<script language="javascript">
function getfilter(str){
document.getElementById("result").innerHTML="<div class='sparea'><i class='fa fa-spinner fa-spin sparea' ></i><div></script";
if (str==""){
document.getElementById("result").innerHTML="";
return;
}
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("result").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","Views/pfolioresult.php?q="+str,true);
xmlhttp.send();
}
</script>
<div class="sprocket-mosaic-header">
<div class="sprocket-mosaic-filter">
<ul>
<li class="all active" data-mosaic-filterby="all" onclick="getfilter(this.id)" id="all" >All</li>
<li class="android" data-mosaic-filterby="android" onclick="getfilter(this.id)" id="android" >Android</li>
<li class="iOS" data-mosaic-filterby="iOS" onclick="getfilter(this.id)" id="ios" >IOS</li>
</ul>
</div>
<div class="clear"></div>
</div>
<div id="result">
ok
</div>
You can simply use Ajax and Jquery for data load. You can use
function getfilter(str){
$.ajax({
type: "POST",
//path to php page to get data
url:"pathto/getdata.php",
data: "id="+str,
success:function(result){
//here is your success action
//get data on div
$("#result").html(result);
});
}
We can do this by calling a function onclick as illustrated above or you can use JQuery's onclick event.
Now Get Id in you getdata.php page using $_POST['id'] and return your database data to ajax success and do whatever you want to do.
Do this
function getfilter(str){
document.getElementById("result").innerHTML="<div class='sparea'><i class='fa fa-spinner fa-spin sparea' ></i><div></script";
if (str==""){
document.getElementById("result").innerHTML="";
return;
}
$.ajax({
url: "Views/pfolioresult.php",
type: "GET",
data: { q : str },
success: function ( responseText ) {
$("#result").html( responseText );
}
});
}
Learn it from here: https://api.jquery.com/jQuery.ajax/
Since you're using jQuery, the easiest would be to use .load()
http://api.jquery.com/load/
Try this
<script language="javascript">
function getfilter(str){
document.getElementById("result").innerHTML="<div class='sparea'><i class='fa fa-spinner fa-spin sparea' ></i><div></script";
if (str == ""){
$( "#result" ).html( "" )
return;
}
var request = $.ajax({
type: "POST",
url: "Views/pfolioresult.php",
data: { id: str }
});
request.done(function( msg ) {
$( "#result" ).html( msg );
});
request.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
}
<script>
function getfilter(str){
if (str==""){
document.getElementById("result").innerHTML="";
return;
}
$.ajax({
url: "Views/pfolioresult.php?q="+str,
type: "GET",
// data: serializedData,
success: function ( responseText ) {
$("#result").html(responseText);
}
});
}
</script>
This code works correctly but suppose i have 10,000 data in database .This code show all data at once after load but how it possible that data show one by one depent on load time that means when one item load then it show and other continuously show
Related
So I am trying to build a single page application using PHP and AJAX but I am having some issues with my navigation.
I have a file controller.php that controls the page to be displayed. The code that handles a post request is as follows
EDIT: Forgot to mention that echoing $_POST['page'] shows nothing
if(!isset($_POST['page'])){
include('Pages/landing_page.php');
echo "empty";
}
else{
echo $_POST['page'];
if($_POST['page'] == 'landing_page'){
include('Pages/landing_page.php');
}
if($_POST['page'] == 'forum'){
include('Pages/forum.php');
echo "forum hit";
}
}
The post request is generated with $.ajax function as follows
$(document).ready(function(){
$("#home_link").on('click', ()=>{
alert("Working");
$.ajax({
type: "POST",
url: "controller.php",
data: "page=landing_page"
});
});
$('#forum_link').on('click', ()=>{
$.ajax({
type: "POST",
url: "controller.php",
data: "page=forum",
success: function(){
alert("Callback Works");
}
});
});
});
I know the jquery click is working because I get the original "Working" alert as well as the callback alert if I click on the forum link.
I am using the Netbeans built in PHP development server but I have also tested it on a proper apache2 server that is well configured for PHP and AJAX.
Any help would be appreciated, thanks!
As I understand the question, this should work:
PHP: (all the same)
if(!isset($_POST['page'])){
include('Pages/landing_page.php');
echo "empty";
}
else{
echo $_POST['page'];
if($_POST['page'] == 'landing_page'){
include('Pages/landing_page.php');
}
if($_POST['page'] == 'forum'){
include('Pages/forum.php');
echo "forum hit";
}
}
JS:
$(document).ready(function(){
$("#home_link").on('click', ()=>{
alert("Working");
$.ajax({
type: "POST",
url: "controller.php",
data: "page=landing_page"
});
});
$('#forum_link').on('click', ()=>{
$.ajax({
type: "POST",
url: "controller.php",
data: "page=forum",
success: function(data){
$("#container").html(data);
alert("Callback Works");
}
});
});
});
You need to take the data returned from the function and put it somewhere, presumably into a container element.
If this isn't what you are trying to do, please comment.
I have a loading gif that I want to display and hide before and after Ajax request using ajaxStart and ajaxStop. Nothing works:
HTML:
<div id="loading" style="display: none"><img src="loading.gif></div>
JS:
$("#searchForm").submit(function(event)
{
$.ajaxStart(function() {
$( "#loading" ).show();
});
$.ajaxStop(function() {
$( "#loading" ).hide();
});
$.ajax({
type: 'POST',
url: 'models/fetchUsers.php', //the script to call to get data
data: $("#searchForm").serialize(), //add the data to the form
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
$.each($(data), function(key, value) {
$('#itemContainer').append(value.user_id);
});
},
error: function()
{
$('#itemContainer').html('<i class="icon-heart-broken"> <?= $lang["NO_DATA"] ?>');
}
});
Try ajaxStart and ajaxStop
$(document).ajaxStart(function() {
$( "#loading" ).show();
});
$(document).ajaxStop(function() {
$( "#loading" ).hide();
});
There is problem in your HTML also ("loading.gif")
<div id="loading" style="display: none"><img src="loading.gif"></div>
Add event.preventDefault(); in your submit function, that will prevent a submit button from submitting a form.
Or Other way is to do the things in your function only, without calling global functions of ajax.
$("#searchForm").submit(function(event)
{
event.preventDefault();
$( "#loading" ).show();
$.ajax({
type: 'POST',
url: 'models/fetchUsers.php', //the script to call to get data
data: $("#searchForm").serialize(), //add the data to the form
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
$.each($(data), function(key, value) {
$('#itemContainer').append(value.user_id);
});
},
complete: function(){
$('#loading').hide();
},
error: function()
{
$('#itemContainer').html('<i class="icon-heart-broken"> <?= $lang["NO_DATA"] ?>');
}
});
}
$(document).ajaxStart(function() {
$("#gif-image-id").show();
}).ajaxStop(function(){
$("#gif-image-id").hide();
});
Put this as a separate event (outside the submit event), and change the selector to what ever the image id actually is.
I have a form that when clicked the submit button makes a call via ajax. This ajax is inside a php file because I need to fill in some variables with data from the database. But I can not use the calls before / success. They just do not work, I've done tests trying to return some data, using alert, console.log and nothing happens. Interestingly, if the ajax is isolated within a file js they work. Some can help me please?
File:
<?php
$var = 'abc';
?>
<script type="text/javascript">
$(document).ready(function() {
$('#buy-button').click(function (e){
var abc = '<?php echo $var; ?>';
$.ajax({
type: 'POST',
data: $('#buy-form').serialize(),
url: './ajax/buy_form.php',
dataType: 'json',
before: function(data){
console.log('ok');
},
success: function(data){
},
});
});
});
</script>
HTML:
<form id="buy-form">
<div class="regular large gray">
<div class="content buy-form">
/* some code here */
<div class="item div-button">
<button id="buy-button" class="button anim" type="submit">Comprar</button>
</div>
</div>
</div>
</form>
----
EDIT
----
Problem solved! The error was in the before ajax. The correct term is beforeSend and not before. Thank you all for help.
You said it was a submit button and you do not cancel the default action so it will submit the form back. You need to stop that from happening.
$('#buy-button').click(function (e){
e.preventDefault();
/* rest of code */
Now to figure out why it is not calling success
$.ajax({
type: 'POST',
data: $('#buy-form').serialize(),
url: './ajax/buy_form.php',
dataType: 'json',
before: function(data){
console.log('ok');
},
success: function(data){
},
error : function() { console.log(arguments); } /* debug why */
});
});
My guess is what you are returning from the server is not valid JSON and it is throwing a parse error.
Try this
<script type="text/javascript">
$(document).ready(function() {
$('#buy-button').click(function (e){
e.preventDefault();
var abc = '<?php echo $var; ?>';
$.ajax({
type: 'POST',
data: $('#buy-form').serialize(),
url: './ajax/buy_form.php',
dataType: 'json',
beforeSend: function(data){
console.log('ok');
},
success:function(data){
}
});
});
});
And make sure that your php file return response
I trying to sort the list of titles of the pages I can see the correct order after sorting in firebug console when i am hitting sort button it is not taking my request to the requested method. here is my jquery code I am kinda new in it.
<script>
$(function(){
$("#sortable").sortable();
$sortable = $("#sortable");
$( "#sortable_nav_items" ).sortable({
placeholder:"sortable-placeholder",
update: function( event, ui ) {
console.log($("#sortable_nav_items").sortable("toArray",{attribute:"pageid"}));
}
});
var order = $("#sortable_nav_items").sortable("toArray",{attribute:"pageid"});
console.log(order);
$sortable.bind('sortupdate',function(event,ui){
console.log($(this).sortable('toArray'));
$.post(
"content.cfc",
{method:"sortOrder",data:$(this).sortable('toArray')}
);
});
});
</script>
here is my list.
<cfoutput>
<div class="well">
<ul id="sortable_nav_items" class="list-group">
<cfloop query="_q">
<li class="list-group-item" pageid="#_q.id#" navOrder="#_q.nav_order#">
#_q.title#
</li>
</cfloop>
</ul>
</div>
<div class="form-group">
<div class="col-md-offset-3 col-md-9">
<button class="btn btn-info" type="submit">
<i class="glyphicon glyphicon-retweet"></i>
Sort
</button>
</div>
</div>
</cfoutput>
can anyone please help me out what i have to do in it to post the changes to the requested method ? Thanks.
You have not bound click event for your button.
$("button").click(function() {
var order = $("#sortable_nav_items").sortable("toArray",{attribute:"pageid"});
$.post(
"content.cfc",
{method:"sortOrder",data:order}
);
});
Here is jsfiddle (no coldfusion stuff though): http://jsfiddle.net/nn4x8/4/
If you want to send server request on every sort change, same handler for 'sortupdate' event. E.g.:
$("#sortable_nav_items").bind('sortupdate', function() {
var order = $(this).sortable("toArray",{attribute:"pageid"});
$.post(
"content.cfc",
{method:"sortOrder",data:order}
);
});
Try this,
$.post( "content.cfc", { data: $(this).sortable('toArray') } ).done(function( data ) {
alert( "Data Loaded: " + data );
});
Alternate of POST in jquery
$.ajax({
type: 'POST',
url: "content.cfc",
dataType: 'json',
beforeSend: function(){
sortOrder()
},
data: {'data':$(this).sortable('toArray')},
success: function(result){
alert(result)
},
});
<script type="text/javascript">
$(function() {
$('.LSide img').click(function() {
$('.BigImage img').attr("src", $(this).attr("src"));
var img =$('.BigImage img').attr("src").slice(0,-5);
//alert($('.BigImage img').attr("src").slice(0,-5))
//alert(img);
});
});
</script>
I want to pass that var img variable to php function, and call that php function at the click event. does it possible?
You can use an AJAX call to your PHP script and pass the value of img with that call.
What you can't do is mix Javascript code (which is a client side scripting language) and PHP code (which is a server side scripting language)
Of course, you can do that by sending a POST request, and with AJAX it'd be:
$.ajax({
type: "POST",
url: "some.php",
data: { img: img.serialize() }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
http://api.jquery.com/jQuery.ajax/
In your html file. Call click finction like this:
<img src="a.png" id="BigImage" onclick="click()">
<script type="text/javascript">
function click(){
var a = document.getElementById('BigImage').src; //id of your img tag
$.ajax({
type: "POST",
url: 'b.php',
data: { ch : a },
success: function(data){
alert(data);
}
});
}
</script>
In your b.php file use `$_POST['ch']` as you want
<?php
echo $_POST['ch'];
?>