Get php results with jquery ajax - php

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
}

Related

Php call itself many times through ajax call

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.

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

Using JQuery, AJAX and PHP

I am creating a PHP site and have ran into the following problem, i would like to be able to click a hyperlink on a page, send a small data item to a php script, have the script perform its function and then return the results.
I am using AJAX with this site to have each page load into a div section of the site, all pages, data and responses load into this central div, like so:
<html>
<body>
<div id="topMenuBar">
<div id="contents">
//ALL DATA IS LOADED HERE...//
</div>
</div>
</body>
</html>
So, when a page is selected from the top menu i simply have the following code run:
$('#topMenuBar a').click(function(e)
{
e.preventDefault();
$('#contents').load($(this).attr('href'), function()
{
});
});
Now that pages load into the content section, I am loading a page called "results.php" which connects to a DB, queries it, and the creates a HTML table with the results. Each table row has a small hyperlink which when clicked is intended to send a value to another PHP script and then clear the contents div and then repopulate the div with the response from this script (getInfo.php). For example, a row will have the following PHP code generate a link:
<label class="moreInfo"><a name="test01" onClick="getInfoFromPHP(<?php echo $data[$id]; ?> )">Get Info</a></label>
So when the table is generated by PHP it, the link when clicked passes a JS function the value.
What i now need to do is to send the value to a PHP script which will again query the DB, and have the results inserted into the "contents" div. I have been trying the following function.
function getInfoFromPHP(myVar){
var netID = myVar;
$.ajax({
url: "getInfo.php",
type: "POST",
data: {
networkID: netID
},
success: function(html) {
$('#contents').empty();
$('#contents').load(html);
}
});
};
When i call the function it does seem to send the data to the script but i get the following error from firebug:
POST http://127.0.0.1/private/networks/includes/leave_a_network.php - 200 OK -15ms
GET http://127.0.0.1/%3Ch2%3EHello 403 Forbidden 21ms
"NetworkError: 403 Forbidden - http://127.0.0.1/%3Ch2%3EHello" Hello
The PHP script is only doing the following:
<?php
session_start();
$networkID = $_POST['networkID'];
echo "<h2>Hello World</h2>";
?>
What is the best way to send data to a PHP script and have it load into a div?
Thanks for any feedback.
In the success function, put $('#contents').html(html); instead of load.
success: function(html) {
Is returning html as a string that does not need to be 'load'ed again like you try here -
$('#contents').load(html);
Change that line to this
$('#contents').html(html);
A better way is using $.ajax to send the request. On the success callback, you can analyse the result, and do what you want with :
http://api.jquery.com/jQuery.ajax/

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/

Form auto submit ajax not working

I'm passing some variable from one file to another php file that contains a form via jQuery ajax. On The form page where data is being passed to have the following code in it, The values are getting passed in properly and and fields are getting populated with the correct entries, i'm able to very this with firebug response, but page is not automatically submitting. Is their anything i should be looking for that is preventing form from auto submitting. If i access the form page directly, i can see auto submit works.
<?php
$title = $_POST['title'];
$wrapper = $_POST['wrapper'];?>
<form action="test.php" method="post" id="publish">
<input type="text" value="<?php echo $title ?>" name="title">
<textarea name="wrapper"><?php echo $wrapper?></textarea>
<input type="submit" value="Submit">
</form>
<script>
window.onload = function(){
document.getElementById('publish').submit();
}
</script>
ajax code that is sending the values looks like this
$.ajax({
type: "POST",
url: "process.php",
data: {
title: 'test',
wrapper: 'testing123'
},
success: function(msg){
alert( "Data Saved: " + msg );
}
});
Spot the difference:
getElementById('publishForm')
id="publish"
From what I see the auto submit is linked to the 'publishForm'
However, your form Id is "publish"
This is probably the cause of the code not working.
Perhaps you should show us the caller code instead of the handler code. Most likely what you're dealing with is the JS not being run during the AJAX call - the PHP page processing is server side.
You could look into sending the form using PHP Curl instead of JS? That would probably address the issue where it works loaded directly, but fails when called from another page.
As far as I understood, that HTML is being loaded through AJAX, right? If so, then window.onload will not be fired since the page was already loaded (AJAX doesn't count). Just do this:
<script type="text/javascript">
document.getElementById('publish').submit();
</script>
EDIT
To break this down:
Your code on SourcePage.php(I made up this name for reference) is posting data to process.php via an AJAX request
process.php then injects "title" & "wrapper" into the html markup and returns html with some javascript to SourcePage.php
You're then expecting that displaying the resulting string (msg) of the returned html on SourcePage.php will get the javascript in that string to execute.
To get this working, you'll need to do a few things.
Parse out the incoming javascript from the html.
Inject the incoming parsed HTML into SourcePage.php's markup.
Pass the parsed out JavaScript into JavaScript's eval function.
Doing this should bring the page from the process.php and successfully execute the JavaScript code on SourcePage.php.
If you were expecting that the JavaScript would run on the server, then I'm afraid you're mistaken as the server(php runtime) will not execute the JavaScript on the server. Perhaps a redirect on the server will accomplish your goal (whatever that may be).
Original
Try this out: http://jsfiddle.net/NiceGuy4263/eJLMS/

Categories