Using JQuery, AJAX and PHP - 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/

Related

jquery and php update using modal dialog

I'm trying to display html form with specific information based on the article id using modal window but I'm struggling to pass value/id to my custom php function.
So, here's the html/php part
while(...) :
Edit
endwhile;
Now js,
$("a.button").on("click", function() {
$("#modal").reveal();
return false;
});
html and php function
<div id="modal">
<?php echo showForm($needThisIDbasedOnClick); ?>
</div>
Hope all this makes sense for you, I'm struggling of getting the certain id and passing to php function
I tried removing the return false; and following the href attribute <a href="?id=17"> ... and than getting the value using $_GET['id'] showForm($_GET['id']) but this solution just don't work the way I wanted, it reloads the page ...
The page with you PHP code is execute on the server side. PHP is interpreted, and then the content is sent to your browser. After receiving the data, your JS code is executed on the client side (thanks to you JS machine of your browser).
If you want to show information without reloading anything, you have 2 solutions:
Embedding all information in the page during the PHP processing and keep it hidden, showing the good one with JS code depend on the link clicked. (Bad solution)
Use an AJAX request with the ID in parameter that will call to a new short PHP script returning the information of the specified row.
If I resume the process could be:
1) The first request is on your main script main.php
2) The page display all your item (embedding only the ID) and contain the information container (which is hidden and empty)
example
<!-- Your list of link with article ID -->
<div>
<a class="articleLink" id="123" href="#">View</a>
<a class="articleLink" id="124" href="#">View</a>
<a class="articleLink" id="125" href="#">View</a>
</div>
<!-- The bloc that will contain info and will be shown in a popup later (hidden) -->
<div id="divInfo">
<input type="text" name="name" value=""/>
<input type="text" name="description" value=""/>
</div>
<script>
$(document).ready(function() {
// add listener to all link
$(".articleLink").click(function(mouseEvent) {
// Retrieve the article ID
var myId = $(this).attr('id');
// Ajax call with the id of the link
// onSuccess, fill the divInfo and show it
$.ajax('getInfo.php', {
dataType: 'json',
type: 'POST',
data: {
articleId: myId
},
success: function(data, status, xhrObj) {
// The data is received, update the info container
$("#divInfo input[name=name]").val(data.name);
$("#divInfo input[name=description]").val(data.desc);
// Show the div in a popup
//...
}
});
return false;
});
});
</script>
3) You are clicking on one link, it will run an ajax call to a second PHP script : getInfo.php, giving the specified ID
4) The script retrieve data in your Database and finally return the information (in JSON for example)
Assuming your PHP getInfo.php will return JSON like
{"name":"an article name","description":"the article description"}
Note: you can produce easily JSON in PHP from array with the function
json_encode()
5) the method onSuccess of your Ajax call is called when the data is received, and you can use the data to fill your form (which is unique and already present in the page - and is hidden).
good luck

PHP Does Not Seem To Play Nicely With An XML String?

I am creating an application where a users draws shapes on a canvas and then saves and retrieves them from a database. The saving part works fine, now though, im trying to load this XML content, Thats where the troubles are starting.
Firstly a user has a list of documents they have created, when clicked it loads that document into the applicaiton to do this, i use the following code, firstly a javascript function which takes the ID of the document, then sends it to a PHP script which retrieves that documents data from a database. The PHP script than loads that documents data into a $_SESSION['data'] variable. Once done, it goes back to the javascript function which redirects the user to application page.
function loadDocument(docID){
$.ajax({
url: "load_a_document.php",
type: "POST",
data: {
documentID: docID,
},
success: function(data)
{
alert(data); //THIS DISPLAYS THE XML WITH NO PROBLEMS???
window.location = "application.php";
}
});
};
The PHP queries the database and retreives the name and XML content of the document, it then does this:
$_SESSION['document_Name'] = $doc_NAME;
$_SESSION['document_XML'] = $doc_DATA;
echo($_SESSION['document_XML']); //this is 'data' on the ajax success call
Now when the PHP is finished it echoes the php context, this shows up in the alert box in the success:{} of AJAX with no problems. Now it takes the user to the actual application which begins like so:
<?php
session_start();
$document_Name = $_SESSION['document_Name'];
$document_Data = $_SESSION['document_XML'];
?>
<script>
alert(" <?php echo $document_Name; ?> "); //WORKS FINE
alert(" <?php echo $_SESSION['document_Name']; ?> ") //WORKS FINE
//alert(" <?php echo $document_Data; ?> "); //STOPS THE PAGE LOADING
//alert(" <?php echo $_SESSION['document_XML']; ?> ") //STOPS THE PAGE LOADING
</script>
Fetching the first two items, there are no problems, as soon as XML data is printer then their is a real problem. I dont understand why the loadDiagram() can alert
() the XML but my application page cannot. Has the data been corrupted somehow?
Thanks for any feedback.
You probably have quotes in the string that's causing the problem. Try
alert(<?php echo json_encode($document_Data) ?>);

Load dynamic content from php on submitting a form

I have created a page "index.php" with a lot of divs and I need to refresh only one of the divs when the form is submitted.
This div loads the content from chat_window.php which is as follows:
<div id="chatbox">
<?php echo $res; ?>
</div>
<!-- Chat user input form-->
<?php echo $formchat; ?>
chat_window.php uses dynamic content - $res and $formchat from chat.php.
Everytime I post the form the content of $res and $formchat is modified and I need to reflect the same in my page which loads chat_window.php.
I used AJAX and jQuery to do the same as follows:
$(document).ready(function() {
$("#submit").click(function() {
var name = $("input#chat").val();
var dataString = "chat="+ name;
$.ajax({
type: "POST",
url: "programo/bot/chat.php",
data: dataString,
success: function() {
}
});
$("#chatwrapper").load(chat_window.php);
return false;
});
});
The index.php has a div to show the chat_window as follows:
<!-- Chat window-->
<div id="chatwrapper">
<?php include ("chat_window.php"); ?>
</div>
As per my analysis, when I post the form, $res and $formchat are getting updated in the php. But when I load the chat_window.php, it doesnot loads the modified values. It rather loads the initial static values.
(Please dont suggest setInterval() as I dont want to refresh the page automatically).
Javascript is non-blocking, so it means that the interpreter does not wait for jobs to complete before processing the next one.
In your code, $("#chatwrapper").load('chat_window.php'); is being called pretty much before the ajax request above it completes. You will need to use the ajax success event to call the reload.
Try:
$.ajax({
type: "POST",
url: "programo/bot/chat.php",
data: dataString,
success: function() {
$("#chatwrapper").load('chat_window.php');
}
});
Try moving the .load() statement into the ajax success handler:
$.ajax({
type: "POST",
url: "programo/bot/chat.php",
data: dataString,
success: function() {
$("#chatwrapper").load("chat_window.php");
}
});
The $.ajax() call is asynchronous, which means that execution does not pause waiting for the response, rather, it moves on directly to the .load() call. (Which is also asynchronous, so really you've no guarantee about the order the response from each call will come in unless you don't make the second call until the first one finishes.)
I got my work done. Though I used another way of doing it.
What I have understood after few days of R&D is that, when we submit the form to a php, the request is sent with input params. When your php file processes this request, it might be updating some global variables. It completes processing the request and returns the control back to the calling index.php page.
The important thing to notice is:
The variable updates made while processing the form submit request do not persist after the control is returned. The global php variables will only get updated when the page gets refreshed.
So, if there is a strict requirement to avoid page refresh, collect the processed data from the php in some output string and pass it back to index.php like this:
$responseString = $res . "|" . $formchat;
echo $responseString;
The success parameter of .ajax will receive this output and accordingly you can update your chat window or any other form.

jquery to refresh div content generated by php

How to refresh a div content generated by the same php page using jquery
i have a test.php, that contains a div called refreshdiv, a button called refreshbutton and may other div's that display other contents
the content of refreshdiv div is generated by php
is it possible to reload the contents of the refreshdiv on clicking refreshbutton on the same page ie, test.php
here is my work around
<div id="refreshdiv">
<table>
<?php
$rec=mysql_query("select * from user_master");
for($i=0;$i<mysql_fetch_array($rec);$i++)
{
?>
<tr>
<td>
<?php echo mysql_result($rec,$i,'username');?>
</td>
</tr>
<?php } ?>
</table>
</div>
tried using $.get, but didnt get any result
Take a look at this jsFiddle I put together - it may help.
I'm making an AJAX call (a POST in this case since it's just HTML and that's what jsFiddle supports for HTML requests - but it would be no different for a $.get for you) that gets data and appends it to a table data cell (<td>). The whole page doesn't update - just the section that I'm targeting -- in this case, the <td> cell, which keeps having "hello's" appended into it.
I hope this helps. Let me know if you have add'l questions.
Use ajax
In the test.php use
if($_GET['ajax'] == 1) {
//echo new content;
}
and the jQuery code will be
function refreshClick() {
$("#refreshdiv").load("./test.php?ajax=1");
//OR
//to customize your call more, you could do
$.ajax({
method: "GET",
url: "./test.php?ajax=1",
success: function(data) { $("#refreshdiv").html(data); },
error: function(err){ Some_Error_Div.innerHTML = err; }
});
}
I think you'd need to set up a php page that will return the contents of the div then access this page via ajax and insert the contents generated by the page into your div. So the jQuery would look something like this -
$.ajax({
url: "div.php",
success: function(data){
$('#refreshdiv').html(data);
}
});

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