I am trying to display search query results on a separate page. I copied the code from a forum, but since the display page isn't php, I'm not sure it will work.
Here is the code from the home page:
<form action="search" method="post">
<input type="text" name="q" />
<input type="submit" name="search" value="Search" />
</form>
I want the search results to show on mysite.com/search (obviously)
The code on mysite.com/search is as follows:
<div id="cse" style="width: 100%;">Loading</div>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">//
google.load('jquery', '1');
google.load('search', '1');
google.setOnLoadCallback(function(){
var customSearchControl = new google.search.CustomSearchControl('XXXXX');
customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
customSearchControl.draw('cse');
$(".gsc-input").val("<?php echo $_POST['q']; ?>");//insert into search field requested search text
$(".gsc-search-button").click();//call button click event, show results
}, true);
// ]]></script>
Do I have any options? Is there a workaround?
since the display page isn't php
Then you can't use $(".gsc-input").val("<?php echo $_POST['q']; ?>");, but could use something like
$.get('path-to-php-script/query.php', function(data) {
$(".gsc-input").html(data);
alert('Load was performed.');
});
The idea is that you just use jQuery to retrieve and manipulate the data that you need to run through PHP script(s) before they're returned to the HTML-only display page.
You can achive like this
Put this code in your head tag
<script language="javascript">
function changeData(fromDiv)
{
document.getElementById('toDiv').innerHTML = fromDiv.innerHTML;
}
</script>
And This in your body tag
<div id="toDiv"></div>
<div id="fromDiv" onclick="changeData(this)">Hello World I am here</div>
Related
Updated: It still not work after I add "#".
I am new to ajax. I am practicing to send value to php script ,and get result back.
Right now, I met one issue which I can not show my result in my html page.
I tried serves answers online, but I still can not fix this issue.
My index.html take value from the form and send form information to getResult.php.
My getResult.php will do calculation and echo result.
How do I display result into index.html?
Hers is html code
index.html
<html>
<body>
<form name="simIntCal" id="simIntCal" method="post"
>
<p id="Amount" >Amount(USD)</p>
<input id="amount_value" type="text" name="amount_value">
<p id="annual_rate" >Annual Rate of Interest
(%)</p>
<input id="rate_value" type="text" name="rate_value">
<p id="time_years" >Time (years)</p>
<input id="time_value" type="text" name="time">
<input id="calculate" type="submit" value="Calculate">
</form>
<p id="amount_inteCal" >The Amount (Acount
+ Interest) is</p>
<input id="result" type="text">
</body>
</html>
ajax script :
<script>
$('#simIntCal').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'getResult.php',
data: $('#simIntCal').serialize(),
success: function (result) {
$("#result").text(result);// display result from getResult.php
alert('success');
}
});
});
</script>
getResult.php
<?php
if ($_SERVER ["REQUEST_METHOD"] == "POST") {
//do some calculation
$result=10;//set result to 10 for testing
echo $result;
}
?>
You are missing the '#' in front of your css selector for result.
$("result").text(result);// display result from cal.php
Should be
$("#result").text(result);// display result from cal.php
index.php
----php start---------
if(isset($_POST['name'])){
echo 'Thank you, '.$_POST['name']; exit();
}
----php end ---------
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
function test(){
var formDATA = {'name': $('#input_name').val()}
$.ajax({
type: 'POST',
url: 'index.php',
data: formDATA,
success: function(response){
$('#result').html();
}
});
}
</script>
<input id="input_name" type="text" value="">
<button onclick="test();">Test Ajax</button>
<div id="result"></div>
Try something simple, this is a very basic version of ajax and php all in one page. Since the button triggers the function you don't even need a form (doesn't mean you shouldn't use one). But i left it simple so you could follow everything.
Sorry when i added php open and closing tags it didn't show up as code.
Also don't forget to include your jquery resources.
In your html file where you want the result to display, you probably want to be using a div.
Currently your code is using an input field:
<input id="result" type="text">
And what you probably want is something like this:
<div id="result"></div>
Unless you were intending to have the result show up in an input field inside your form, and in that case, the input field isn't actually inside your form code.
I currently have two PHP pages: test1.php and test2.php. Inside test1 are 2 DIVs: one named "SubmitDiv", and one named "DisplayDiv". Inside SubmitDiv is a Submit button. When the user clicks on the Submit button, it should load test2.php inside DisplayDiv. Currently test2.php will only display "Hello World". I want it to load test2.php inside the DisplayDiv so that the test1.php page doesn't need to break stride or otherwise reload.
And this is where I am stuck. I am aware that I likely have to make use of AJAX in order for it to dynamically load the test2.php page inside DisplayDiv. How this is done, however, has bested me, and my attempts at it have so far failed. Using the below scripts, which I have pieced together from online searches of this issue, when I try to click on the Submit button - which should load test2.php inside DisplayDiv - instead it just refreshes the whole page and no test2.php is loaded.
test1.php:
<html>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
function loadSubmitResults() {
$(function() {
$('#DisplayDiv').load('test2.php');
});
}
</script>
<body>
<div id="page">
<form id="SubmitForm" method="post">
<div id="SubmitDiv" style="background-color:black;">
<button type="submit" form="SubmitForm" onclick="loadSubmitResults();">Submit</button>
</div>
</form>
<div id="DisplayDiv" style="background-color:red;">
<!-- This is where test2.php should be inserted -->
</div>
</div>
</body>
test2.php:
<html>
<meta charset="utf-8">
<body>
<div id="page" style="background-color:yellow;">
<?php
echo "Hello World.";
?>
</div>
</body>
</html>
If this were something I was working on, I'd change:
<button type="submit" form="QueryForm" onclick="loadQueryResults();">Submit Query</button>
to
<button type="submit" form="QueryForm" onclick="return loadQueryResults();">Submit Query</button>
Then I'd change your loadQueryResults function to:
function loadQueryResults() {
$('#DisplayDiv').load('test2.php');
return false;
}
What this is doing is then returning the value of false to the onclick of the button which as a type of "submit" will, by default, submit the form. Returning any false value on a form submit will cause the form to not submit. Returning false is a general rule when trying to prevent default events from running.
The structure here is a little strange:
function loadQueryResults() {
$(function() {
$('#DisplayDiv').load('test2.php');
});
}
You're declaring a function, but inside of that function you call the jQuery function and pass it a function with the code you want to run? Normally the latter is for running something when the document is ready. It shouldn't be needed here. My guess is that this inner code (the one line you want to run) never actually gets executed.
Does a simpler version like this work for you?:
function loadQueryResults() {
$('#DisplayDiv').load('test2.php');
}
This should just run the code you want when the function is called, without the various decorations of the jQuery function.
For good measure, you should also return false to try to prevent the default submit action:
function loadQueryResults() {
$('#DisplayDiv').load('test2.php');
return false;
}
You can further improve this by using a selector in the call to .load() to pick out only the parts of the DOM that you want. Things like html and body might be stripped out automatically, but explicitly doing things is better than guessing:
$('#DisplayDiv').load('test2.php #page');
Of course, now you're also in a situation where you may end up with multiple elements of the id page in the same DOM, which is invalid. You may want to consider changing some of your ids.
The best way to do this is with the code below:
test1.php:
<html>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
// Handler for .ready() called.
$('#SubmitForm').submit(function( event ) {
$.ajax({
url: 'test2.php',
type: 'POST',
dataType: 'html',
data: $('#SubmitForm').serialize(),
success: function(content)
{
$("#DisplayDiv").html(content);
}
});
event.preventDefault();
});
});
</script>
<body>
<div id="page">
<form id="SubmitForm" method="post">
<div id="SubmitDiv" style="background-color:black;">
<button type="submit" class="btnSubmit">Submit</button>
</div>
</form>
<div id="DisplayDiv" style="background-color:red;">
<!-- This is where test2.php should be inserted -->
</div>
</div>
</body>
test2.php:
<div id="page" style="background-color:yellow;">
<?php
echo "Hello World.";
?>
</div>
this a simple example in how to submit form using the Jquery form plugins and retrieving data using html format
html Code
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
// prepare the form when the DOM is ready
$(document).ready(function() {
// bind form using ajaxForm
$('#htmlForm').ajaxForm({
// target identifies the element(s) to update with the server response
target: '#htmlExampleTarget',
// success identifies the function to invoke when the server response
// has been received; here we apply a fade-in effect to the new content
success: function() {
$('#htmlExampleTarget').fadeIn('slow');
}
});
});
</script>
</head>
<body>
<form id="htmlForm" action="post.php" method="post">
Message: <input type="text" name="message" value="Hello HTML" />
<input type="submit" value="Echo as HTML" />
</form>
<div id="htmlExampleTarget"></div>
</body>
</html>
PHP Code
<?php
echo '<div style="background-color:#ffa; padding:20px">' . $_POST['message'] . '</div>';
?>
this just work fine
what i need to know if what if i need to Serialize the form fields so how to pass this option through the JS function
also i want show a loading message while form processed
how should i do that too
thank you
To serailize and post that to a php page, you need only jQuery in your page. no other plugin needed
$("#htmlForm").submit(function(){
var serializedData= $("#htmlForm").serialize();
$.post("post.php", { dat: serializedData}, function(data) {
//do whatever with the response here
});
});
If you want to show a loading message, you can do that before you start the post call.
Assuming you have div with id "divProgress" present in your page
HTML
<div id="divProgress" style="display:none;"></div>
Script
$(function(){
$("#htmlForm").submit(function(){
$("#divProgress").html("Please wait...").fadeIn(400,function(){
var serializedData= $("#htmlForm").serialize();
$.post("post.php", { dat: serializedData},function(data) {
//do whatever with the response here
});
});
});
});
The answer posted by Shyju should work just fine. I think the 'dat' should be given in quotes.
$.post("post.php", { 'dat': serializedData},function(data) {
...
}
OR simply,
$.post("post.php", serializedData, function(data) {
...
}
and access the data using $_POST in PHP.
NOTE: Sorry, I have not tested the code, but it should work.
Phery library does this behind the scenes for you, just create the form with and it will submit your inputs in form automatically. http://phery-php-ajax.net/
<?php
Phery::instance()->set(array(
'remote-function' => function($data){
return PheryResponse::factory('#htmlExampleTarget')->fadeIn('slow');
}
))->process();
?>
<?php echo Phery::form_for('remote-function', 'post.php', array('id' => ''); ?> //outputs <form data-remote="remote-function">
Message: <input type="text" name="message" value="Hello HTML" />
<input type="submit" value="Echo as HTML" />
</form>
<div id="htmlExampleTarget"></div>
</body>
</html>
I know a bit php, ajax & javascript (and jQuery) - but since I am a bit of a begginer I need a little help to connect the dots for this easy task:
I want to let the user enter sometext (lets say: "I saw the sun, the sun is so nice and shiny") and I want to send this text to the server and then replace the word "sun" with "moon") - send it back to the user and write to him: "I saw the moon, the moon is so nice and shiny").
I just need help with understanding:
How do I send the text to the server using php.
How do I manipulate it and sends it back to the user.
I am sure there is a tutorial for it - I just didn't know how to look for it so I am asking here - to get a good start.
<?php
if (isset($_POST['text'])) //only execute if some text were sent to this script
{
echo str_replace('sun','moon',$_POST['text']); //manipulate the text and print it
die(); // stop script execution
}
?>
<html>
<head>
<script>
$(document).ready(function(){//when document finished to load
$('#send').click(function(){//when user clicked on send button
var text = $('#text').val();//get the text from input field
$.post('',{text:text},function(data){ // send the text to the current script as a post variable called text
alert(data); // when we received the response display it in alert window
});
});
});
</script>
</head>
<body>
<input type="text" id="text" />
<input type="button" value="send" id="send" />
</body>
</html>
no ajax needed
<?php
if ($_POST){
if ($_POST['name']){
echo str_replace('sun', 'moon', $_POST['name']);
}
}
?>
<form method="post" action="">
<input type="text" name="text" />
<input type="submit" />
</form>
if you want ajax, do this
<?php
if ($_POST){
if ($_POST['name']){
echo str_replace('sun', 'moon', $_POST['name']);
}
}else{
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script>
$("form").submit(function(){
$.post('<?php echo $_SERVER['PHP_SELF']; ?>', {name:$("#name").val()},
function(html){
$("body").append(html);
}
);
return false;
</script>
<body>
<form method="post" action="">
<input type="text" id="name" name="name" />
<input type="submit" />
</form>
</body>
<?php
}
?>
Google is your friend. I searched for "ajax for beginners jquery php". There are hundreds, thousands of resources to walk you through this very thing. Here's one tutorial that I found:
http://www.devirtuoso.com/2009/07/beginners-guide-to-using-ajax-with-jquery/
Try to google for ajax and jquery tutorials. Basically it would work something like this:
Get user text input and call a javascript function that will send that text to process.php page
//input page
function getAjax(text){
var $data = "sentText="+ text +";
$.ajax({
type: "GET",
dataType: 'text',
url: "process.php",
data: $data,
success: function(output){
$('#responseDiv').html(output); //output is the text echoed from the php page
}
});
}
on the process.php page you take that text from a $_GET variable
//process.php
$sentText = $_GET['sentText'];
echo $sentText.' - some new text added';
I have a form that calls a php script on submit to insert data into a MySQL database. I would like the output of the php script return to a greybox. I haven't been able to make it work so I appreciate any help you guys can provide.
I have the greybox call on the form definition see below but is not doing the trick.
Here is a subset of the code:
<script type="text/javascript" src="greybox/AJS.js"></script>
<script type="text/javascript" src="greybox/AJX_fx.js"></script>
<script type="text/javascript" src="greybox/gb_scripts.js"></script>
<div id="content">
<form id="contact_us" name="contact_us" action="contact-greybox.php" method="POST" onSubmit="return GB_showCenter('Testing', this.action, 500, 500)">
<fieldset>
<label for="employee_id">Employee ID:</label>
<input id="employee_id" name="employee_id" type="number" size="10" /><P />
<label for="employee_name">Employee Name:<strong><br /> (as it should appear on
email) </strong></label>
<input id="employee_name" name="employee_name" type="text" /><P />
</fieldlist>
<p class="submit"><input type="image" name="submit" value="Submit Form" src="icons/ambas_submit.jpg" boder="0">
</form>
</div>
The php is a simple insert statement into MySQL.
Appreciate any help
greybox doesn't support POST submits, but the general pattern is to use ajax to submit the form- otherwise your page will refresh.
You need to set an onclick( $.submit ) to the form input then return false at the end of your ajax call:
$('#contact_us').submit(function(){
//get your inputs here
var e_id = $.('#employee_id').val();
//...etc....
$.post( ...
//set your data/input fields here:
data: { id: e_id },
success: function(response){
//display the response: this is what you get back from: contact-greybox.php
}
})
return false;
});
fancybox is an overlay box that supports being called with pure html as a parameter, so that you can just put this in your success function:
$.fancybox(response);
...or
$.fancybox(response.html)... etc.