PHP and AJAX - make ajax call on load of a document - php

Can I make an AJAX call immediately after loading a page? To be more specific, I have an ajax action on click of some html tag (say in page 1). Now when I come to the same page (page 1) from some other page (say page 2), (i.e.. on ready of the document) can I make that ajax call which is present in the onclick of that appropriate html tag? I am using PHP as server side script..
There were confusion on my question.. Let me explain more.
I have an phtml page where there are lot of ajax calls on click of various tags.
Lets say, tag1 has send-message functionality ajax call which on click loads a compose message part of html.
Similarly tag2 has photo display funcitonality ajax call which on click loads the photo display part of html.
Now I'm in page 2 which is a search result page Where I have a link for page 1. That link is send-message link. So now I have to come to page 2 and with compose message part html loaded. I want to load it via ajax which will be performed on clik of the send-message link (tag 1)in page 1. How to accomplish this? How will I inform to page 1 to load the compose message part of html through ajax?

you can call that function explain below
<script type="text/javascript">
function_name();
</script>

Im not sure what you want to achieve here but if you're asking if you could do AJAX on ready of the document, then i think you can..

Check this out in jquery
$(document).ready(function(e) {
$.ajax({
type:'POST',
url:g_site_path+'search/agentpopup',
dataType:'html',
data:data,
success:function(html){
$("#agentpopup").html(html);
}
})
}

$_SERVER['HTTP_REFERER']
Is the php data-feild that will tell from where the page request is coming (Ex. Page 2 has requested Page 1). Note that HTTP-Referer is by its very nature risky and can easily be spoofed. To test for document ready, you can use something like jQuery
$(document).ready(function() {
$.ajax('your_ajax_script.php', function(result) {
/* Do what ever you want to do of result*/
console.log(result);
});
});

Related

PHP contact form needs to call Javascript to show a hidden div on main .html page

I have a one page website in the works that has a contact form where its contact error and contact thank you messages are placed further down the page as hidden divs.
The contact form calls an external php file that calls the anchor links of the error and thank you message divs in the index.html file.
www.photograsurfer.com/test/index.html
www.photograsurfer.com/test/code/contact-panel.php
Everything works successfully as long as the divs are not hidden. So now I need to use the following javascript to get the hidden divs to display when needed.
<script type="text/javascript">
function showContactPanelError() {
document.getElementById('contact-panel-error').style.display = "block";
}
</script>
My problem, besides being a complete PHP beginner, is that I don't know how to get the PHP file to reference the Javascript code to display the hidden divs properly on the main page.
Any help is appreciated.
Thanks.
Use jQuery forms (http://malsup.com/jquery/form/) to submit your form via AJAX, then show/hide divs depending on values you return from PHP scripts.
you could assign php variable to javascript as
var error="<?php echo $_GET['error']; ?>";
the $error is the data passed along with the url like wwww.example.com/test.php?error=1
Now you could check var error and call your function showContactPanelError().
I ended up going with a mixture of the 2 methods on these pages.
http://trevordavis.net/blog/ajax-forms-with-jquery
https://spruce.it/noise/simple-ajax-contact-form/#contact
Ditched the div idea since the Ajax method allowed me to not reload the page and enter error and thank you messages within the contact form itself. Seemed like an easier approach.
Thanks for all of the suggestions, as I never would have looked at using Ajax otherwise.
You can add a onclick event on submit button. On clicking it will create an ajax call send data to the required external PHP file and then on success will display the hidden division properly on the main page.
here's a sample code just for an explanation
**
* Description : Function that will trigger the AJAX request.
* #param none
*/
function CategorySubscriber_Unsubscribe(){
var data = {
'data-1': data-1,
'data-2': data-2,
// as per your need you can put any number of data
};
var url = // your url
jQuery.post(url, data, function(response){
jQuery.show("#your-div-id");
});
}
function(response) will be executed when ajax call will be in success status.
You can learn it from these links
http://www.w3schools.com/jquery/ajax_post.asp
http://api.jquery.com/jQuery.post/

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!

Loading pages into a div with JQuery, existing Javascript not working

I have a page I'm working on where a user clicks a link and it loads a new php file into an existing div. It works but the page that loads into the div will not function with existing Javascript stuff in the page.
I can include the
<script type="text/javascript" src="js/admin.js"></script>
into the loaded pages but when you flick back and forth between the pages I notice that RAM usage starts to go up and up, so I don't think this is the best way of doing it.
Any ideas how the loaded page can function with the already-loaded javascript from the index page?
Thanks!
bind your events like this :
$(document).on({
"event" : function(e) {},
...
}, "selector");
If you are using bind or click type events change to using something like on (or live or delegate if you are required to use jquery version less than 1.9)
OR/AND
In your function that loads in the page via ajax provide a call back that initiates only what is needed. Example:
$('#myDiv').load('ajax/page.php', function(){
$('#myDiv a').customPlugin('whatever');
$('#myDiv button').bind('click', function(){
window.open('http://www.google.com/', 'some-window');
});
});

php javascript partial page reload

I have a page set-up, with several divs.
For now all we need is
<div id="main">...</div> & <div id="sidebar">...</div>
Each div has code such as:
<?php include("page.php") ?>
The main div does all the work, and includes a JavaScript function. E.g. at the moment the user can click a button to remember an item displayed in a table.
Am I able to only reload the sidebar instead of the whole page when the user calls this function?
I am posting the function here, and all I need now is to be able to refresh the sidepanel and its included php files if that is possible? I assume something along the lines of this could do the job? or am I wrong? load("#sidebar")
function saveToFavorites(code)
{
$.ajax({
async:false,
type: "POST",
url: 'formPostsUser.php?reqtype=addToFavorite',
data:'coursecode='+ code,
success: function(data)
{
$('.result').html(data);
if(data != "")
{
alert(data);
load("#sidebar")
}
}
});
}
Kind regards
Alex
Happy about any and every reply and hint ;)
First thing
<div="sidebar">..</div>
The above markup is wrong HTML. You should give the sidebar as the value of your properties such as id or class
<div id="sidebar">..</div>
Loading the Sidebar content
You can use jQuery ajax to load content of this div using jQuery load method like this
$(function(){
$("#sidebar").load("yourPHPPageToReturnSideBarContent.php");
});
Assuming yourPHPPageToReturnSideBarContent.php is the PHP page which renders the HTML Markkup for the sidebar. Note that this will load the content on the document ready event.
Loading the side bar content on an event
If you want to load it on a purticular event like a button click you can do it like this
$(function(){
$(document).on("click","yourButtonId",function(){
$("#sidebar").load("yourPHPPageToReturnSideBarContent.php");
});
});
The above script will load the side bar content on a button click. The button's id is e "yourButtonId" in this example.
Note that i used jQuery on here to bind the function because it will take care of current element and future element in case if you want to load the markup which contains the button dynamically.

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()

Categories