Post operation with Jquery - php

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

Related

How can I combine php documents to 1 document?

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?

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

How to pass variables to an AJAX call without a form

I am building an application in Code Igniter and am currently building some functionality where a user can approve or deny a request on the page by clicking either a tick or a cross icon on the page. These icons are anchor tags.
The trouble I am having is passing an ID for that individual request to the AJAX form.
I would have no issue implementing this functionality in a form as I would simply use a hidden input field which would have it's value saved in it set from the controller. There can be many of these requests but they would always have their own individual ID as it is looped through in the view.
As I am using anchor tags instead of a form I am not sure where I could store the id for that request in the markup.
Here is the code:
<p><span class="bold">Authorise This Request?: </span></p>
<p>
<img src="/igniter/images/tick.png" />
<img src="/igniter/images/cross.png" />
</p>
</div>
<?php $i++; ?>
<?php } ?>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('.authorise').click(function() {
$.ajax({
type: "POST",
url: 'holiday_request/authoriseRequest',
data: 'check=' + $(this).attr('id'),
success: function(data) {
}
});
return false;
});
});
</script>
As you can see I use the ID of the input field to determine later on whether to allow or deny it. All I want to do is to be able to pass the ID for that request through which is currently in the controller, so adding '&id= blahblahblah' onto the end of the URL variable in the AJAX call.
Is there a way I can do this without having to use a form instead of anchor tags?
You can use HTML5 data-* Attributes
<img src="/igniter/images/tick.png" />
...
Then get the value and add it to ajax data parameter
data: 'check=' + $(this).data('check') + '&id=' + $(this).data('id'),
You can store the ID in Data attribute of the anchor tag.
<img src="/igniter/images/tick.png" />
To get the stored value for allow anchor tag using jquery.
$val_allow = $('#allow').data('val'); // value 10
You can try using $.post and can have custom parameters as you like!
$.post({ 'holiday_request/authoriseRequest' , { check: someId , anotherParam: 1 } ,
function(response)
{
console.log(response);
}
});

jQuery AJAX - POST data to IMG tag

file.php
<?php
$variable = 'mainImage';
?>
<div>
<img src="image.php">
</div>
<input type="button" onClick="">
I am trying to do the following:
When the button is clicked $variable should be passed to image.php and the image should reload accordingly.
Yes, i know we can update the src to image.php?variable=mainImage. ( $_GET )
But is it possible to send $variable through $_POST without refreshing the page, but refreshing only the image?
You can probably accomplish this using data URIs to get something like:
// Instead of simply storing the URL as the src attribute,
// execute the post and shove the data into a data URL
$.post('image.php', {variable: 'value'}, function(data) {
image.src = "data:image/jpeg;base64," + data;
});
There might also be some useful information in the minimal image transport section of the ajaxTransport documentation about how to more tightly integrate such functionality.
Sure, you can use jQuery to accomplish this. I suggest giving your image an id before doing this, this way we can select that particular image and grab the source, so do this.
<img id="main-image" src="image.php">
$(function(){
var main_image = $('#main-image');
var url = main_image.attr('src');
$.post( url, { variable: '<?php echo $mainImage ?>' }, function( data ){
main_image.attr('src', data);
})
});

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