Passing PHP variable to Jquery without refresh - php

I apologize upfront for my lack of jquery knowledge. In this website I am building, a user is presented with a number of thumbnail images representing plants. When a thumbnail is clicked, a jquery popup is initiated. What I would like to be able to do is pass a php variable that has the ID of the plant over to the jquery popup to display the prper information. Any help would be greatly appreciated. Thank you.
EDIT: http://www.plantcombos.com/header/main_index.php?display=random_mix

Im pretty sure you dont need to query PHP each time ... something like this would work :
<img class-"imgclick" src="/small-plant.jpg" data-id="123" />
This would be the output from your server side (php if thats what your using) - it stores the ID of the image in the data attribute
JavaScript :
$(document).ready(function() {
$('.imglink').click(function(event) {
event.preventDefault();
$('dialogid')
.data('image_id', $(this).data('id'))
.dialog('open');
})
})
the image id from the data attribute is then passed to the data attribute of the dialog. This attribute can be accessed using $(this).data('image_id') form within the dialog then

Use the jQuery AJAX method to gather data from a PHP file and display it on the page. It is very easy and you can pass any variables (parameters) you like to the page.
http://api.jquery.com/jQuery.ajax/
For example:
// This will send a request to a PHP page
$.ajax({
url: "http://example.com/test.php",
dataType: "html",
success: function(data){
// Place the returned data into your content
$('#image').html(data);
}
});

Related

Updating the dynamic PHP in a jQuery Mobile site after updating the database

Let's say I have 2 pages in a jQuery Mobile website.
Page1 - shows data from a database using inline PHP.
Page2 - inserts new data into the database.
The problem is that page1 is not updated when going back, after page2 adds something to the database. I can get it updated by pressing F5, but how can I achieve the same update using jQuery?
I think you're showing data in Page 1 using the pageinit event. This will fire only once and won't update your data every time you add new data.
You need to use pagebeforeshow event of Page 1 to get data from database. This way, new data will be brought every time, which is what you need. Here's a syntax :
$(document).on("pagebeforeshow", "#page1", function() {
//call to server
});
If you're not using pageinit, you must be using document.ready event to get data. Well, thats the way thats done. You must not use ready with jquery mobile. DOM ready will initialize the whole document which will make the ajax page change feature of jQM pointless & useless.
It was late last night and I missed that I should just get my inline php content using Ajax.
So this is how I solved it:
Moved everything contain dynamic content using PHP in a separate file.
Add an Ajax call to the bottom of the page that loads the PHP file as follows:
$(document).on('pagebeforeshow', function(){
$.ajax({
type: "GET",
url: "includes/db/ajax_show_php_content.php",
success: function(html) {
$("#page1").html(html); //Insert PHP content
$("#page1").trigger('create'); //Apply jQuery Mobile style to it.
});
});
Thanks to #hungerpain and #anglinb for their help in figuring this out.
I'm not extremely familiar with jQuery Moblie but here's what I found:
function refreshPage()
{
jQuery.mobile.changePage(window.location.href, {
allowSamePageTransition: true,
transition: 'none',
reloadPage: true
});
}
I think the reloadPage to true should do the trick.
If that doesn't work, check out this answer: jQuery Mobile Page refresh mechanism
Hope this helps!

onclick -> mysql query -> javascript; same page

I need button to begin a mysql query to then insert the results into a javacript code block which is to be displayed on the same page that the button is on. mysql queries come from the values of drop-down menus.
Homepage.php contains
two drop down menus
div id='one' to hold the results javscript code block
a button to stimulate the mysql query to be displayed in div id ='one' through Javascript
flow of the process is as such
1. user chooses an option from each drop down
2. when ready, the user clicks a button
3. the onclick runs a mysql query with selections from the drop down menu.
4. send the results as array from the mysql query into the javascript code block
5. display the results in div id ='one'
all of this needs to happen on the same page!
The problem I am having is that as soon as the page is loaded, the javascipt is static. I am unable to push the mysql results into the javascript on the page which I need it to appear on. Having everything on the same page is causing trouble.
I'm not looking for the exact code laid out for me, just a correct flow of the process that should be used to accomplish this. Thank you in advance!
I've tried
using both dropdowns to call the same javascript function which used httprequest. The function was directed towards a php page which did the mysql processing. The results were then return back through the httprequest to the homepage.
I've tried to save the entire Javascript code block as a php variable with the mysql results already in it, then returning the variable into the home page through HTTPRequest, thinking I could create dynamic javascript code this way. Nothing has worked
You need to use a technology called AJAX. I'd recommend jQuery's .ajax() method. Trying to do raw XHR is painful at best.
Here is how you'll want to structure your code:
Load the page.
User chooses an option.
An onChange listener fires off an AJAX request
The server receives and processes the request
The server sends back a JSON array of options for the dependent select
The client side AJAX sender gets the response back
The client updates the select to have the values from the JSON array.
Basically, HTTP is stateless, so once the page is loaded, it's done. You'll have to make successive requests to the server for dynamic data.
Use AJAX,
example
$.ajax({
type: "POST",
url: "yourpage.php",
data: "{}",
success: function(result) {
if(result == "true") {
// do stuff you need like populate your div
$("#one").html(result);
} else {
alert("error");
}
}
});
For this purpose you need to learn ajax.This is used to make a request without reloading the page.so that you can make a background call to mysql
your code will be something like that
$("#submitbutton").live("click",function(){
$.ajax({url:"yourfile"},data:{$(this).data}).done(function(data){
//this data will in json form so decode this and use this in div 2
var x =$.parseJSON(data);
$("#div2").html(x.val());
})
})
and "yourfile" is the main file which connect to server and make a database request
here is how I used an onchange method to stimulate a MYSQL query and have the Highchart display the result. The major problem was that the returned JSON array was a string that needed to be converted into an INT. The resultArray variable is then used in the data: portion of the highChart.
$(function(){
$("#awayTeam").change(function(){
$.ajax({
type: "POST",
data: "away=" + $("#awayRunner").val(),
dataType: "json",
url: "/getCharts.php",
success: function(response){
var arrayLength = response.length;
var resultArray = [];
var i = 0;
while(i<arrayLength){
resultArray[i] = parseInt(response[i]);
i++;
}
In the PHP code, the array must be returned as JSON like this
echo json_encode($awayRunner);

How to populate one form data into another form on same page before submit is clicked using ajax or js?

I am new to ajax and javascript.
I want to populate a entry form data into another form on the same page before it is submitted.
That means i want to display the name,gender etc of registration form in another form on the same page before it is submitted with click button event.
Please anybody post some examples.
(In response to your comment on the question above...)
Ah, that example is significantly more complex than previously implied. The target in that example isn't a form, it's an image. Do you have functionality in your server-side code already for generating the image?
Posting the AJAX to the server is very much the easy part in this case. Using jQuery for example, you can do something like this:
$.ajax({
type: 'POST',
url: 'somepage.php',
data: data,
success: function() {
alert('success!');
},
dataType: 'json'
});
The variable 'data' would be built from your form elements. Possibly something like this:
var data = '';
data = data + 'somevalue=' + $('#formElement').val();
data = data + 'anothervalue=' + $('#aDifferentElement').val();
// etc.
What the code essentially does is submit an HTTP POST to the supplied URL with the supplied data, and then run the supplied "success" function upon a successful result. You can also add an "error" function for an error result.
In your case, the result looks like it's an image. So you'd end up setting the src attribute on an img tag to the resulting image. Something like this:
$('#imageElement').attr('src', someString);
I'm not sure exactly how they're doing it in that example, but you can certainly look through the code and step through it in Firebug to see what you can find. The response appears to be the actual image, not a link to the image. But you can design yours either way.

how can I get just a single div to refresh on submit as apposed to the entire page?

I am working with a dynamically generated page written in PHP. The divon the page contain contents listed FancyBox links that open editing screens.
Once editing is complete and the user closes the FancyBox modal the changes
need to be reflected on the parent page.
Right, so I was able to find a solution that refreshes the entire page on submit
using
parent.location.reload (true);
to refresh the entire parent page. But, that causes a browser prompt
that is confusing to users and a bit of over kill as I really only
need the information edited to refresh.
how can I get just a single div to refresh on submit as
apposed to the entire page??????
You need to submit the form through AJAX. Since your using something that uses jQuery, you can use it to do it.
Here you can find a tutorial on how to do it
I think the best way is loading page fragments with .load().
something like,
$('#pageNeedToBeRefreshed').load('test.html #pageNeedToBeRefreshed');
User ,
It should be pretty easy
have a div place holder like below
<div id="dataToRefresh"> </div>
Once you close the dialog, have a event handler...
$('dataToRefresh').html('testing'); // give your data here
it should upate the parts of the page
let me know if you need anything else
please go thruogh .html api for more info
http://api.jquery.com/html/
Suppose you have the below div to refresh:
Then write
$("#dataToRefresh").load();
Might it will be helping you
Instead of using submit in html you can submit your form using the ajax -
$('#formid').submit(function(){
var data = $(this).serialize(); //this gives you the data of all elements of form in serialized format
$.ajax({
type: 'POST',
dataType:"json",
url: 'your url',
data: data,
success: function(data){
//replace the contents of the div you want to refresh here.
}
});
});
jQuery('#id_of_div').load('/url/to/updated/html');
See jQuery docs for load()

How can I add a simple counter function in javascript jquery?

I'm using Shadowbox a jquery overlay and I wanted to count how many people are actually using the overlay. Thus, I would need a function that would write a counter to a file or sending a query through a php api...
has to be a a php url api because I cant use php on the server where the overlay is.
So I need help with executing a javascript function on the overlay click, tips on how to make a counter query through GET method.
Thanks
<script type="text/javascript">
Shadowbox.init({
handleOversize: "resize",
overlayOpacity: 0.9
});
When you bind your click handler to open the shadownbox, add a binding for an ajax call, such as this:
$.ajax({
type: "GET",
url: "stats.js",
data: "name=urlOrNameOfItem"
});
Replace urlOrNameOfItem with something meaningful so you can track what has been clicked. I assume you know in php how to handle a query string.
See JQuery docs: http://api.jquery.com/jQuery.ajax/
Before you display your Shadowbox throw an Ajax query to a php script which would save the current request in a db (including $_SERVER info for better analysis).
This PHP script can fetch the current count of views for that image from the Db and update it accordingly.
I'm guessing the shadowbox function is called as a onclick event on your image so just add the Ajax call something like this:
$.ajax({
url: 'path-to-counter-script.php?i='+image-identifier,
success: function() {
//display shadowbox
}
});

Categories