Ajax Call Worked; Doesn't Work Anymore - php

I have an AJAX call on a page for administrators to e-sign. When a button (adminEsign_btn) is pressed, this jQuery is called:
$("#adminEsign_btn").click(function(e){//admin esign submitted
e.preventDefault();
//validate esign
var valid = true;
if($.trim($('#adminSignature').val()).length < 3){
valid = false;
}
//action
if(valid === false){
$('#adminEsignError').html('<span class="error">You must agree to the statement and sign.</span>');
}
else{//validation passed, submit data
var schoolID = <?php echo $schoolProfile['schoolID']; ?>;
var signature = $('#adminSignature').val();
$('#adminEsignLoader').css({'display':'inline-block'});
$('#submitForm').attr("disabled","disabled");
$('#submitForm').val("Updating...");
$.ajax({
type: "POST",
url: 'bin/schoolProfile.saveEsign.php',
data: { schoolID:schoolID, signature:signature}
}).done(function(response) {
//$('#debug').html(response);
//alert(response);
if(response.indexOf('success') >= 0){//if 'success' exists in the response text
$('#submitForm').removeAttr("disabled");
$('#submitForm').val("Update School Profile");
$('#adminEsignLoader').hide();
//disable the e-sign
$('#adminAgree').attr("disabled","disabled");
$('#adminSignature').attr("readonly","readonly");
$('#adminEsign_btn').attr("disabled","disabled");
}
});
$('#adminEsignError').html('');
}
});
I didn't write the original code, so I don't know exactly what is going on in the if statement:
if(response.indexOf('success') >= 0){//if 'success' exists in the response text
But the call isn't expecting a return other than an echo of success. The following php page (schoolProfile.saveEsign.php) is what is called:
<?php
include($_SERVER['DOCUMENT_ROOT'] . '/includes/init.php');
$Page->clearance('Admin');
$Main->saveSchoolAdminEsign($_POST['schoolID'], $_POST['signature']);
echo 'success';
?>
NOTE: $Main is initialized in init.php as well as is $Page.
This code worked up until today when I tested it again. It is supposed to post the data to schoolProfile.saveEsign.php and run a function to save the schoolID and signature to a mysql database.
I've used the javascript alert() function to post the results of the "response" and it always shows the code for the entire current page (schoolProfile.edit.php).
I've run the code in Chrome and it shows that the data is being posted. It has status 302 - Found. The size is 485 B (sounds reasonable for 2 variables with only text), but underneath size in Chrome Network Debugger is content and content is 0 B - empty. I don't know if this means the data isn't being sent or what.
I've tested setting a Session variable to see if the session gets saved and I haven't been able to change it's value so that may be a sign that the data isn't actually being pushed across. But when I view the header for the page being called, it shows the 2 variables - schoolID and signature - with values.
I'm new to Chrome Network Debugger so if there are any other things I can check or if anyone has any suggestions any help would be appreciated.
EDIT: I've also tested the success and error functions inside the ajax call and success is always called. Once again it only returns the entire code for the current page (schoolProfile.edit.php).

I found the issue. In my include($_SERVER['DOCUMENT_ROOT'] . '/includes/init.php'); The init.php document redirects the user to schoolProfile.edit.php if they haven't completed filling out the school profile and it also makes sure that they aren't already at that url using PHP's $_SERVER['REQUEST_URI'].
The issue was that when trying to call schoolProfile.saveEsign.php, this url was not in the "list" of okay'd URL's so the AJAX request was always being redirected to schoolProfile.edit.php - AKA the current page. That is why I would always see the current page code when I would do an alert.
For future reference for myself. Original code:
if($_SERVER['REQUEST_URI'] != '/settings/schoolProfile.edit?f='.$Main->encrypt("INCOMPLETE")) {
header("Location:/settings/schoolProfile.edit?f=".$Main->encrypt("INCOMPLETE"));
exit();
}
Fixed Code:
if($_SERVER['REQUEST_URI'] != '/settings/schoolProfile.edit?f='.$Main->encrypt("INCOMPLETE")
&& $_SERVER['REQUEST_URI'] != '/settings/bin/schoolProfile.saveEsign'
&& $_SERVER['REQUEST_URI'] != '/settings/bin/schoolProfile.saveEsign.php') {
header("Location:/settings/schoolProfile.edit?f=".$Main->encrypt("INCOMPLETE"));
exit();
}

Related

POST with Ajax not working - Why?

HTML
<div pid="14" class="buybutton">Buy</div>
Javascript
<script>
$(document).ready(function() {
$(".buybutton").click(function(){
console.log("Clicked Button");
var pid = $(this).attr("pid");
console.log(pid,"= Product ID");
$.post("/redirecttoproduct.php", {"pidofproduct": pid});
});
});
</script>
Console:
Clicked Button
14 = Product ID
redirecttoproduct.php
<?php
session_start();
$_SESSION['redirectproductpid'] = $_POST['pidofproduct'];
?>
Trying to echo SESSION, nothing shows up
<?php
$productpid = $_SESSION['redirectproductpid'];
echo $productpid;
?>
Nothing shows up - Any ideas?
Did you missed the session_start(); in this page? session_start() is necessary when you use $_SESSION.
<?php
session_start();
$productpid = $_SESSION['redirectproductpid'];
echo $productpid;
?>
I suggest do a callback function first to check if the post request is successfully submitted, one of the reason your $_SESSION variable doesn't return any value is because your js code doesn't post any values to it at all, in result no data is being assigned to your $_SESSION var, ie:
$.post("/redirecttoproduct.php", {"pidofproduct": pid})
.done(function() {alert( "success" );})
.fail(function() {alert( "error" );});
And it would be more convenient if you could supply an absolute path to your $.post request like your website's dir url ie: $.post("//yourwebsite.com/redirecttoproduct.php") with this relative path errors can be significantly avoided, and make sure your not submitting invalid values that would not pass your XSS filters (if there are any), hope this helps, cheers!

redirect to a page with php and and also submit POST data

I want to redirect to a page after executing a php function and also submit a html form with the methode POST, at once.
I found many solutions with GET but I want to handle this with POST.
You can use cUrl to send POST data you want, then make the redirect.
Look on the net for: "php curl".
Make your form action point to the php document where you want to execute your function and then in the end place this header("location: your_location_file.php");
Step one - submit form to functions.php
Step two - do what ever you need to do with the submited data
Step three - Redirect
Example:
<form method="post" action="functions.php">
...
</form>
functions.php
<?php
...
all your code
...
header("location: your_location_file.php");
?>
Javascript can help if you don't want to rely on curl. Had this laying around. Pass in $_POST or an array of the data you want posted. Add error/parameter checking.
function http_post_redirect($url='', $data=array(), $doc=true) {
$data = json_encode($data);
if($doc) { echo "<html><head></head><body>"; }
echo "
<script type='text/javascript'>
var data = eval('(' + '$data' + ')');
var jsForm = document.createElement('form');
jsForm.method = 'post';
jsForm.action = '$url';
for (var name in data) {
var jsInput = document.createElement('input');
jsInput.setAttribute('type', 'hidden');
jsInput.setAttribute('name', name);
jsInput.setAttribute('value', data[name]);
jsForm.appendChild(jsInput);
}
document.body.appendChild(jsForm);
jsForm.submit();
</script>";
if($doc) { echo "</body></html>"; }
exit;
}
You could use a session to hold the POST data.
I am currently using code like below. On my first page load, the $_POST data is checked. If it contains certain values already in the database, then it redirects to a page for those values.
// This could be part of the same script as below, or a different script.
session_start();
if($_POST['my_value'] && valueExistsInMyDb($_POST['my_value']) ) { // check my db to see if this is an existing value
$id = getIdOfMyValue($_POST['my_value']); // e.g. '4'
$_SESSION['POST'] = $_POST; // take ALL post data and save it in the session variable
header("location: your.php?myvalue=" . $id); // redirect to bookmarkable target page where $_GET variable matches what was posted.
exit(); // ensure no other code is executed in this script after header is issued.
}
Then your other file (or maybe even the same file) could do this:
// your.php?myvalue=4
if(isset($_SESSION) && array_key_exists('POST',$_SESSION)) {
$_POST = $_SESSION['POST']; // creates or overwrites your $_POST array with data from the session. The rest of your script won't be able to tell that it's not a real $_POST, which may or may not be what you want.
unset($_SESSION['POST']); // you probably want to remove the data from the session.
}
// now your myvalue=4 is stored in GET, and you can handle the rest of the POST data as you like
I don't know if that is the best solution, but so far it seems to be working for me so far. I only just wrote the code a few days ago and haven't tested all aspects yet.
Another option is to use HTML5 to change the address bar. No redirect needed. But the downside is that only "modern Webkit browsers" can use it, apparently.

how to create user files within a chat and messaging system using ajax and php

i really do hope to get a helpful answer. i've been working on a way to make a chatbox that allows private sessions between two users,one where only two users chat with the option of joining the general chatroom, i'm doing this without any xmpp,sockets etc, i'm just using files which would serve as logs, i'll explain the concept:
a user has logged in, they are directed to the chat-page, where a list of their friends stored in a database is loaded to their right, this part is working fine:
//i've declared all the variables previously
//skip to the part that loads the names:
while($rowb=mysql_fetch_array($done))
{
$rafiki=$rowb['name'];
//show the names,when the user clicks on any of them, the name(variable $jina) of the user
//and the friend's name are sent to the function makefile()
echo "<a href='Javascript:makefile(".$jina.",".$rafiki.")'>"."$rafiki"."</a>"."<br/>";
}
when the user clicks on any name, they are sent to the javascript function, which takes both parameters, the user's name and the name of the friend, and then adds an extension at the end, to make a log file that would serve as the chat log between both of them:
function makefile(username,friendname)
{
//add file extension
var ext=".html";
//concatenate
var dash="-";
var full=username.concat(dash,friendname,dash,ext);
var str=friendname.concat(dash,username,dash,ext);
so each pair would have their own file, the variable full is sent to a script via ajax to make the process seamless, the script does a number of things:
it first checks to see if a log file, that bears the data sent from the client side exists, either beginning with the user's name or the friend's name,if either file exists,it checks to see if any messages have been sent and writes them to the file, if neither file exists, it creates a new file,and prompts a user that a friend wants to start a chat, when the friend clicks on the user's name, the first condition will succeed, because a file would already have been made:
<?php
session_start();
$full=$_POST['full'];
//first, check to see if variations of the file already exist
//start by exploding the sent data
$result=explode("-",$full);
$usrnme=$result[0];
$frndnme=$result[1];
$ext=$result[2];
//make varied names for comparison
$vrdfull=array($result[1],$result[0],$result[2]);
$str=implode("-",$vrdfull);
$_SESSION['str']=$str;
$_SESSION['full']=$full;
//start actual comparison
if(file_exists($full)||file_exists($str))
{
//stuff to do if first file exists
if(file_exists($full))
{
//check to see if message has been sent
if (isset($_POST['message']))
{
$message=$_POST['message'];
//update existing file with message
$fp=fopen($full,'a');
fwrite($fp, "<div id=\"sent\">".$usrnme." :"." ".$message."<br/>"."</div>");
//close the file
fclose($fp);
}
}
else
//stuff to do if second file exists
{if(file_exists($str))
{
//check to see if message has been sent
if (isset($_POST['message']))
{
$message=$_POST['message'];
//update existing file with message
$fpp=fopen($str,'a');
fwrite($fpp, "<div id=\"sent\">".$usrname." :"." ".$message."<br/>"."</div>");
//close the file
fclose($fpp);
}
}
}
}
else
{
//create file, since neither files exist
$fhandel=fopen($full,'a');
//check if message has been sent
if(isset($_POST['message']))
{
$messssage=$_POST['message'];
fwrite($fhandel,"<div id=\"sent\">".$usrname." "." : ".$messssage."<br/>"."</div>");
}
fclose($fhandel);
//send msg to friend, incurring them to accept
$ext=".html";
$frrnme=$frndnme.$ext;
$fpp=fopen($frrnme,'a');
//prompt the user to initiate chat by opening file,by clicking on the name he/she would see
fwrite($fpp,"<div id=\"msg\">".$frndnme." wants to chat, click on their name to accept"."</div>");
fclose($fpp);
}
?>
i don't think this part has any problems, just posted it to help convey the idea across.here's the ajax that sends the string full to the script (i think it may be wrong):
$.ajax({
type:'POST',
url:'makesend.php',
data: {full:full},
//what to do if data was sent:
success: function(full){
$('#myResponse').html(full);
}
});
return false;
no data is shown in the div "myresponse", so i think there's a problem here, i don't know what. the next thing would be to handle messages sent by the users,here's the form that would get their input:
<form name="message" action="">
<input name="message" type="text" id="usermsg" size="63" />
<input name="submitmsg" type="submit" onclick="send()" id="submitmsg" value="Send" />
</form>
and here's the function send() that sends data to the makesend.php file:
function send(){
var clientmsg = $("#usermsg").val();
$.post("makesend.php", {message: clientmsg});
$("#usermsg").attr("value", "");
return false;
}
again, when i tested this and wrote a message, the page reloaded and no data was sent to the script! there's a problem here as well,i don't know what it is. moving on, after the file has been created and the user's begin interaction, it needs to be uploaded to a message area where the user can see it, here's the message area div:
remember that i'll need to load a file that exists, so before loading it to this area, i'll need to use php to see which version exists, either one with the user's name first or with the friend's name (either $full or $str):
$("#msgarea").html(
"<?php
//check to see if either file exists
if(file_exists($_SESSION['full'])||file_exists($_SESSION['str'])){
//check to see if the first file exists:
if(file_exists($_SESSION['full']))
{
$full=$_SESSION['full'];
$handlle = fopen($full, "r");
$contents = fread($handlle, filesize($full));
fclose($handlle);
//load it's contents to the division if it does
echo $contents;}
else
{
//if first file doesn't exist, load the second one:
$str=$_SESSION['str'];
//check to see if it exists before loading it
if(file_exists($str))
{
$handle = fopen($str, 'r');
$contents = fread($handle, filesize($str));
fclose($handle);
//load it to the division
echo $contents;
}
}
}
?>"
);
i think it's legal to do that, add php code to the innerHTML of an element, so this code would load whatever version of the file that exists. i get the file names from the session because this part of the code gets executed after data is sent to the makesend.php file, which starts a session and gives them ($_SESSION['full'] and $_SESSION['str']) values. this part that loads the file is the last piece of code within the function makefile(), first, the function obtains data from the user in form of the name they clicked, it sends them to a script (makesend.php) which creates the chat log file, after this, comes the last part, which loads the data onto the division "msgarea". next, i'd need to refresh/reload the created log file after a certain amount of time to show the messages sent by the users, i chose to use 2.5 seconds, this part is outside the function makefile(),i had to use php within the jquery to first check which file exists, i'd then use jquery in the php to reload and animate(auto-scroll) the existing one,this php is inside the 'javascript' tags:
<?php
//set up the conditions
$full=$_SESSION['full'];
$str=$_SESSION['str'];
//check whether either file exists
if(file_exists($full)||file_exists($str))
{
//reload the first file if it exists
if(file_exists($full)){
//this is the jquery inside the php(which is also in javascript tags)
echo '<script type="text/javascript" src="jquery-1.8.0.min (1).js"></script>';
echo '<script type="text/javascript">';
echo
'function loadLog(){
var oldscrollHeight = $("#msgarea").attr("scrollHeight") - 20;
$.ajax({
url: <?php session_start(); echo $_SESSION[\'full\']?>,
cache: false,
success: function(html){
$("#msgarea").html(html); //Insert chat log into the #msgarea div
var newscrollHeight = $("#msgarea").attr("scrollHeight") - 20;
if(newscrollHeight > oldscrollHeight){
$("#msgarea").animate({ scrollTop: newscrollHeight }, \'normal\'); //Autoscroll to bottom of div
}
},
});
}
setInterval (loadLog, 2500); //Reload file every 2.5 seconds';
}
else{
//this will reload the second file since the first doesn't exist:
echo
'function lloadLog(){
var oldscrollHeight = $("#msgarea").attr("scrollHeight") - 20;
$.ajax({
url: <?php session_start(); echo $_SESSION[\'str\']?>,
cache: false,
success: function(html){
$("#msgarea").html(html); //Insert chat log into the #msgarea div
var newscrollHeight = $("#msgarea").attr("scrollHeight") - 20;
if(newscrollHeight > oldscrollHeight){
$("#msgarea").animate({ scrollTop: newscrollHeight }, \'normal\'); //Autoscroll to bottom of div
}
},
});
}
setInterval (lloadLog, 2500); //Reload file every 2.5 secsonds';
}
echo '</script>';
}
?>
and i think that's it, the entire system, also, there's a problem with the logout call, here's the code, it's at the very end of the file:
$("#exit").click(function(){
var exit = confirm("Are you sure you want to end the session?");
if(exit==true){window.location = 'testing.php?logout=true';}
});
here's the markup for it:
<p class="logout"><a id="exit" href="#">Exit Chat</a></p>
and at the top of the file, here's the part that checks whether it's set to true:
session_start();
//logout function
if(isset($_GET['logout']))
{
if(file_exists($_SESSION['full'])||file_exists($_SESSION['str']))
{
if(file_exists($_SESSION['full']))
{
$full=$_SESSION['full'];
$flogout=fopen($full,'a');
fwrite($flogout, $_SESSION['username']." has left the anichat!!! "."<br>");
fclose($flogout);
}
else
{
$str=$_SESSION['str'];
if(file_exists($str))
{
$flogoout=fopen($str,'a');
fwrite($flogoout, $_SESSION['username']." has left the chat "."<br>");
fclose($flogoout);
}
}
}
session_destroy();
header("Location:testing.php");//user redircect.
}
the user's page is not even refreshed so that the session is destroyed, it just refreshes and the session data is still present(this is because the login form isn't shown, it's supposed to be shown if the $_SESSION['name'] is empty). i know that this is a long question, but i am a beginner and i really need help with this, i think the main issues are with the ajax, but if you can spot anything else i will be very thankful, i kindly ask for a relevant answer that will help me implement this, if you would like me to post the entire code present in both testing.php and makesend.php,in a way that is not separated like the way i've done here to illustrate, please ask if it helps.i thank all you advanced programmers who go out of their way to help others, thanks in advance.
I guess it is that the processing page makesend.php is no retrieving anything to the request. You can use firebug to determine if it is writtin some thing. I am saying it since you are not reading the file after you updated (didn't see it) You can create a new ajax request that is called periodically after some interval and load the contents in the log file with the conversation.

PHP JQuery and Jeditable

Just a quick question regarding this issue i am having. I am using jeditable to edit in place some fields on a page. This is working perfectly. Now I wish to implement some data checking. I have my php code to check the data entered and if its correct, it updates that database, and if it isn't it will return the error. The issue I am having is I want it to spit out the error to tell them but when they click the field again to edit it, it shows the error in the field until a page refresh. What i want it to do is have the same data in the field when they click on it after the error occurs instead of having to refresh the page then click the field again to edit it. Perhaps there is a way to return back the error and pass that into a tooltip of some sort above the field? Of course the way jeditable works is the div is surrounding the field then i have some js calling on my update.php file, this parses what jeditable passes to it and returns a $value to be error checked and by default if it is fine it simply at the bottom of the php "return $value;" to be put back int he field after its been saved in the DB.
Hopefully someone can understand what I am asking here and any assistance would be appreciated.
Easiest way is probably to do some client side validation. Right now you are doing server side validation by checking in PHP when the form is submitted. What are you checking for?Without code it is hard to give you a good example of client side validation.
Basic field checking:
var check_field = $("#field").val();
if (!check_field) { alert("Error message"); } else
{
// submit POST or whatever
}
Edit
Since the MAC address validation algorithm is already written server side, I recommend a separate ajax POST request that calls the checker function. Take the result of that request (true, false) and check it client side. If true, proceed with the update call.
Example:
$("#form").submit(function() {
var mac = $("#macfield").val();
if (!mac) { alert("MAC address can't be empty!"); } else
{
$.POST("checkmacaddress.php", {macval: mac}).success(function(a){
//assuming a comes back as a bool
if (!a) { alert("Invalid MAC!"); } else
{
// if the checker returned true, update the record
$.POST("update.php" ...);
}
});
} });
This doesn't include the checkmacaddress.php but you should be able to handle that if you already have the function on hand.
Hate when I do this, post here then figure out the answer myself...but at least if someone has the same issue they will see it. I found out about the jeditable onsubmit functions...i am using a tooltip to show on hover when editing the field so this will set the tooltip to the error and not submit the data unless its a valid mac.
function isMAC(value) {
teststr = value;
regex=/^([0-9a-f]{2}([:-]|$)){6}$|([0-9a-f]{4}([.]|$)){3}$/i;
if (regex.test(teststr)){
return true;
}
else {
return false;
}
}
$(".edit_mac").editable("edit_mac.php", {
onsubmit: function(settings, data) {
var input = $(data).find('input');
var value = input.val();
if (isMAC(value)) {
return true;
} else {
//display your message
$("#tooltip").html("Bad MAC Address...");
return false;
}
},
indicator : "Saving...",
submitdata: { _method: "put" },
submit : 'Save',
cssclass : "editable",
type : "text"
});

Update whole page on Ajax request

I have an AJAX request that can have two possible outcomes:
The server responds with a message which I should place in a <div>
The server responds with an HTML page, in this case I need to substitute current page with a new one and change the address (the client knows the address before a request).
What would be the solution if I have the AJAX request that needs to handle both of these cases?
url = "http://example.com"
ajax.request(callback)
function callback(response) {
if (case2(response)) {
history.pushState({}, "New page", url);
document.innerHTML = response
} else {
updateDiv(response)
}
}
I'm interested in a correct way to implement the first branch, or if the server can somehow compose a headers that will make browser to handle a response as a usual HTTP response and update a page location and content, something like redirect with given content.
I understand that the server can return a link instead of a page, but in this case one additional stage will be needed on a client - redirect and then populating the new page on the server.
Quite frankly, I think that approach is basically broken by design. You shouldn't have to make that decision at that place. For example, the ajax response could only signal that a whole new page should be loaded and the new content then be generated on a second (non-ajax) request to a new URL.
In case you're forced to take the way you already go, and provided the response content is not very large, you could try Javascript-URIs. Basically, an URI in the form of javascript:"string" will load a new page which that string is the source code for. So, if response already is a string, just assigning javascript:response to window.location.href should suffice. Maybe you have to do some escaping beforehand. And I don't know, how cross-browser-compatible this approach is.
load
is also possible.
A variant of this is building the URL not with the variable name, but with the actual string data. Like
function source2url(src) {
// make valid javascript string from source text
var esc1 = src
.replace(/\\/g, '\\\\')
.replace(/\'/g, '\\\'')
.replace(/\x0A/g, '\\x0A')
.replace(/\x0D/g, '\\x0D');
// make valid url from that
return "javascript:'" + encodeURIComponent(esc1) + "'";
}
window.location.href = source2url(response);
This will, of course, generate pretty large URIs. And you'll always have the Javascript-URI in the address bar.
UPDATE
A similar approach is to use base64 encoding in a data URI. The Wikipedia entry explains how it works, including a javascript example. However, you'd have to base64-encode the content somehow. (Note: You can use data URIs with or without the base64 encoding. You have to see what gives you shorter URIs for your specific content.)
I had a similar issue once. A full error page was returned instead of a simple HTML snippet. We eventually fixed this by changing the logic, but here is one of the solutions I found:
document.open();
document.write(responseText);
document.close();
The reason we abandoned this is that on IE there were some problems. I didn't loose any time to investigate why, but it threw an 'Access denied' exception when attempting to write the string. I think there were some <meta> tags that confused IE, or maybe conditional comments, I'm not sure. (It worked when I used some simple pages...)
Bottom line is: you shouldn't have to do this, but if there is nothing else you can do (like returning an url string) the code above might work.
It's really easy if the response is valid XML.
var new_doc = (new DOMParser).parseFromString(response, "application/xml");
document.replaceChild(document.adoptNode(new_doc.doctype), document.doctype);
document.replaceChild(document.adoptNode(new_doc.documentElement), document.documentElement);
Since the request is for an updated answer, here's my solution using HTML5's History API with jQuery. It should run easily by combining the PHP and HTML parts into one file.
My solution allows for AJAX to return the following:
A message through AJAX, which updates a <div> container.
A URL, which causes the browser to redirect to the URL
A complete HTML page, which calls the History API's history.pushState() to add the current URL to the browser's history and replaces the entire HTML on the page with the HTML returned from AJAX.
PHP
This is just a sample of what the PHP script will need to return when it is invoked via AJAX. It shows how to encode flags to determine whether the AJAX call should update the container or load a new page, and how to return its result via JSON through json_encode. For completeness, I named this script test.php.
<?php
// Random messages to return
$messages = array(
'Stack Overflow',
'Error Message',
'Testing'
);
// If the page was requested via AJAX
if( isset( $_POST['ajax']))
{
$response = array(
'redirect' => // Flag to redirect
( rand() % 2 == 0) ? true : false,
'load_html' => // Flag to load HTML or do URL redirect
( rand() % 2 == 0) ? true : false,
'html' => // Returned HTML
'<html><head><title>AJAX Loaded Title</title></head><body>It works!</body></html>',
'title' => 'History API previous title',
'message' => // Random message
$messages[ (rand() % count( $messages)) ]
);
echo json_encode( $response);
exit;
}
JS
Since I am using jQuery, lets start with that. The following submits an AJAX POST to the server, to the above PHP script at URL test.php. Note that it also sets the POST parameter ajax to be true, enabling the PHP script to detect that it received an AJAX request. The dataType field tells jQuery that the server's response will be in JSON, and that it should decode that JSON to a JSON object in the response callback. Finally, the success callback, which is fired when the AJAX response is successfully received, determines what to do based on the flags sent from the server.
$.ajax({
type: 'POST',
url: "/test.php",
data: {ajax : true},
dataType: "json",
success: function( json) {
if( json.redirect) {
if( json.load_html) {
// If the History API is available
if( !(typeof history.pushState === 'undefined')) {
history.pushState(
{ url: redirect_url, title: document.title},
document.title, // Can also use json.title to set previous page title on server
redirect_url
);
}
// Output the HTML
document.open();
document.write( json.html);
document.close();
}
else {
window.location = redirect_url;
}
}
else {
$('#message').html( json.message);
}
},
});
HTML
Here is the complete HTML source of my tested file. I tested it in FF4 - FF8. Note that jQuery provides the ready method to prevent the JS from executing until the DOM is loaded. I've also used Google's hosting of jQuery, so you do not need to upload a copy of jQuery to your server to test this.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js" type="text/javascript"></script>
<title>Default Page</title>
<script type="text/javascript"">
$( document).ready( function() {
$('#ajax_link').click( function() {
var redirect_url = "/test.php";
$.ajax({
type: 'POST',
url: "/test.php",
data: {ajax : true},
dataType: "json",
success: function( json) {
if( json.redirect) {
if( json.load_html) {
// If the History API is available
if( !(typeof history.pushState === 'undefined')) {
history.pushState(
{ url: redirect_url, title: document.title},
document.title, // Can also use json.title to set previous page title on server
redirect_url
);
}
document.open();
document.write( json.html);
document.close();
}
else {
window.location = redirect_url;
}
}
else {
$('#message').html( json.message);
}
},
});
})
});
</script>
</head>
<body>
<div id="message">The default contents of the message</div>
<a id="ajax_link" href="#">Fire AJAX</a>
</body>
</html>
Give an id to body <body id="page"> and your other div will be <div id="message"></div> now your ajax will look like
$.ajax({
url:'myAjax.php',
data:{datakey:datavalue},
dataType:"JSON",
success: function (response) {
if(response.message=="your message")
{
$('#message').html(response.content);
}
else
{
$('#page').html(response.content);
}
}
});
as T-Bull say... the whole process is wrong here....
you simply are over-complicating things and you know that infact:
I understand that the server can return a link instead of a page, but
in this case one additional stage will be needed on a client -
redirect and then populating the new page on the server.
stop complicating and start do it well...
Client open the page first time, so, track it $_SESSION['tmp_client_id'] = 'client_'.session_id(); obviously is better if the client is already subscribed, anyway, put stuff in temp table OR into another session var etc...
Client fill in the form;
Client submit the form;
Make the AJAX request;
Store $_POST variable inside tmp_client_tbl with it's unique tmp_client_id OR just $_SESSION['client_'.session_id()] = json_encode($_POST);
Outcome #1 ? display message in a </div>
Outcome #2 ? refresh page and check if( isset($_SESSION['client_'.session_id()])) { if so let's display the form again with filled fields: } else { display empty form;
SELECT * FROM tmp_client_tbl WHERE tmp_client_id = '{$_SESSION['tmp_client_id']}' OR json_decode($_SESSION['client_'.session_id()]);
$form_data = $mysql_rows; OR $json_array;
foreach($form_data as $name => $value) { echo "<input name='$name' value='$value' />" } in a ninja way that assume you have such kind of form builder array where $form = array('text' => array('name','lastname'), 'select' => array('countries'), ... ), OR simply by <input name='lastname' value='{$lastname}' /> where the fields values are pre-polutated with empty vars;
time elapsed, error occurred, browser closed? session_destroy(); or unset($_SESSION['client_'.session_id()]);

Categories