Jquery load dymanic content with parameter - php

I'm trying to load div content based on the a href being clicked and pass in a parameter. For example, Link 1
Clicking on Link 1 will pass value "3" to process.php, and return back the value "apple is good for you".
However, I can't seem to be able to pass the value without having a submit button. Anyway I can pass the parameter to another php file to process, and return the value?
$(document).ready(function(){
$("#testing a").live("click", function(evt){
var id= $(this).attr('id');
$.post("process.php", { id: id },
function(data) {
alert(data);
$('#result').load(data);
});
})
});
Below is my HTML
<div id="testing">
hello
</div>
<div id="result"></div>
Appreciate your help, thanks a lot!

You shouldn't be using numbers for id values. Instead, prefix them with a letter, or consider adding them to a data- atribute on the element.
Additionally, $.live() is deprecated, and we are encouraged to use $.on() from here on out for event delegation. I've gone ahead and handled this in the code below, but the id issue remains.
Lastly, $.load() and $.html() aren't the same. If you want to load data into an element, you don't call the load method (though the name could lead to that confusion).
// Short-hand version of $(document).ready();
$(function(){
// Handle anchor clicks on #testing
$("#testing").on("click", "a", function(e){
// Prevent links from sending us away
e.preventDefault();
// POST our anchor ID to process.php, and handle the response
$.post("process.php", { 'id': $(this).attr("id") }, function(data){
// Set the response as the HTML content of #result
$("#result").html(data);
});
});
});
From your process.php file, you might have something like the following:
$msg = array(
"...chirp chirp...",
"This is response number 1",
"And I am the second guy you'll see!",
"Apples are good for you!"
);
$num = $_POST["id"] || 0;
echo $msg[ $num ];

Related

SQL Query creates buttons that one can click to 'hopefully' change DIV

I am failing hardcore with describing this but here it goes..
I have home.php, pretty much just:
<body>
<div id='leftColumn'>
<?php include ('includes/roomQuery.php')
</div>
</body>
Now,
roomQuery.php echos my sql column 'room_name' from table 'rooms' as follows:
echo "<td>$roomName</td>";
Any of the room links will take me to room.php and populate the page with more queries respective to $roomName via $_GET.
room.php is basically:
$get = $_GET['room'];
$query
while($row = $result->fetch_assoc()){
echo $query
This is working perfectly for what it is.
====================================
however, I am trying to make my site flow better, and have been trying out the jQuery .load function. So far I have changed roomQuery.php to:
echo "<td><button>$roomName</button></td>";
here is my jQuery to replace home.php #page with room.php #page:
$(document).ready(function(){
$("button").click(function(){
$("#page").load("room.php #page",function(responseTxt,statusTxt,xhr){
if(statusTxt=="success")
alert("Success");
if(statusTxt=="error")
alert("Error: "+xhr.status+": "+xhr.statusText);
});
});
});
When I click any of the buttons that roomQuery.php spits out, it replaces #page perfectly but I cannot grasp how/if I can send $_GET['room'] to room.php so that when #page is loaded, the information is still respective to the room I clicked on. If I change jQuery to
$("#page").load("room.php?room=CL%20124 #page"
Then #page is populated with the data specifically respective to room CL 124. Is it possible to post the button text that is output from roomsQuery.php to room.php #page when the button is clicked?
Yes, you can pass data into the .load() call as the second parameter.
Firstly, you need to work out how to get the room ID from the DOM into your jQuery call, maybe you could use a data attribute on the button element like this:
<button data-room-id="123">Click me</button>
Then use jQuery like this:
$("button").click(function(){
// define your room ID here, however you do it
var your_room = $(this).data('room-id');
$("#page").load(
"room.php #page",
{
room: your_room
},
function(responseTxt,statusTxt,xhr){
if(statusTxt=="success")
alert("Success");
if(statusTxt=="error")
alert("Error: "+xhr.status+": "+xhr.statusText);
}
);
});
Edit: just noticed that you might actually be using the button's value as your room ID, if so, use this definition:
var your_room = $(this).val();
If you're expecting spaces or non-alpha numeric characters in this value, you might want to consider URL encoding it before you send it.

Reload div using jquery load function working only once and how to pass a variable

I have very limited knowledge with scripts so I hope you guys can help me with a simple solution to a small problem that I have...
I'm using the following jquery function to refresh a div with new content when a link is clicked
<script>
$(function() {
$("#myButton").click(function() {
$("#loaddiv").fadeOut('slow').load("reload.php").fadeIn("slow");
});
});
</script>
My problem is, I need to send 2 variables to the reload.php page to use in a mysql query (I have no idea how to accomplish that), also I need to make multiple links work with this function, at the moment I have multiples links with the same id and only the first link works so I guess I must associate different ids to the function in order for this to work, how can I do that?
here's the page where i'm using this: http://www.emulegion.info/teste/games/game.php
You may want to use document ready instead of function on your first line as this will make sure the code is not executed until the full page (and all elements) have loaded.
You can then use the callback functions of the fade and load to perform actions in a timely manner.
additional variables you can add after the .php, these can then be read in your reload.php file as $var1 = $_GET['var1'];
Do make sure to sanitize these though for security.
<script type="text/javascript">
// execute when document is ready
$(document).ready(function() {
// add click handler to your button
$("#myButton").click(function() {
// fade div out
$("#loaddiv").fadeOut('slow',function(){
// load new content
$("#loaddiv").load("reload.php?var1=foo&var2=bar",function(){
// content has finished loading, fade div in.
$("#loaddiv").fadeIn('slow');
}); // end load content
}); // end fade div out
}); // end add click to button
}); // end document ready
</script>
For different variables you could add a HTML5 style variable to your button.
<input type="button" id="myButton" data-var1="foo" data-var2="bar" />
You can retrieve this when the button is clicked:
// add click handler to your button
$("#myButton").click(function() {
// get vars to use
var var1 = $(this).data('var1');
var var2 = $(this).data('var2');
...
load("reload.php?var1="+var1+"&var2="+var2
if you have multiple buttons/links I would use class instead of id "myButton". that way you can apply the function to all buttons with the above script. Just replace "#myButton" for ".myButton"
First, you should use .on('click', function() or .live('click', function() to resolve your one click issue.
You'll want to do something like:
<script>
$(function() {
$("#myButton").on('click', function() {
var a = 'somthing';
var b = 'something_else';
$.post('url.php', {param1: a, param2: b}, function(data) {
//data = url.php response
if(data != '') {
$("#loaddiv").fadeOut('slow').html(data).fadeIn("slow");
}
});
});
});
</script>
Then you can just put var_dump($_POST); in url.php to find out what data is being sent.
Try creating a function that would accept parameters that you want.
Like:
$(document).ready(function(){
$('.link').click(function(){
reload(p1,p2);
});
});
function reload(param1, param2){
$("#loaddiv").fadeOut('slow').load("reload.php?param1="+param1+"&param2="+param2).fadeIn("slow");
}
But by doing the above code your reload.php should be using $GET. Also you need to use class names for your links instead of id.
<script type="text/javascript">
// execute when document is ready
**$(document).ready(function() {**
**$("#myButton").click(function() {**
**$("#loaddiv").fadeOut('slow',function(){**
**$("#loaddiv").load("reload.php?var1=foo&var2=bar",function(){**
// content has finished loading, fade div in.
$("#loaddiv").fadeIn('slow');
});
});
});
});
</script>
$("#myButton").click(function() {
// get vars to use
var var1 = $(this).data('var1');
var var2 = $(this).data('var2');

Run PHP code when user clicks link and pass variables

I need to run a PHP code from external server when user clicks a link. Link can't lead directly to PHP file so I guess I need to use AJAX/jQuery to run the PHP? But how can I do it and how can I pass a variable to the link?
Something like this?
<a href="runcode.html?id=' + ID + '"> and then runcode.html will have an AJAX/jQuery code that will send that variable to PHP?
use something like this in you page with link
Some text
in the same page put this somewhere on top
<script language='javascript'>
$(function(){
$('.myClass').click(function(){
var data1 = 'someString';
var data2 = 5;//some integer
var data3 = "<?php echo $somephpVariable?>";
$.ajax({
url : "phpfile.php (where you want to pass datas or run some php code)",
data: "d1="+data1+"&d2="+data2+"&d3="+data3,
type : "post",//can be get or post
success: function(){
alert('success');//do something
}
});
return false;
});
});
</script>
on the url mentioned in url: in ajax submission
you can fetch those datas passed
for examlple
<?php
$data1 =$_POST['d1'];
$data2 =$_POST['d2'];
$data3 =$_POST['d3'];
//now you can perform actions as you wish
?>
hope that helps
You can do this with an ajax request too. The basic idea is:
Send ajax request to runcode.html
Configure another AJAX to trigger from that page
Considering, this as the markup
<a id="link" href="runcode.html'">Test</a>
JS
$("#link").on("click", function() {
$.get("runcode.html", { "id" : ID }, function(data) {
//on success
});
return false; //stop the navigation
});

How to get variables in div loaded with AJAX

While working with jQuery and PHP a problem occurs with loading new data from "give-me-more-results-below-the-div.php".
I have the tooltips working below with '.live', but the values of the new loaded content are not available.
Now, how would one get info from new data, loaded in a div, but (naturally) not showing in the page code? :-)
As you can see, I only need three variables to pass: main_memberID, like_section and the like_id.
I'm seriously lost here. So any help is highly appreciated.
So far, I got this on the jQuery functioning part:
$(".ClassToLike img[title]").live('hover', function() {
$('.ClassToLike img[title]').tooltip({ position: 'center left', offset: [0, -2], delay: 0 })
});
$('.like_something').live("click", function (event) {
var value = $(this).attr ( "id" );
$(this).attr({
src: '/img/icons/checked.gif',
});
$(".tooltip").live().html('you like ' + this.name);
$.ajax({
type : 'POST',
url : 'like_something.php',
dataType : 'json',
data: {
main_memberID: $('#main_memberID').val(),
like_section: $('#like_section').val(),
like_id: this.id,
},
success: function(){ //alert( 'You have just clicked '+event.target.id+' image');
},
error: function(){
alert('failure');
}
});
});
I often id the div like
<div class="like_something" id="div_memberID_sectionName_anotherID"/>
Then
$('.like_something').live('click',function(){
var info = $(this).attr('id'); // get the id
var infoArr = info.split('_'); // split the id into an array using the underscore
// retrieve your values
var memberID = infoArr[1];
var sectionName = infoArr[2];
var id = infoArr[3];
});
To fix the problem, first open up your browser's requests panel, in Chrome it's a "Network" tab in Dev tools. When you click .like_something, is a request sent? And are there any console errors? If the request is sent, look at the Response tab and see what the server is sending back.
Also, you could store the data you need to send with the request in an attribute with the data- prefix, like this:
<a href="#" class="like_something" data-section="section" data-member-id="Member id">
...
</a>
This is most likely not your exact HTML, but you get how it works.
Then you can retreive it in the jQuery like this:
data: {
main_memberID: $(this).attr('data-member-id'),
like_section: $(this).attr('data-section'),
like_id: this.id,
},
I hope this helps!
Still getting the hang of working on this site, but this one is my closing (as posted under Nathan's answer):
Super thanks for the input you all! Nathan gave me the best way to retrieve and pass the info I needed. Again, this place is great. Thanks for all the efforts!

How to pass dynamic id text box value to another page without refreshing with jquery and php

$('.btncomment').click(function () {
var id = $(this).attr('id');
$.post('SaveTopicInformation.php', {
tid: commentform.(topic_ + id).value,
topicdetail: commentform.(topicdetail_ + id).value,
userid: commentform.(user_ + id).value
});
});
I have to pass the 3 text box value to another page. First of all, I display the all the record from database. then, I have comment link for each row. I like to give comment and save the comment for eache record. I use by jquery and php. please help me out. I can't finger out how to pass dynamic text box's value by bynamic name.
You cannot access object fields like that. You need to use the array subscript syntax:
$.post('SaveTopicInformation.php', {
tid: commentform['topic_' + id].value,
topicdetail: commentform['topicdetail_' + id].value,
userid: commentform['user_' + id].value
});
Actually, since you are using jQuery, using .val() on a jQuery object wrapping the form element would be much nicer.
Try this code sample. What it does is listen for your submit button to be pressed, then it grabs all of the content from a certain form, and submits it to a server:
//Listen for the submit button to be clicked
$('.btncomment').click(function () {
$.ajax({
'url' : 'SaveTopicInformation.php', //Processor URL
'type' : 'POST', //Send as POST-data
'data' : $('.myForm').serialize(); //Send the entire form
'success' : function(data) { //What to do when the form is submitted
if (data == 'success') {
alert('Form submitted!');
}
}
});
});
Hope that helps,
spryno724

Categories