How can I combine php documents to 1 document? - php

I'm making something like stock-price finder, there is data table made up of stock name, code, price.
what I want to do is if user input stock name on index.html, the result will shown at result.php , and If user click stock name, describe more information on view.php. anyway I made up this, the problem is... I think the pagination would be complicated with user, I want to combine pages to one page. not using result.php and view.php, but only index.html.
Like this...
There are some variable moving page to page, so I'm very afraid of how can I merge this pages. user input text, and the code. I don't know how I can control it.
index.html
<form action="./result.php" method="get">
<label>
Search
<input type="text" name="keywords">
<input type="submit" value="Search">
</label>
</form>
result.php
<?php
require_once './require/db.php';
if(isset($_GET['keywords'])){
$keywords = $db->escape_string($_GET['keywords']);
$query = $db->query("SELECT name,code FROM data2 WHERE name LIKE '%{$keywords}%' ");
?>
<div class="result-count">
Found <?php echo $query->num_rows; ?> results.
</div>
<?php
}
if($query->num_rows) {
while($r = $query->fetch_object()) {
?>
<div class="result">
<a href="./result.php?code=<?php echo $r->code;?>">
<?php echo $r->name; ?></a>
</div>
<br />
<br />
<?php
}
}
?>
view.php
<?php
require_once("./require/file_get_contents_curl.php");
$code = $_GET['code'];
$source = file_get_contents("http://www.nasdaq.com/symbol/$code");
$dom = new DOMDocument();
#$dom->loadHTML();
$stacks = $dom->getElementsByTagName('dl')->item(0)->textContent;
?>
The above code I made up. but I want to merge it. How can I combine 3 documents to 1 document? because of user input 'keywords(index.html->result.php)' and '_GET variable(result.php->view.php)' It's very difficult to me. Please help me.

You can keep your separate files, but instead of displaying the information inside those actual files, you can call them via AJAX (asynchronous HTTP requests) instead. Here's the syntax using jQuery:
index.html
<input type="text" id="keywords">
<button id="search">Search</button>
<div id="result"></div> <!-- The div that will be filled with the result from the AJAX request -->
Javascript
$('#search').click(function(){
$.ajax({
url: "result.php",
method: "POST",
data: {keywords: $('#keywords').val()}
}).success(function(result) {
$('#result').html(result);
});
});
result.php
<?php
require_once './require/db.php';
if(isset($_POST['keywords'])){
$keywords = $db->escape_string($_POST['keywords']);
$query = $db->query("SELECT name,code FROM data2 WHERE name LIKE ' {$keywords}%' ");
echo "Found ".$query->num_rows." results.";
?>
So in the example I made up above you pass in the variable keywords as keywords. This means that inside result.php, you can access the variable keywords via $_POST['keywords'].
So basically, you do the exact same things in result.php and view.php you've done so far, but you return the data to the index.html file instead of just echoing it out in that file. If you want to read more about the AJAX function in jQuery, here's a link: jQuery.ajax().
Hope this helps, please let me know if you wonder something.

This is a very broad question.
So the answer will be very subjective.
If this is your first rodeo, I think its a good time to learn about AJAX.
The basic idea is that you let a javascript request information from the server, and add the response to the page.
AJAX is a complex set of methods, but with modern frameworks like jquery, it's become easy to implement.
See this documentation:
http://www.w3schools.com/jquery/jquery_get_started.asp
and
https://api.jquery.com/jquery.get/
when jquery is added to your page, try this:
$.get( "result.php", function( data ) {
$( ".result" ).html( data );
alert( "Load was performed." );
});
if you do not like ajax,
try adding iframes to the index.html, and set the src of the iframe to the php page you want to display.
This will cause them to load once. So you need to refresh them everytime the dropdown changes.
that could be a little tricky: How to refresh an IFrame using Javascript?

Related

Ajax output to second div using PHP

I am a new user of ajax; so...
I am using ajax on a simple html page to access a php script to receive data, calculate results using data in an mysql table, and echo results in a div on the same page. My javascript statement to do this is:
$.post('ajax/phpscript.php', {
postuser:theuser,
postname:uans1
}, function(data) {
$('#outputdiv1').html(data);
}
);
The php echo output goes to a div on the main page called outputdiv1.
I got that part; no problem. Not sure exactly how it works, but it does work.
I would also like to echo output to a different div (which I will call outputdiv2) on the same page, using the php script. In my php script, How do I refer to or echo output this other div?
I guess I could have a second $.post statement in the javascript code, accessing a second php script. But that would force me to access the mysql database a second time. Doesn't seem efficient to me.
Is there a better way to do this?
Thanks.
HTML code is here:
theuser is defined earlier
<table width=400 align=center><tr><td>
There is a question here, with 2 possible answers:<p>
<form>
<input type=radio style="width:22px; height:22px" name="ques1" id="opt1" value="answer 1" onclick="post1()"> answer 1<br>
<input type=radio style="width:22px; height:22px" name="ques1" id="opt2" value="answer 2" onclick="post1()"> answer 2<br>
</form>
<div id="outdiv1">first response from php will go here, beneath the question.<br></div>
<script type="text/javascript">
function post1() {
var uans1 = "none"
if (document.getElementById("opt2").checked) {
uans1 = "answer 2"
}
if (document.getElementById("opt1").checked) {
uans1 = "answer 1"
}
$.post('ajax/phpscript.php',{postuser:theuser,postname:uans1}, function(data) {$('#ans1div').html(data);});
}
</script>
</td>
<td width=20%>
<div id="outputdiv2">
second response from php will go here, to the right of the question.<p>
</div>
</td>
</tr></table>
first response will not be the same as the second response.
You could use JSON to communicate and return an array. something like this in js
$.ajax({
url: 'ajax/phpscript.php',
method: 'POST',
data: {
postuser: theuser,
postname: uans1
},
dataType: 'JSON'
}).done(function(data) {
if ($.isArray(data)) {
$('#outputdiv1').html(data[0]);
$('#outputdiv2').html(data[1]);
}
});
And your php script should do something look like this
<?php
include('dbconnection.php');
$result = [];
//SELECT data for div1 (part you already have)
$result[] = $mysql_result_as_html_for_outputdiv_1; // In your case this would be a html string
//SELECT other data for div2
$result[] = $mysql_result_as_html_for_outputdiv_2; // In your case this would be a html string
header('Content-Type: application/json');
echo json_encode($result);
?>
An even more clean solution would be to just return the data as objects from php and make some templates in js suitable for your data.
You need to understand this: who write in the div is javascript, not php, cause you are using ajax. Ajax is a way to comunicate with php, and give a response. Now you need to handle this response with javascript.
If you want to put the same content in outputdiv1 and outputdiv2, you not need to post ajax again, only write it in two divs.
$.post('ajax/phpscript.php',{postuser:theuser,postname:uans1}, function(data) {$('#outputdiv1').html(data);$('#outputdiv2').html(data);});
if you want different data i suggest you think the system to get all result that you need in one post request and return it in a json format (see http://php.net/manual/es/function.json-encode.php), so you can handle better with JSON.parse() in client side.

Passing the link's text as a value to the next page

I am trying to pass the link's text as a value to the next page so I can use it to search the database for the item and retrieve the information related to the value .I have tried using the POST method but regardless the information is not passed. This is the code I tried .
<form action="DetailedMenu.php" method = "POST" action = "<?php $_PHP_SELF ?>">
<?php
for($i=0;$i<sizeof($array);$i++) {
if($array[$i]["Food_Category"]=="starters") {
echo str_repeat(' ', 4); ?>
<a href="DetailedMenu.php" ><?php echo $array[$i]["Food_Name"];?></a>
<?php echo " " .str_repeat('. ', 25). "€".$array[$i]["Food_Price"]."<br>"; ?>
<input type="hidden" name="name" value="<?php echo $array[$i]["Food_Name"];?>">
<?php
}
}
?>
</form>
You don't need the form.
The easiest way to do what you're trying to do....
In addition to including the text in the content of the link, include it as a query string parameter.
for($i=0;$i<sizeof($array);$i++) {
if($array[$i]["Food_Category"]=="starters") {
...
<?php echo $array[$i]["Food_Name"];?>
...
}
}
I would actually recommend something more like this. I obviously don't know the names of your fields, so I've just taken a guess...
for($i=0;$i<sizeof($array);$i++) {
if($array[$i]["Food_Category"]=="starters") {
...
<?php echo $array[$i]["Food_Name"];?>
...
}
}
You'll be able to access "FoodID" as a parameter within your PHP, just as you would if it had been submitted from a form.
You may be looking for AJAX. AJAX lets you send the form data to a back end PHP file (that can then insert data into a DB, and/or get data from the DB) without refreshing the page.
In fact, when you are using AJAX you don't even need to use a <form> structure -- simple DIVs work just fine. Then you don't need to use event.preventDefault() to suppress the built-in form refresh.
Just build a structure inside a DIV (input fields, labels, etc) and when the user is ready to submit, they can click an ordinary button:
<button id="btnSubmit">Submit</button>
jQuery:
$('#btnSubmit').click(function(){
var fn = $('#firstname').val();
var ln = $('#lastname').val();
$.ajax({
type: 'post',
url: 'ajax_receiver.php',
data: 'fn=' +fn+ '&ln=' +ln,
success: function(d){
if (d.length) alert(d);
}
});
});
ajax_receiver.php:
<?php
$fn = $_POST['fn'];
$ln = $_POST['ln'];
//Do your stuff
Check out this post and especially its examples. Copy them onto your own system and see how they work. It's pretty simple.

How to save and retrieve contenteditable data

I want to be able to change the text of some pages. Using contenteditable would be perfect for me.
Problem is that I only know how to program in PHP. I have searched on the internet for hours trying to make it work, but I just don't understand the programming languages used to store the data enough to make it work.
This is how I would like it to work:
Admin hits a button 'edit'
div becomes editable.
When the admin is ready editing, he hits a button 'save'
The data is saved to a file or database (don't really know what would be the best option).
The edited content shows up when the page is opened.
This is all I have for now:
<div class="big_wrapper" contenteditable>
PAGE CONTENT
</div>
I know how to make the part with converting the div to an contenteditable div when the admin hits 'edit'.
My problem is that i really have no idea how to save the edited data.
I also don't know if it would be hard to retrieve the data from a file, depents on the way how the data is saved. If it is saved to a database I would have no problem retrieving it, but I don't know if that is possible and if that is the best option.
Thanks for your help,
Samuël
EDIT:
#gibberish, thank you so much for your super-quick reply!
I tried to make it work, but it doesn't work yet. I can not figure out what i'm doing wrong.
Here's my code:
over_ons.php:
<div class="big_wrapper" contenteditable>
PAGE CONTENT
</div>
<input type="button" value="Send Data" id="mybutt">
<script type="text/javascript">
$('#mybutt').click(function(){
var myTxt = $('.big_wrapper').html();
$.ajax({
type: 'post',
url: 'sent_data.php',
data: 'varname=' +myTxt+ '&anothervar=' +moreTxt
});
});
</script>
sent_data.php:
<?php
session_start();
include_once('./main.php');
include($main .'connectie.php');
$tekst=$_POST['myTxt'];
$query="UPDATE paginas SET inhoud='" .$tekst. "' WHERE id='1'";
mysql_query($query);
?>
Thanks again for your great help!
Can you also help me to make the div editable only when the user hits a button?
SOLUTION:
It took me over 2 weeks to finally make everyting work. I had to learn javascript, jQuery and Ajax. But now it works flawlessly. I even added some extras for the fanciness :)
I would like to share how i did this if someone wants to do the same.
over_ons.php:
//Active page:
$pagina = 'over_ons'; ?>
<input type='hidden' id='pagina' value='<?php echo $pagina; ?>'> <!--Show active page to javascript--><?php
//Active user:
if(isset($_SESSION['correct_ingelogd']) and $_SESSION['functie']=='admin'){
$editor = $_SESSION['gebruikersnaam']; ?>
<input type='hidden' id='editor' value='<?php echo $editor; ?>'> <!--Show active user to javascript--><?php
} ?>
<!--Editable DIV: -->
<div class='big_wrapper' id='editable'>
<?php
//Get eddited page content from the database
$query=mysql_query("SELECT inhoud FROM paginas WHERE naam_pagina='" .$pagina. "'");
while($inhoud_test=mysql_fetch_array($query)){
$inhoud=$inhoud_test[0];
}
//Show content
echo $inhoud;
?>
</div>
<!--Show edit button-->
<?php
if(isset($_SESSION['correct_ingelogd']) and $_SESSION['functie']=='admin')
{?>
<div id='sidenote'>
<input type='button' value='Bewerken' id='sent_data' class='button' />
<div id="feedback" />
</div>
<?php }
As this is a pretty long and complicated file, I tried to translate most of my comments to english.
If you want to translate something that in't already translated, the original language is Dutch.
javascript.js:
//If the system is in edit mode and the user tries to leave the page,
//let the user know it is not so smart to leave yet.
$(window).bind('beforeunload', function(){
var value = $('#sent_data').attr('value'); //change the name of the edit button
if(value == 'Verstuur bewerkingen'){
return 'Are you sure you want to leave the page? All unsaved edits will be lost!';
}
});
//Make content editable
$('#sent_data').click(function(){
var value = $('#sent_data').attr('value'); //change the name of the edit button
if(value == 'Bewerken'){
$('#sent_data').attr('value', 'Verstuur bewerkingen'); //change the name of the edit button
var $div=$('#editable'), isEditable=$div.is('.editable'); //Make div editable
$div.prop('contenteditable',!isEditable).toggleClass('editable')
$('#feedback').html('<p class="opvallend">The content from<BR>this page is now<BR>editable.</p>');
}else if(value == 'Verstuur bewerkingen'){
var pagina = $('#pagina').val();
var editor = $('#editor').val();
var div_inhoud = $("#editable").html();
$.ajax({
type: 'POST',
url: 'sent_data.php',
data: 'tekst=' +div_inhoud+ '&pagina=' +pagina+ '&editor=' +editor,
success: function(data){
Change the div back tot not editable, and change the button's name
$('#sent_data').attr('value', 'Bewerken'); //change the name of the edit button
var $div=$('#editable'), isEditable=$div.is('.editable'); //Make div not editable
$div.prop('contenteditable',!isEditable).toggleClass('editable')
//Tell the user if the edditing was succesfully
$('#feedback').html(data);
setTimeout(function(){
var value = $('#sent_data').attr('value'); //look up the name of the edit button
if(value == 'Bewerken'){ //Only if the button's name is 'bewerken', take away the help text
$('#feedback').text('');
}
}, 5000);
}
}).fail(function() {
//If there was an error, let the user know
$('#feedback').html('<p class="opvallend">There was an error.<BR>Your changes have<BR>not been saved.<BR>Please try again.</p>');
});
}
});
And finally,
sent_data.php:
<?php
session_start();
include_once('./main.php');
include($main .'connectie.php');
//Look up witch page has to be edited
$pagina=$_POST['pagina'];
//Get the name of the person who eddited the page
$editor=$_POST['editor'];
//Get content:
$tekst=$_POST['tekst'];
$tekst = mysql_real_escape_string($tekst);
$query="UPDATE paginas SET naam_editer='" .$editor. "', inhoud='" .$tekst. "' WHERE naam_pagina='" .$pagina. "'";
}
if(mysql_query($query)){
echo "<p class='opvallend'>Successfully saves changes.</p>";
}else{
echo "<p class='opvallend'>Saving of changes failed.<BR>
Please try again.</p>";
}
?>
Use a client-side language, such as JavaScript (or best, jQuery), to manage whether the input boxes could be edited.
Use AJAX to grab the field data and fire it off to a PHP file, which would stick the data in your database.
Here is a very simplified example of using jQuery to manage enabling/disabling the input fields:
jsFiddle Demo
$('.editable').prop('disabled',true);
$('.editbutt').click(function(){
var num = $(this).attr('id').split('-')[1];
$('#edit-'+num).prop('disabled',false).focus();
});
$('.editable').blur(function(){
var myTxt = $(this).val();
$.ajax({
type: 'post',
url: 'some_php_file.php',
data: 'varname=' +myTxt+ '&anothervar=' +moreTxt
});
});
PHP file: some_php_file.php
<?php
$myVar = $_POST['varname'];
$secondVar = $_POST['anothervar'];
//Now, do what you want with the data in the vars
Using AJAX is quite easy. I gave a very brief example of what it would look like. Don't look in the HTML or jQuery for the moreTxt variable -- I added that to show how you would add a second var of data to the ajax.
Here are some basic examples to bring you up to speed on ajax:
AJAX request callback using jQuery
There is no short path to learning jQuery or AJAX. Read the examples and experiment.
You can find some excellent, free jQuery tutorials here:
http://thenewboston.com
http://phpacademy.org
UPDATE EDIT:
To respond to your comment inquiry:
To send data from a DIV to a PHP file, first you need an event that triggers the code. As you mentioned, on an input field, this can be the blur() event, which triggers when you leave a field. On a <select>, it can be the change() event, which triggers when you choose a selection. But on a DIV... well, the user cannot interact with a div, right? The trigger must be something that the user does, such as clicking a button.
So, the user clicks a button -- you can get the content of the DIV using the .html() command. (On input boxes and select controls, you would use .val(), but on DIVs and table cells you must use .html(). Code would look like this:
How to send DIV content after a button clicked:
HTML:
<div class='big_wrapper' contenteditable>
PAGE CONTENT
</div>
<input id="mybutt" type="button" value="Send Data" />
jQuery:
$('#mybutt').click(function(){
var myTxt = $('.big_wrapper').html();
$.ajax({
type: 'post',
url: 'some_php_file.php',
data: 'varname=' +myTxt+ '&anothervar=' +moreTxt
});
});
You could save the whole
page clientside with this:
<script>
function saveAs(filename, allHtml) {
allHtml = document.documentElement.outerHTML;
var blob = new Blob([allHtml], {type: 'text/csv'});
if(window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveBlob(blob, filename);
}
else{
var elem = window.document.createElement('a');
elem.href = window.URL.createObjectURL(blob);
elem.download = filename;
document.body.appendChild(elem);
elem.click();
document.body.removeChild(elem);
}
}
</script>
hth

Post operation with Jquery

I want to edit photo in my datatable with Jquery.For this,
<a href="ajax/edit_photo.php?id=<?=$row['ID']?>" class="edit ajax" id="">-->'Edit Photo Link'
edit_photo.php:
<div class="photoEdit">
<form id="editphoto" action="1.php?id=<?=$_GET['id']?>" method="post" class="stdform quickform" enctype="multipart/form-data">
//My Forms...
</form>
</div>
My Jquery:
jQuery('#editphoto').submit(function(){
var formdata = jQuery(this).serialize();
var url = jQuery(this).attr('action');
jQuery.post(url, formdata, function(data){
jQuery('.notifyMessage').addClass('notifySuccess');
//otherwise
//jQuery('.notifyMessage').addClass('notifyError');
jQuery.fn.colorbox.resize();
});
return false;
});
And My 1.php
<?
include("../../connection.php");
include("../../functions/upload.php");
?>
<?
$limit="1048576";
if(isset($_GET['kaydet'])){
$id=$_GET['id'];
$icerik=$_POST['icerik'];
$picture=DoUpload("picture",$limit,$FileUploadPath);
$result=mysql_query("SELECT * FROM tbl_photo WHERE ID=$id");
$picture2=mysql_result($result,0,"picture");
if($picture=='')
$picture=$picture2;
if($picture!="")
{
mysql_query("UPDATE `tbl_photo` SET `picture` = '$picture',`icerik` = '$icerik' WHERE `ID` =$id");
}
}
?>
I coded something.But in my operation,Jquery doesn't work.So,does not to anything.
You cannot upload binary through jquery. You would have to use the iframe method, or use some jquery library. (This one is an easy one to try. http://blueimp.github.com/jQuery-File-Upload/)
Plus you are mixing GET and POST in your PHP code. Since you are doing a POST request in jquery, you won't be able to get any variables in PHP using $_GET. They should all be replaced with $_POST.
for image uploads or other binary data use a hidden iframe.
<div style="position:absolute;top-500px;">
<iframe src="blank.htm" id=ifr name="ifr">
</iframe>
</div>
then have your image form submit to the iframe.
<form target="ifr" onsubmit="pollstatus(<?php=$id ?>)">
add a hidden form field to your form with an unique identifier.
then have an ajax call the status of the processing with the id every 100ms with setinterval, if processing is complete retrieve the image using ajax to get html code that displays the image as you like it with css transformations, however fancy you like it, and place that in your result div

Send $.post from JQuery to controller in code igniter and load the result

I want to send a post from HTML that contains info about a certain form to a controller in code igniter. The I want the controller to process the info and loads a certain page inside a div. Here is my code. I think I'm supposed to use something like .html or something? I'm not quite sure, I dont understand it
The controller
function search_friend(){
//this function gets text from text field and searches for a user and returns all users similar to this dude
// $this->input->post($searchFriendForm);
// $this->input->post($searchFriendText);
$this->load->model('userProfile_m');
$people = $this->userProfile_m->get_user_by_name($this->input->post($searchFriendText));
$this->load->view('addFriendSearchResult',$people);
}
the form in html
<form method="post" action="" name="searchFriendForm" id="add-friend-search">
<input type="text"/ name="searchFriendText">
<input type="button" class="small green button" id="add-friend-button" />
</form>
the jquery function
$("#add-friend-button").click(function(){ //start click
$.post("<?php echo site_url('userProfile/search_friend'); ?>", $("#add-friend-search").serialize());
$("#insert-activity").load("<?php echo base_url().''?>system/application/views/addFriendSearchResult.php");
$("#add-friend-search").slideUp("slow",function(){});
}); //end click
Firstly, in your controller change this line like this (u need to pass the string name of the field here):
$people = $this->userProfile_m->get_user_by_name($this->input->post('searchFriendText'));
Next, change your jQuery to be like this:
$("#add-friend-button").click(function(){ //start click
$.post("<?php echo site_url('userProfile/search_friend'); ?>",
$("#add-friend-search").serialize(),
function(data){
$("#insert-activity").html(data);
});
$("#add-friend-search").slideUp("slow",function(){});
}); //end click
You cant call your view directly, and you don't need to. The post should return the data, which you can write out to your #insert-activity element.

Categories