I want to load a dynamic content to specific div name with multiple querystring from a menu.
Example dynamic menu link
index.php?tag=2
index.php?category=1&tag=2
index.php?category=2&tag=2&location=3
Example query process in PHP for link index.php?category=1&tag=2
$tag = intval($_GET['tag']);
$cat = intval($_GET['category']);
if(isset($tag) && isset($cat)) {
$select = $db->query("SELECT * FROM table WHERE cat=".$cat." AND tag=".$tag."");
... // fetch results
}
Question - With jQuery how to tell user clicked the link then send the callback to PHP process & show the results in the specific div name without refresh the page.
Let me know
Description
You have to create another php page that returns data in json format for the given substring. Your substring is dynamic so you have to get the substring from another element. I suggest a <input type="hidden" value="YourQueryString"/>, its simple. You can put the element next to your link and get the value using jQuery.val().
Then you use jQuery.ajax() / jQuery.get() or jQuery.post() in your index.php to get the data from that page / script. (jQuery.get() and jQuery.post() uses jQuery.ajax() internally)
In the callback method of jQuery ajax you grab the data and build the html from it.
After that you can use jQuery.html() to set the data to your div.
Sample
html / php
<a class="AnyClassName">Click me</a>
<input type="hidden" value="category=1&tag=2"/>
jQuery
$(".AnyClassName").click(function() {
// lets get the query string
var queryString = $(this).next().val();
$.ajax({
url: "yourNewPage.php?" + queryString,
context: document.body,
success: function(data){
var generatedHtml = "..." // build your html from the data object
$("#IdOfYourDiv").html(generatedHtml);
}
});
});
Update
Alternatively your php page can return html (simple page) for your query string. This is easier than build html in the jQuery Ajax Callback. If this is done you can do this
$(".AnyClassName").click(function() {
// lets get the query string
var queryString = $(this).next().val();
$('#IdOfYourDiv').load("yourNewPage.php?" + queryString);
});
More Information
Documentation
jQuery.ajax()
jQuery.post()
jQuery.get()
jQuery.load()
jQuery.html()
jQuery.val()
jQuery.next()
Tutorials
jQuery, Ajax, Json and Php
Use jQuery and PHP to build an Ajax-driven Web page
Use one of jQueries many AJAX functions, for instance:
$.post("ajax.php", "category=1&tag=2",
function(data) {
alert("Data Loaded: " + data);
});
Check:
http://api.jquery.com/jQuery.post/
Your PHP script should return the HTML you want to load into the div; the JS looks like this:
$('#your_menu').on('click', 'a', function(e) {
var $this = $(this),
url = $this.href;
$.ajax({
url: url,
success: function(html) {
$('#div_to_update').html(html);
}
});
});
It gets the URL from the link you clicked in the menu, passes the URL to the Ajax call, and fills the target div with the HTML response. See here for more info on this topic.
You can use jQuery.load() for this (Javascript - client side):
$('#id_of_the_div').load('index.php?category=1&tag=2');
Check out the http://api.jquery.com/load/ for more.
Related
I already checked around for this answer but all are different problems just same title (to prevent random duplicate marks).
Here is an ajax call to the click of the filter button that should send the data inserted in the form formmatcat to the php file formfilt.php and should load the result in a div with id resultins
<script>
$(function () {
$('#filter').on('click', function(event){
event.preventDefault();
$.ajax({
type: 'post',
url: 'formfilt.php',
data: $('#formmatcat').serialize(),
success: function () {
$("#resultins").load('formfilt.php');
}
});
});
});
</script>
I set the preventdefault to load only in the div without redirecting to the php file and this works but if I put the preventDefault it echoes the string I build by concatenating values sent from the form with those empty values. The strange thing is that if I remove preventDefault of course it redirects and loads the php file but with the correct values:
Moral of the story, data in the form with the ajax call goes correctly to the php file but looks like preventDefault don't let this. Thanks in advance
Here's the structure of the html part with the form
<form id="formmatcat" method="post" action="formfilt.php">
.
.
various textboxes
.
.
</form>
What you're doing is sending an AJAX request toformfilt.php, when this call happens and it returns a response it will be stored as a parameter within the success or $.done function as I'll mention later, that is where your echo'd content will be.
What you're doing here is when the call is successful, you simple send a GET request to the same page. Since that GET request differs from the AJAX POST request and has no POST parameters you'll not get the correct output.
By simply submitting the form and letting it go to the page rather than cancelling the request you're getting the right values as you're directly posting to the page with the correct values, when you call the load function you're doing a seperate AJAX get request.
What load actually is, is a rough equivelant to $.get which is shorthand for $.ajax.
Looking at jQuery AJAX docs
jqXHR.done(function( data, textStatus, jqXHR ) {});
An alternative construct to the success callback option, the .done() method replaces the deprecated jqXHR.success() method. Refer to deferred.done() for implementation details.
Basically, a $.ajax() call returns a promise object that you can chain callbacks on when it is finished. Also note that data here will be the actual content within your PHP file, thus if you rewrite your AJAX call like so:
<script type="text/javascript">
$(function() {
$('#filter').on('click', function(e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'formfilt.php',
data: $('#formmatcat').serialize()
}).done(function(data) {
$('#resultins').html(data);
});
});
});
</script>
It will then continue to load the output of formfilt.php into the div with ID resultins.
dont use form, use input without form, and use button tag use onclick to run function, if you use form, it will submit and redirect,
i'm not good with ajax on jQuery
but if i were to use javascript/XHR
var CB=document.getElementById("filter").value; //get input/filter value
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200)
document.getElementById('contain').innerHTML=xhttp.responseText;
};
var url="formfilt.php?filter="+CB;
xhttp.open("GET", url, true);
xhttp.send();
if you want to use post :
xhttp.open("POST", "formfilt.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send('filter='+CB);
sorry, i'm also learning, and new to this, just learning a week ago,
My PHP page
<ul id="upvote-the-image">
<li>Upvote<img src="image.png" /></li>
</ul>
is currently successfully sending variable to javascript
$("#upvote").each(function(index) {
var upthis = $(this).attr("rel");
var plusone = upthis;
$.post("upvote.php", {
'plusone': plusone
});
alert(plusone);
});
(The alert in the code is for testing)
I have multiple images using the rel tag. I would like for each to be able to be upvoted and shown that they are upvoted on the page without loading a new page.
My question, and problem: what is my next step? I would just like to know how to send a value to upvote.php. I know how touse mysql to add an upvote, just not how to send a value to upvote.php, or even if my javascript code opens the page correctly.
thanks
I think you need something like this:
<ul id="upvote-the-image">
<li><span rel="50" id="upvote">Upvote</span><img src="image.png" /></li>
</ul>
<span id="result"></span>
$("#upvote").click(function(index) {
var upthis = $(this).attr("rel");
var oOptions = {
url: upvote.php, //the receiving data page
data: upthis, //the data to the server
complete: function() { $('#result').text('Thanks!') } //the result on the page
};
$.ajax(oOptions);
}
You dont need an anchor, I changed it for a span, you can test asyc connection using F12 in your browser
Your javascript never opens the php page, it just sends data to it, and receives an http header with a response. Your php script should be watching for $_POST['plusone'] and handle database processing accordingly. Your next step would be to write a callback within your $.post function, which I recommend changing to the full ajax function while learning, as it's easier to understand and see all the pieces of what's happening.
$.ajax({
type: 'POST',
url: "upvote.php",
data: {'plusone': plusone},
success: function(IDofSelectedImg){
//function to increment the rel value in the image that was clicked
$(IDofSelectedImg).attr("rel")= upthis +1;
},
});
You'd need some unique identifier for each img element in order to select it, and send it's id to the php script. add a class instead of id for upvote and make the id a uniquely identifiable number that you could target with jquery when you need to increment the rel value. (From the looks of it, It looks like you're putting the value from the rel attribute into the database in the place of the old value.)
A good programming tip here for JQuery, Don't do:
<a href="javascript:return false;"
Instead do something like:
$(function(){
$('#upvote').on('click', function(event){
event.preventDefault();
$.post('upvote.php', {'plusone': $(this).attr('rel')}, function(data){
alert('done and upvoted');
});
});
});
That is a much better way to handle links on your DOM document.
Here are some Doc pages for you to read about that coding I use:
http://api.jquery.com/on/
http://api.jquery.com/jQuery.post/
Those will explain my code to you.
Hope it helps,
I need to know how to use jQuery's "load" AJAX function to get the wanted data in a variable?
Should look like this in the end:
var data = "->load data<-";
Thanks!
The load method is there to directly append the data to a jQuery element. Instead you could use jQuery.get or jQuery.post to issue a GET or POST request. Eg.
$.get("url.to/load/from", { param: "Hello" }, function(data){
var loadedData = data;
});
It's a bit difficult to say what you're asking here...
There are 2 load functions in jQuery's core.
If you want to get some data through an ajax call, you should take a look at other jquery ajax methods such as get,post,ajax... and so on:
var data = null;
$.get(url,params,function(response){
data = response;
});
If you want to listen to an load event (such as when the window or an image is loaded) you can do something like :
var data = null;
$(window).load(function(){
data = 'some data';
});
Use http://api.jquery.com/jQuery.get/ or jQuery.post with callbacks to store data into variable.
I hope it will help you
.load is specifically a convenience wrapper to place data directly into a DOM element, without needing to go through custom functions to do so. Use one of the other AJAX methods, like .get.
I have successfully implemented jQuery post
$.post("loadurl.php", { param: value },
function(data) {
alert("Data Loaded: " + data);
});
});
This question already has answers here:
using php include in jquery
(2 answers)
Closed 9 years ago.
My problem is that I need to include a PHP file inside a DIV when a button is pressed without the page reloading.
There is even more explanation in the 'Jsfiddle' file.
Below is an included Jsfiddle document.
http://jsfiddle.net/jjygp/5/
Thanks for your time. I am more than happy to provide any information upon request.
See here for your updated jsfiddle
You had marked the change button with a name of Change but were trying to select it with an id of change. Also, you had not told jsfiddle to include jQuery.
Try the following:
<button name="Change" id="Change">Change Div</button>
You are specifying a click function on an id, but no id is set on the button.
You can try with load() function in jquery
http://api.jquery.com/load/
PHP is a server-side script language, which will be executed before a JavaScript script did.
Therefore, you cannot use .load() to execute a PHP code, however, you may try .ajax() to create an AJAX request to the server which can implement the PHP code.
Please see http://api.jquery.com/jQuery.ajax/ if you have trouble on using .ajax().
Note: in .ajax() method, there is a setting called beforeSend, which "can be used to modify the jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object before it is sent". Hope this method helps you in any way.
Then, your JavaScript code will be like this:
$(document).ready(function(){
$("#Change").click(function(){
//doing AJAX request
$.ajax({
url:"include/start10.php",
beforeSend:function(){
$('#myDiv').fadeOut('slow');
},
success:function(data){
// do something with the return data if you have
// the return data could be a plain-text, or HTML, or JSON, or JSONP, depends on your needs, if you do ha
$('#myDiv').fadeIn('slow');
}
});
});
});
You cannot include PHP file with AJAX, but instead the response of the AJAX server-side script, which is the PHP (which has the same effect).
Loading...
The JS file (code):
function ajaxalizeDiv()
{
$.ajax({
type: "get",
url: "/path/to/the/php/you/want/to/include",
data: {
// Anything in json format you may want to include
id: myvarwithid, // descriptive example
action: "read" // descriptive example
},
dataType: "json",
success: onAjax
});
}
function onAjax(res)
{
if(!res || !res.text)
return;
$("#mydiv").html(res.text);
}
And here goes the PHP file:
<?php
$id = (int) #$_GET['id']; // same as in data part of ajax query request
$action = #$_GET['action']; // same as in data part of ajax query request
$text = 'click me';
// Note this is short example you may want to echo instead of die
// You may use not JSON, but raw text. However, JSON is more human-friendy (readable)
// and easy to maintain.
// Note also the array keys are used in the onAjax function form res (response).
die(json_encode(array('text' => $text /* and anything else you want */)));
?>
I need to create a page that will load divs from an external page using Jquery and AJAX.
I have come across a few good tutorials, but they are all based on static content, my links and content are generated by PHP.
The main tutorial I am basing my code on is from:
http://yensdesign.com/2008/12/how-to-load-content-via-ajax-in-jquery/
The exact function i need is as follows:
Main page contains a permanent div listing some links containing a parameter.
Upon click, link passes parameter to external page.
External page filters recordset against parameter and populates div with results.
The new div contains a new set of links with new parameters.
The external div is loaded underneath the main pages first div.
Process can then be repeated creating a chain of divs under each other.
The last div in the chain will then direct to a new page collating all the previously used querystrings.
I can handle all of the PHP work with populating the divs on the main and external pages.
It's the JQuery and AJAX part i'm struggling with.
$(document).ready(function(){
var sections = $('a[id^=link_]'); // Link that passes parameter to external page
var content = $('div[id^=content_]'); // Where external div is loaded to
sections.click(function(){
//load selected section
switch(this.id){
case "div01":
content.load("external.php?param=1 #section_div01");
break;
case "div02":
content.load("external.php?param=2 #section_div02");
break;
}
});
The problem I am having is getting JQuery to pass the dynamically generated parameters to the external page and then retrieve the new div.
I can currently only do this with static links (As above).
I'm not sure if you've solved this already, but I'm surprised no one's mentioned to use the ajax() function.
This would allow you to define the request type as GET:
function loadContent(id) {
$.ajax({
type: "GET",
url: "external.php",
dataType: 'html',
data: {param: id},
success: function(html){
$("#container").html(html);
},
error: function(){
},
complete: function(){
}
});
}
Just call this function instead of using load. Obviously you'll have to tinker with the code (mainly what goes in the success function) a little, but this should give you a good starting point.
You can use the optional data argument to pass parameters to the GET request. Read the documentation. This is far better than building the URL yourself. You can of course add dynamic generated data to the parameters list.
function loadDiv(evt)
{
// these params will be accessible in php-script as $_POST['varname'];
var params = {name:'myDiv', var1:123, var2:'qwer'};
$.post('http://host/divscript.php', params, onLoadDiv);
}
function onLoadDiv(data)
{
$('#myContainer').html(data);
}
$(document).ready(function() {
$('#divButton').click(loadDiv);
});
In this example server-side script should return inner content of your div. Sure you can return XML-serialized data or JS to eval etc... it depends on task. The example is simplified, so extend it to fit your needs.
This tutorial on loading AJAX content is good:
http://net.tutsplus.com/tutorials/javascript-ajax/5-ways-to-make-ajax-calls-with-jquery/
Especially the part explaining how to read the results with Firebug.
Use this :
function GetDiv(id) {
$.ajax({
type: "GET",
url: "external.php"
dataType: 'html',
data:id,
success: function(html){
$("#container").append(html);
},
});
}
var params = {
param: 1,
otherParam: 2
};
content.load("external.php #section_div01", params);
will load "external.php?param=1&otherParam=2"