redirect without page reload - php

I want to redirect error message to index page so i wrote the following code:
$message="Bad answer, go back to page!";
header("location:index.php?message=".$message);
this code in process page, and i'm fetching data in index.php page like:
<?php
if(isset($_GET['message'])) {
$message=$_GET['message'];?>
<?php echo $message; ?></iframe>
}
else { echo ""; }
?>
i tried to display message in iframe....but i couldn't succeed.

Your echoing the iFrame tags incompletely/incorrectly. Try this
<?php
if(isset($_GET['message'])) {
$message=$_GET['message'];
echo '<iframe>'.$message.'</iframe>';
}
else { echo ""; }
?>

When you are talking about DOM manipulation (without needing to refresh the page), you should know the best, most elegant way is to do that with Jquery / Ajax / PHP.
Use $.get or $.post to send data to PHP and get the returned data (this case : Bad answer, go back to page!)
Get your <div> or <iframe> element and load the returned data inside of your selected element with Jquery.
I don't know if you are willing to do some changes. If you are willing to do more changes, please drop a comment so I will give you a code example about it.
Some Information you must know;
$.get and / or $.post.
.load() to load returned data.
I hope this helps.

Related

How to use a jQuery object from php?

Why does this not work? This is the first thing in the body:
<?php
if(isset($_POST['submit'])){
echo "<script>$('.classToShow').show();</script>";
}else{
echo "<script>$('.classToShow').show();</script>";
}
?>
classToShow is a simple div in the body. It won't show up and its not depending on the boolean condition, it must be the code...
While this works:
<?php
if(isset($_POST['submit'])){
echo "<script>alert('works');</script>";
}else{
echo "<script>alert('works');</script>";
}
?>
So the simple JavaScript works, but the jQuery doesn't... Why is this?
This is your problem:
This is the first thing in the body
At that point the element with the class of classToShow does not exist yet, so nothing happens. You should wait for the DOM to be ready before you run that code.
On the other hand, if you just want to show something when a POST request was made, you can add it directly using php and you don't need jQuery to do that afterwards.
A common solution would be to show it directly using php and then use javascript to hide the message after a certain timeout.
You can use $(document).ready() and inside that write the code

Display "Please Wait" between form submission and redirect

I have a page that contains an HTML form that submits back to itself once the user clicks a link in a list of returned search results. Once they click the link, the page takes the submitted variables, runs a bunch of searches on various external APIs, parses a bunch of data, and adds a bunch of stuff to the database, then redirects to a new page that has been created from that data.
All the searching and parsing can take up to six or seven seconds; I'd like to be able to show the user a "Please Wait" kind of message while all that work is happening behind the scenes.
Trouble is, I can't show and hide a DIV because it will screw up my PHP redirect if I've already generated output before the
header('Location: ' . $newURL);
command. I've searched around for answers but while there are many that are similar, none of them are close enough to my specific situation that I can hack around them.
I'd be grateful if someone could point me in the right direction.
Updated version which now works, courtesy #Izkata from his comments below:
jQuery("a").bind('click', function() {
jQuery('#feedback')[0].innerHTML = 'Searching, please wait...';
})
Turned out what I needed to do was assign bind a the message to the click of a link, not to 'submit', as submit was looking for form data.
The simplest way I can think of doesn't require the server to do anything:
<div id='wait_message' style='display: none;'>
Please wait while search is in progress...
</div>
...
$$('.links').observe('click', function(e) {
$('wait_message').show();
});
(Event is written using Prototype.js; you should use whatever is appropriate (JQuery/mootools/etc))
Using the example page in the comments, this works - it runs in Firebug, so just putting it on your page somewhere should work just fine.:
jQuery('#newMovieSearchForm').bind('submit', function() {
jQuery('#feedback')[0].innerHTML = 'Searching, please wait...';
})
There's probably a jQuery-way to update the text instead of using innerHTML, but I don't know it - we don't use jQuery here.
You are right, you won't be able to output data to the screen and then try to redirect afterwards using PHP. You could accomplish this by echoing JS:
echo 'Please wait...';
// Time-intensive PHP here
echo '<script>window.location = "new-location.php";</script>';
You can do something like this:
First, take care of output buffering, i.e. you want php to display output as it executes - you don't want it to buffer.
That way, you can output some html that will show a "loading.." sort of thing.
And, will wait for the script to end it's execution.
Once, you are done with php, redirect using a meta tag, something like:
echo '<meta http-equiv="refresh" content="5;URL=\'http://example.com/\'">';

Sending PHP variable, via jQuery to landing page whilst skipping third party submission script?

My goal is to set a Google Conversion value from a custom field defined in WordPress. The conversion script is located on the landing page, so I need to get my custom field data from my form to the landing page. I can't use GET or POST as the form submission is handled by a third party and no data is returned to the actual landing page.
So I've tried using a PHP session, but this third party is getting in the way of just being able to use PHP, because it's keeping all the data for itself.
This is the approach I'm hoping I can get working:
The validation for the form is done using jQuery Tools.
I then need to submit the variable after validation has been successful via jQuery/AJAX to a separate php file.
Then as the landing page starts to load, I must grab that variable from mentioned PHP file and echo it in the relevant place.
I figured I don't actually need to start a session on the page with the form, as jquery is grabbing the data straight out the input, not any session data. So here's my input with conversion value:
<input type="hidden" id="conv" name="conv" value="90">
Then my form validation:
$("#course-form-modal").validator().submit(function(e) {
// when data is valid
if (!e.isDefaultPrevented()) {
// this grabs the value from my form
var con_val = $("#conv").val();
// and this sends it...
$.post(
"../../usersession.php",
{ data: con_val }
);
}
});
Then I've got the code in usersession.php... where I sent the data:
// As I'm just trying to echo what was sent to this page, via ajax, I shouldn't need to worry about starting/retrieving a SESSION yet... right?
<?php $var_value = $_POST['data']; ?>
<div id="results">
<?php echo $var_value ?>
</div>
// I CAN WORRY ABOUT THIS HALF LATER. RIGHT NOW I JUST WANT TO ECHO MY RESULTS ON USERSESSION.PHP //
Finally, I've got the code on my landing page to retrieve the data from usersession.php:
session_start();
$var_value = $_SESSION['conv'];
echo $var_value;
I'm not entirely sure all this code is right for starters, I'm more of a front end guy...
-EDIT-
Right, I'm pretty sure the code is correct at least now. For some reason it's still not working though. At the moment I'm wondering if WordPress would prevent me writing to usersessions.php from my javascript file (for reference, that file path is set absolutely in my working (not working) example)? I know WordPress will sometimes throw a 404 when you try to access a file directly.
The other potential issue could be with the third party software, vanillasoft. I've a link to their script in the action tag of my form, could that somehow bypass/kill the sending/receiving of data between the form > usersession.php > and then the landing page?
On a side note, if anyone has a great idea on how I can test if usersession.php is receiving the data then please let me know? I did have this code originally, but it returns nothing and if I link straight to the file after a send something (as in just paste the file url in to my browser) it returns a '0'...
if(isset($_POST['conv'])) {
session_start();
$_SESSION['conv'] = $_POST[''conv''];
echo "1";
} else {
echo "0";
}
Set your ID on the input. jQuery is looking for the ID, but you have only set the name.
<input type="hidden" name="conv" value="90">
Should be:
<input type="hidden" name="conv" id="conv" value="90">
EDIT:
Can't believe I didn't catch this earlier. Your problem is in the usersession.php at the following line.
$_SESSION['conv'] = $_POST[''conv''];
You have the POST quoted wrong.
It should be:
$_SESSION['conv'] = $_POST['conv'];
EDIT (re: New js edits)
In you java script your post vars should be formatted thusly:
{ name: "John", time: "2pm" }
So your line should be something like this:
$.post(
'../../usersession.php',
{
conv: $("#conv").val()
},
function(data)
{
alert("Data Loaded: " + $("#conv").val());
}
);

php post without form

I have a php page that takes some get strings, after some user interaction I want to continue executing some php code without navigating or refreshing the page so that its smooth and doesn't flicker. Ive tried secretly clicking invisible forms and it always refreshes, how can achieve this?
Also as a side note, I am using jquery but I was not able to get that post function up and running, I will keep trying it but let me know if that is a wrong solution.
//gallery.php
//jquery
$(".download").click(function()
{
$.post("gallery.php", { images: "testing it out" } );
});
<?php
if(isset($_POST['images']))
{
echo "It worked";
}
else if(isset($_GET['artist']))
{
echo "It worked2";
}
?>
They are both in the same page, the get always works because I pass the info though the url from another page. But the .download click doesnt cause the php code under post to execute
Use Ajax to send a HTTP request in the background.
Using Ajax is the solution...
You can try with jQuery, read this link http://api.jquery.com/jQuery.post/
jquery ajax is very simple method for post a form without page refresh ..
read more about ajax
Are you thinking of AJAX?

how to get form action response without ajax in a good way?

I know how to get an AJAX response:
$.post( '/action',
{ actiontodo: 'insert' }
function (data) { alert(data); } );
Int the action.php (server side):
<?php
if ($_POST['actiontodo'] == 'insert')
{
doInsertAction();
echo "inserted";
}
?>
Finally the output of this code is an alert BOX with the word: inserted.
BUT, without ajax, I have two ways to solve this (in the server side):
ONE:
<?php
if ($_POST['actiontodo'] == 'insert') {
doInsertAction();
header( "Location: " . $_SERVER['HTTP_REFERER'] . " &response=inserted" );
} ?>
TWO:
<?php
session_start();
if ($_POST['actiontodo'] == 'insert') {
doInsertAction();
$_SESSION['response'] = 'inserted';
}
header( "Location: " . $_SERVER['HTTP_REFERER'] );
?>
Returning to the page I get the answer from the SESSION or from GET and shows the alert.
I like more the ONE solution, but each solution has a problem:
ONE problem:
The returning URL is : http://www.foo.com/myrefererurl&response=inserted
If you types this URL without using the form, you will see the alert BOX each time you will refresh the page. The question is: How to show the message only ONE time? (ONLY AFTER THE FORM ACTION)
TWO problem:
The SESSION now has the value inserted ($_SESSION['response']), when the page returns from the action obviously the solution maybe delete this value of the session like: unset( $_SESSION['response'], but SUPPOSE the UNSET do not reached for any reason (connection failure or navigation stopped by the user, etc), when you go to another form in other page the alert will showed because the $_SESSION['response'] still exists (in another form without submit it and has nothing to do with that response). Inclusively WITH GET &response=inserted in another URL the problem will exists too.
I hope you understand this questions and bring a BEST WAY solution. Basically the question is how to control that responses......
Unobtrusive JS, or "progressive enhancement" is the way to go.
Step 1:
Build your page first to work without JavaScript. Let's say you have a simple application where a user selects something and hits submit. Depending on the selection, you will either display a helpful error message above the form or you'll update the page with the correct output and hide (or get rid of) the form. Build this page like you would for AJAX, but do not script anything yet.
Here's your page:
<html>
<head>
<style type="text/css">
p#feedback { display:none;}
</style>
</head>
<body>
<div id="feedback"></div>
<div id="form">
<form action="getaction.php" method="post" id="actionform">
<select name="requestedAction">
<option value="foo">Do Foo</option>
<option value="bar">Do Bar</option>
</select>
<input type="submit">
</form>
</div>
</body>
</html>
On a successful submission. the server will get a request with one $_POST value: requestedAction=foo (or bar). Based on this, your server script will construct a new page with everything from <html> to </html>.
At this point, you have a page that works in any non-JS-enabled browser. Old fashioned. Very reliable.
Step 2
Add the scripting to override the default submit behavior. Grab the data you need from the page and construct an AJAX submission. The only difference between this and the submission above is that you will add a flag telling the server that the request is coming via AJAX and to send back only the needed message (you could also send it to a different script). The server script will basically go through the same logic as above, but rather than building the entire page, it only sends back the message string and leaves it to AJAX to put that data in the right place. Your response could be just a text fragment, a block of HTML or an XML data structure. It depends on your needs.
<script type="text/javascript">
$(enhance); // at onDOMReady, run the enhance function
function enhance() {
// Override the default form submission behavior:
$('form#actionform').bind('submit',doSubmit);
};
function doSubmit(event) {
$.ajax(
{
type:'POST',
url:'/path/to/getaction.php',
data:'request=' + $('form#actionform select[name=requestedAction]').val() + '&type=ajax',
success:fnCallback
}
);
// Kill the submit action so the user doesn't leave the page
event.preventDefault();
};
function fnCallback(xhr) {
var strResponse = xhr.responseText;
if (strResponse === "error") {
$('div#feedback').text("There was an error. Please try again.");
}
else {
$('div#feedback').text(strResponse);
$('div#form').hide();
}
};
</script>
In this case, the AJAX submission will be identifiable to the server because there is a second POST parameter of type=ajax.
A site that does this really unbelievably well on a very big scale is ESPN. Turn off JS and check out their main story headlines under the big picture. The behavior is identical to their AJAX-enabled page and aside from the video not working, you really would never know if your JS was on or off. There's basically no way to build a site like this without starting from dumb HTML and building up.

Categories