Php call itself many times through ajax call - php

I have a php file which makes calls to itself with ajax through a click event.
Due to these calls the jquery code (all the code that i have inside the script tags) is repeated, as a consequence the jquery code to be executed many times.
I want to execute the script only the first time that i call the php file.
Please help me with this.
I can also post part of my code.
Thanks in advance!
Sorry for my omission. I use jquery tabs which are created like this
<div class='tabs'>
<ul>
<li>First</li>
<li>Second</li>
<li>Third</li>
</ul>
<ul>
<li>First</li>
<li>Second</li>
<li>Third</li>
</ul>
</div>
The php file functions.php has jquery ajax call
$( ".decision_button > input" ).click(function() {
var responseSubmit = $.ajax({
url: 'functions.php',
type: 'POST',
data:'comments='+comment_select,
async: false
}).responseText;});
So every time click on href the file is called and the jquery code is repeated.
I hope this was clear.
Thank you

When calling the page from JavaScript (AJAX) add some parameters to you url, so PHP script can distinguish is it called by user or by "itself". For example if your page is your-domain.com/index.php from JavaScript you open it as your-domain.com/index.php?ajax=1.
Then in PHP find all places where you echo JavaScript code and put it in if statement:
if(!isset($_GET['ajax'])){
echo "JAVASCRIPT code goes here";
}

You could add a GET parameter to your Ajax call:
if (!isset($_GET['repeat']) || $_GET['repeat'] != 'false') {
echo '$.ajax("test.php?repeat=false", ...)';
}
(assuming you use jQuery).
Of course, you could use a POST parameter as well if you like. This way, php will print the jQuery Ajax call only if it hasn't been called via Ajax.

Related

Execute php function only when clicked (wordpress)

For one of my wordpress site php files, I have the following code:
<div class="tabs">
Items
</div>
<div class="section" id="tab1">
<?php get_template_part('page/tab1'); ?>
</div>
So, it will call the tab1.php file into the div id="tab1"section.
However, I want to make it so that the get_template_part is only executed or called when the Items tab is clicked.
What would be the jQuery to call or execute the get_template_part function?
EDIT:
So, what I am trying to achieve is similar to Ajax. Since the get_template_part function won't be called till the "Items"tab is clicked, the browser does not have to call unnecessary files and slow down the page.
Let me know if you think this is the best way to do it.
Thanks!
Though the idea behind is already illustrated by Raphael in his answer, I intervene to add some details.
the best way to use AJAX with Wordpress is to use its built-in way of handling it, and that by sending requests to wp-admin/admin-ajax.php( I know the “admin” part of the file name is a bit misleading. but all requests in the front-end (the viewing side) as well as the admin can be processed in admin-ajax.php, with a lot of benefits, especially for security. And for the server-side code php that will be executed, it should be placed in functions.php.
Your jQuery code will look something like:
$(document).ready(function() {
$('.tabs a').click(function(e) {
e.preventDefault();
var tab_id = $(this).attr('id');
$.ajax({
type: "GET",
url: "wp-admin/admin-ajax.php",
dataType: 'html',
data: ({ action: 'yourFunction', id: tab_id}),
success: function(data){
$('#tab'+tab_id).html(data);
},
error: function(data)
{
alert("Error!");
return false;
}
});
});
});
infunctions.php of your theme (or directly in your plugin file), add:
add_action('wp_ajax_yourFunction', 'yourFunction');
add_action('wp_ajax_nopriv_yourFunction', 'yourFunction');
and define in the same file yourFunction callback function like this:
function yourFunction() {
// get id
// your php code
die();
}
For the javascript part, take a look at ajax() and its shorthand get(). And for the best practices using AJAX with Wordpress, there are many tutorials on the web (I will be back to give one). Good luck
Edit:
As it is mentionned by Karl, you can use .load() instead of ajax(), It should be noted that .load() is just a wrapper for $.ajax(). It adds functionality which allows you to define where in the document the returned data is to be inserted. Therefore really only usable when the call only will result in HTML. It is called slightly differently than the other as it is a method tied to a particular jQuery-wrapped DOM element. Therefore, one would do: $('#divWantingContent').load(...) which internally calls .ajax().
But my original answer is on how to organize php code respecting Wordpress best practices.
You can't really call a PHP function from javascript because by the time the browser sees the page, the PHP has already executed (or in your case, not executed )
The only way for you to do what you want is to spin the PHP function off into a separate script and then call that file using AJAX. Have the script echo HTML, and then insert the HTML into the tab1 div in the AJAX callback.
I think the easiest solution for you would be to use the jQuery load() function. It is the easiest way to achieve what you describe. The only issue that when someone clicks the header, there will be a delay to get the subitems as they do not exist yet (which would be the case for any situation where you delay the load.
HTML:
<div class="tabs">
Items
</div>
<div class="section" id="tab1"></div>
JS:
$(function () {
//wait for the page to finish loading
$('#items_id').click (function (e){
//watch for the items header to be clicked
e.preventDefault();
//prevent it from opening a link
$('#tab1').load('tab1.php');
//load the tab1.php file, or whatever file INTO the div
});
})

Refreshing a particular <span>'s content using ajax?

I am developing a web app that has some messages. In the menu, I have displayed the message number as follows.
<ul class="menu">
<li>Messages <span id="count" class="pull-right">3</span></li>
</ul>
On the other hand I have a php file that outputs only the message count. I want to update span#count using this php file on click of a button with class .jm-msg
I have jquery loaded on my page. As I am very new to AJAX and Javascript, I have absolutely no clue on how to do this. Can someone please guide me by providing sample code?
This is pretty easy:
setInterval(function(){
$.post("yoururl", function(resp){
$("yourspanid").html(resp);
});
}, 1000)
Your url needs to be set to the file where you load the data from
If you want to keep the span data uptodate simply use setInterval().
You should use setInterval over your whole $.post not just the function
This is a one-liner:
$('.jm-msg').on('click', function() {
$("#count").load('/getCount.php');
});
Documentation: http://api.jquery.com/load/

PHP/AJAX: Can't seem to be able to display ajax result into DIV, but works in ALERT()

I'm currently learning PHP through a real website project and want to use Ajax calls to change sections of the website.
CODE SAMPLE
myproject.js
$(document).ready(function() {
$("#inventory").click(function() {
$.ajaxSetup({
url: "sectionhandler.php?section='inventory'",
type: "get",
dataType: "html"
});
$.ajax().done(function(html) {
alert(html); // This works!
$("#section").html(html); // This doesn't work.
$("#section").append(html); // This neither.
});
});
});
inventory.html
<table><tr><td>Hello world with AJAX!</td></tr></table>
sectionhandler.php
<?php echo file_get_contents( 'inventory.html' ); ?>
menu.html
<a id="inventory" href="">Inventory</a>
index.php
<div id="menu" class="content"><?php echo file_get_contents( 'menu.html' ); ?></div>
<div id="section" class="content"></div>
RELATED ARTICLES FOUND AND READ AND TRIED
XMLHttpRequest won't work in IE 7/8 but works in other browsers
jQuery.ajax()
jQuery.ajaxSetup()
.append()
jquery .html() vs .append()
Can't append HTML code into one div by using jQuery
Add Html to Div with effect jQuery
Use append() to add text/html to an element with jQuery
And there are many many more...
RESULT
When I click on the Inventory link contained within menu.html and displayed through index.php, the jQuery code executes just fine. I get the result from the server while displaying the right content from inventory.html in the alert().
However, when I come to either set the innerHTML to the <div id="section" class="content"></div>, I can't seem to be able to get the expected result. The background of the page seems to flash, though not supposed to as per Ajax definition, and the content of my XMLHttpRequest.responseText never get displayed.
The closer I got to make it work was when I was double-clicking on the Inventory link, so that after the first "flash" from the page background, it showed the content of my section.
I have tried multiple ways using classic Javascript with an onclick element on my <a> tag, I have tried with document.getElementById("section"), though getting the right element, I was not able to show my content on the page.
Any thoughts are welcome!
Thanks in advance ! =)
With all chance, you need to prevent browser default behavior:
$("#inventory").click(function(event) {
event.preventDefault();
...
});
Notice the event parameter added to the click handler.
By the way, you HTML response is invalid - a <table> should contain a <tbody> element wrapping any <tr>s.
As requested. A more simple solution
$("#section").load("sectionhandler.php?section=inventory");
jQuery .load()

How does this AJAX script pass a variable via post to the PHP script?

I am going through this tutorial
http://www.9lessons.info/2009/04/exactly-twitter-like-follow-and-remove.html
on how to implement a twitter-like follow/unfollow button.
I am also completely new to AJAX and so I am kind of figuring it out as I go along.
Usually one passes variables through a form and sets the action to POST and then does stuff with PHP.
Here however, there is this section of javascript (for following a user)
<script type="text/javascript" >
$(function()
{
$(".follow").click(function(){
var element = $(this);
var I = element.attr("id");
var info = 'id=' + I;
$("#loading").html('<img src="loader.gif" >');
$.ajax({
type: "POST",
url: "follow.php",
data: info,
success: function(){
$("#loading").ajaxComplete(function(){}).slideUp();
$('#follow'+I).fadeOut(200).hide();
$('#remove'+I).fadeIn(200).show();
}
});
return false;
});
});
</script>
and say we have this section of html/php
<?php
$sql=mysql_query("Some SQL Statement that grabs users");
while($row=mysql_fetch_array($sql))
{
$id=$row["user_id"];
?>
<div id="follow<?php echo $id;?>">
<a href="#" class="follow" id="<?php echo $id;?>">
<span class="follow_b"> Follow </span></a>
</div>
<div id="remove<?php echo $id;?>" style="display:none">
You Following <a href="#" class="remove" id="<?php echo $id;?>">
<span class="remove_b"> remove </span></a>
</div>
<?php
}
?>
What is the POST variable needed by follow.php called? What does "success" do and how does it interact with follow.php?
PHP will receive a POST variable called 'id', which has the value that was stored in the page element with id ID.
The success handler is a script construct saying 'execute this code if the ajax request succeeded'. There's also an 'error' equivalent which only executes if something blew up. success by itself does not interact with PHP. It's simply some code that happens to be run if the PHP script does not return an error code.
Many ajax scripts indicate success/failure by manipulating the HTTP error code of the response. 2xx = everything ok, invoke the success handler. Anything 4xx or 5xx would invoke the error handler.
I believe you want $_POST['id'] to access your id parameter that was passed in.
"success" is called when your follow.php script completes successfully.
The jQuery ajax call will encode data as a POST and send it to your PHP script. It seems like in this case the script is on the same page, so I'm guessing it will ping itself. AJAX does this asynchronously (by definition).
The success function is fired when the ajax receives a response from the php page. It's how you know the data has made the round trip, and any data you expect from the php script was received. This is where you would want to put whatever functionality comes next sequentially, or anything dependent on the data you're getting back from .php.
This explains the parameters of the $.ajax() call: http://api.jquery.com/jQuery.ajax/
The post you included isn't a tutorial, it's simply a snippet of the code he uses. For actual tutorials of the Jquery Ajax function, try this tutorial:
http://net.tutsplus.com/tutorials/javascript-ajax/5-ways-to-make-ajax-calls-with-jquery/

Get php results with jquery ajax

I don't know why I am having a hard time with this, but it's about time I came up for air and asked the question.
What is the best way to call a php file with jquery ajax, have it process some inputs via $_GET, return those results and again use ajax to replace the content of a div?
So far, I can call the php file, and in the success of the jquery ajax call I get an alert of the text.
$.ajax({
url: "xxx/xxx.php",
type: "GET",
data: data,
cache: false,
success: function (html) {
alert("HTLM = " + html);
$('#product-list').html(html);
}
});
I set the php function to echo the result, the alert spits out the html from the php file. But I get a side effect. I get the code that the php generated echoed at the top of the page. So php is doing it's job (by echoing the content). Next jquery is doing it's job by replacing the div's content with the values from the php file.
How do I stop the php file from echoing the stuff at the top of the page?
Sample code being echoed from php and alerted in the success of jquery ajax
HTML =
<div class="quarter">
<div class="thumb">
<a href="productinfo.php?prod-code=Y-32Z&cat=bw&sub=">
<img src="products/thumbs/no_thumb.gif" alt="No Image" border="0" />
</a>
</div>
<div class="labels"><span class="new-label">New</span></div>
<p><span class="prod-name">32OZ YARD</span></p>
<p><span class="prod-code">Y-32Z</span></p>
</div>
Thanks!!!
-Kris
Are you including your php file that you use for your ajax call at the top of the page? If so you dont need to. That would cause the data to dump at the top.
Ask your question :)
EDIT TO ANSWER QUESTION
<div id="product-list">
<?php include 'products.php' ?>
</div>
Your ajax function will now overwrite the php content when it runs and outputs to #product-list
If you mean you want to avoid showing the header and body tags, just the contents, you need to detect when the request is AJAX at PHP side.
Some pseudo-code is:
IF (!IS_AJAX)
HTML
HEADER
BODY
ENDIF
CONTENTS
IF (!IS_AJAX)
/BODY
/HTML
ENDIF
Search for HTTP_X_REQUESTED_WITH here at stackoverflow
Your question isn't exactly clear, but it sounds like you only want to use PART of the response data. If that's the case, then there's 2 ways to go about it:
First, you can check on the PHP side if it's being requested via AJAX. This is the solution I'd use, since it prevents useless data being transferred to the client:
define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
...
if(!IS_AJAX) {
// anything here will NOT be sent in response to ajax requests
}
Alternatively, you can mark the part of the response data you wish to use with an ID, then search the returned data for that id:
<h1>Don't care about this</h1>
<div id="use_this">This is the useful data.</div>
Then for your ajax response callback:
success = function(data) {
data = $(data).find('#use_this');
// do whatever
}

Categories