I want to upload an image without refreshing page. please help me for this purpose. I find many thing but ever
Complete Script :
you need ajax to do it and here some code to work for u :
ajaximage.php
Contains PHP code.
This script helps you to upload images into uploads folder.
Image file name rename into timestamp+session_id.extention
<?php
include('db.php');
session_start();
$session_id='1'; // User session id
$path = "uploads/";
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") {
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name)) {
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats)) {
if($size<(1024*1024)) // Image size max 1 MB
{
$actual_image_name = time().$session_id.".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name)) {
mysql_query("UPDATE users SET profile_image='$actual_image_name' WHERE uid='$session_id'");
echo "<img src='uploads/".$actual_image_name."' class='preview'>";
}
else
echo "failed";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
}
else
echo "Please select image..!";
exit;
}
?>
index.php
Contains simple PHP and HTML code.
Here $session_id=1 means user id session value.
<?php
include('db.php');
session_start();
$session_id='1'; // User login session value
?>
<form id="imageform" method="post" enctype="multipart/form-data" action='ajaximage.php'>
Upload image <input type="file" name="photoimg" id="photoimg" />
</form>
<div id='preview'>
</div>
Sample database design for Users.
Users
Contains user details username, password, email, profile_image and profile_image_small etc.
CREATE TABLE `users` (
`uid` int(11) AUTO_INCREMENT PRIMARY KEY,
`username` varchar(255) UNIQUE KEY,
`password` varchar(100),
`email` varchar(255) UNIQUE KEY,
`profile_image` varchar(200),
`profile_image_small` varchar(200),
)
Javascript Code
$("#photoimg").on('change',function(){})
// photoimg is the ID name of INPUT FILE tag and
$('#imageform').ajaxForm()
//imageform is the ID name of FORM. While changing INPUT it calls FORM submit without refreshing page using ajaxForm() method.
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#photoimg').on('change', function()
{
$("#preview").html('');
$("#preview").html('<img src="loader.gif" alt="Uploading...."/>');
$("#imageform").ajaxForm(
{
target: '#preview'
}).submit();
});
});
</script>
Uploading files to the server without a page refresh requires some additional client-side tools. These tools will then need to communicate with the PHP backend that you have written. Here are some popular solutions which offer what you are looking for:
Uploadify, my favorite of these solutions: http://www.uploadify.com/
SWFUpload, similar to Uploadify: http://swfupload.org/
jQuery Form Plugin, an AJAX-based uploader: http://jquery.malsup.com/form/#file-upload
Hope that helps.
Two good tutorials:
http://www.9lessons.info/2011/08/ajax-image-upload-without-refreshing.html
http://css-tricks.com/6522-ajax-image-uploading/
You need to use ajax to do that. Ajax will send the request to a PHP script that will do the work without refreshing the entire page.
Submit it via XMLHttpRequest. In a nutshell you would need to initialise a FormData() object and append your file to the object, then initiate an xhr connection, and send your object via xhr xhr.send.
This is all at a very basic level...
Or, better yet, use a pre-existing tool.
Lot of jquery plug ins are available, you can show progress bar too. refer this
http://www.phpletter.com/Demo/AjaxFileUpload-Demo/
Related
I use WordPress on my local server.
To perform a redirect after a user has completed the contact form with the Plugin Contact Form 7 I want him to be redirected to a specific page.
I tried a plugin that I found but it doesn't work and the site crashes.
I would like that:
user goes to page with ID 2. Once the contact form has been completed, clicking send will call the file home-it.js.
User goes to page with ID 96. Once the contact form has been filled in, clicking on send will call the file home-de.js
etc.
I tried this PHP code but it didn't work:
$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if (strpos($url,'2') !== false) {
?> <script type="text/javascript" src="home-it.js"></script> <?php
} elseif (strpos($url,'124') !== false) {
?> <script> type="text/javascript" src"home-fr.js"></script> <?php
} elseif (strpos($url,'96') !== false) {
?> <script type="text/javascript" src="home-de.js"></script> <?php
} elseif (strpos($url,'82') !== false) {
?> <script type="text/javascript" src="home-en.js"></script> <?php
}
If I put the JS file on the page it works perfectly.
But the hoh system recognizes the page ID.
Can you help me?
Thanks so much,
Pascal
Contact Form 7 provides several types of custom DOM events. You can utilize the events within your JavaScript code to run a function in a specific situation.
In your case, you may want to try the wpcf7submit custom DOM event:
var wpcf7Elm = document.querySelector( '.wpcf7' );
wpcf7Elm.addEventListener( 'wpcf7submit', function( event ) {
alert( "Fire!" );
}, false );
For more information about CF7 events:
https://contactform7.com/dom-events/
Also, about your code - it's not a good practice to search for the ID in the URL:
Consider a very probable situation when you have pages with ids 96 and 196 your code will run for both because you are searching for 96
An alternative could be using the native WordPress function get_the_ID() to retrieve the ID of the current item (See here: https://developer.wordpress.org/reference/functions/get_the_id/)
Maybe try:
<?php
$post_id = get_the_ID();
if ($post_id == 2) {
?> <script type="text/javascript" src="home-it.js"></script> <?php
} elseif { ... }
?>
Thanks for the reply.
Who has set me wordpress and apache has something wrong and now no longer recognizes the IDs.
Meaning: if I use your formula or tell wordpress to use permalinks it doesn't work.
For this I need to be able to parse the link and redirect accordingly
Code is below.... I have dropdown menu - that is using PHP to query SQL, in order to populate the dropdown menu options, which is working fine.
You will see below - the sql query is statically configured, I would like to make this more dynamic.
Ideally id like another drop down menu on the same page with statically configured country options, and then when the customer selects which country my PHP script updates with the country in the sql query that php is using....
So for example where in my script below it says;
WHERE country ='SE'
I want it to populate with which ever country the user has selected in the pull down menu, so it could be 'FR', 'DE' or whatever country code has been selected.
I suspect this may be javascript? or maybe php can do this...?
I'm very much a novice level - so if you can be of assistance as much detail, or script as possible please :)
<html>
<body>
<form name="search" action="\cgi-bin\eu.py" method="get">
<?php
require_once 'db.inc.php';
$mysqli = new mysqli(DB_HOST,DB_USER,DB_PASS,DB_NAME);
$sqlSelect="SELECT * FROM clnts WHERE country ='SE' ORDER BY clnt_name";
$result = $mysqli -> query ($sqlSelect);
if(mysqli_num_rows($result)){
$select= '<select name="select">';
while($rs=mysqli_fetch_array($result)){
$select.='<option value="'.$rs['mgmt_ip'].'">'.$rs['clnt_name'].'</option>';
}
}
$select.='</select>';
echo $select;
?>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
You can POST the selected dropdown value to the same page. You can do this automatically by using an 'onChange()' event on the dropdown menu.
Use this to POST to the same page and then get the value for the selected option and use that in your query...
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
add this at the top of you PHP....
if(isset($_POST['select']))
{
$selected_country_var = " country = '" . $_POST['select'] . "' ";
}else
{
$selected_country_var = " ";
}
edit your query to ...
$sqlSelect="SELECT * FROM clnts WHERE" . $selected_country_var . " ORDER BY clnt_name";
now edit your option/dropdown to have the onChnange event...
<select name="select" onchange="this.form.submit()">';
Let me know if I should clarify or if you need additional functionality.
It's usually not a "clean" solution to put together both server and client side code on the same page.
It's actually a better practice to put the server code on a seprate file for example 'handler.php' or 'api.php' and then call it using XMLHttpRequest (more commonly known as AJAX) ...
then, when using ajax you can pass data to the server using POST or GET variables and have it process the data.
that way you can create client side which is more fluent, and communication between the server and the client will be more "tidy"
in your case if you have say 'handler.php' on the server and use jquery ajax you could do something like :
client.html
$.ajax({
url : 'path_to_handler.php',
method : 'POST',
data : { countryCode : 'IL', otherVar : 1 },
onSuccess : function(result){
// do whatever with the data
}
});
and on the server
handler.php
if( isset($_POST['contryCode']) ){
// query the db and have the result returned as json
echo json_encode($result_query);
}
I understand that for a login / register system to work within Phonegap, you have to use aJax with your php. I've got a sucessful php login and register page working but I'm unsure where to begin with jQuery / aJax a.k.a where I'm meant to put it, and what exactly I should be putting in. I was wondering if someone would know how to point me into the right direction.
jQuery
jQuery is a framework built on Javascript. Javascript is a client-side (browser) language . It runs on your device, unlike PHP that gets executed on the server.
You need to include jQuery in the HTML of your login page using script tags:
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
jQuery provides a way to target any html element within your document and perform certain functions on that element. You specify what element by using the following syntax:
$(element).doSomething();
You can select classes or IDs:
<p id="myparagraph">A paragraph of text</p>
<p class="myparagraphclass">A paragraph of text</p>
$('#myparagraph').doSomething();
$('.myparagraphclass').doSomething();
AJAX
AJAX is a method introduced with Javascript that allows a page to request another url along with the result of that request. You will need to use AJAX login with Cordova/Phonegap because the "app" you're building is based on Javascript.
Thankfully, jQuery provides some really nice and easy to use AJAX methods.
Putting it together
I notice from a previous question that you have already created a PHP script that checks the login credentials are correct. Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given in /public_html/access/login.php on line 15
I have edited slightly the code within that question (/access/login.php):
require_once($_SERVER['DOCUMENT_ROOT'] . "/html5up-aerial/access/functions.php");
$username = trim($_POST['username']);
$password = trim($_POST['password']);
if ($username&&$password) {
session_start();
require_once($_SERVER['DOCUMENT ROOT'] . "db_connect.php");
mysqli_select_db($db_server, $db_database) or
die("Couldn't find db");
$username = clean_string($db_server, $username);
$password = clean_string($db_server, $password);
$query = "SELECT * FROM users WHERE username='$username'";
$result = mysqli_query($db_server, $query);
*if($row = mysqli_fetch_array($result)){*
$db_username = $row['username'];
$db_password = $row['password'];
if($username==$db_username&&salt($password)==$db_password){
$_SESSION['username']=$username;
$_SESSION['logged']="logged";
//header('Location: home.php'); // Have commented this out
$message = "YOU ARE NOW LOGGED IN!"; // <- ADDED THIS
}else{
$message = "<h1>Incorrect password!</h1>";
}
}else{
$message = "<h1>That user does not exist!</h1>" .
"Please <a href='index.php'>try again</a>";
}
mysqli_free_result($result);
require_once("db_close.php");
}else{
$message = "<h1>Please enter a valid username/password</h1>";
}
//header/footer only required if submitting to a seperate page
echo $message; // ADDED THIS
die(); // ADDED THIS
This will be the PHP script that AJAX requests.
Now we create the HTML document with a login form and include jQuery and write our ajax code:
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
<form class="login-form" method="post">
Username: <input name="username" /><br />
Password: <input name="password" type="password" /><br />
<input type="submit" value="Login" />
</form>
<script>
$('.login-form').on('submit', function(e) { // Listen for submit
e.preventDefault(); // Don't actually submit the form
var data = $(this); // Put the form in a variable
$.ajax({
type: "POST",
url: '/access/login.php',
data: $(data).serialize(), // Make form data into correct format
success: function(response) {
alert(response); // Alert with the response from /access/login.php
}
});
});
</script>
To debug this code you will need to use Chrome development toolbar or Firefox Firebug. Hope this helps.
Here's what I'm trying to achieve: I want to redirect the user if any errors I check for are found to a html/php form (that the user see's first where inputs are previously created) with custom error messages.
Details: The User see's the HTML/PHP form first where they enter names in a csv format. After they click create, the names are processed in another file of just php where the names are checked for errors and other such things. If an error is found I want the User to be redirected to the HTML/PHP form where they can fix the errors and whatever corresponding error messages are displayed. Once they fix the names the User can click the 'create user' button and processed again (without errors hopefully) and upon completion, redirect user to a page where names and such things are displayed. The redirect happens after the headers are sent. From what I've read this isn't the best thing but, for now, it'll do for me.
Code For HTML/PHP form:
<!DOCTYPE HTML>
<HTML>
<head>
<title>PHP FORM</title>
</head>
<body>
<form method="post" action="processForm.php">
Name: <input type="text" name="names" required = "required"><br>
<input type="submit" value="Create Users" onclick="formInputNames"><br>
Activate: <input type="checkbox" name="activate">
</form>
<?php
// include 'processForm.php';
// errorCheck($fullname,$nameSplit,$formInputNames);
?>
</body>
</html>
I tried messing around with 'include' but it doesn't seem to do anything, however, I kept it here to help illustrate what I'm trying to achieve.
Code For Process:
$formInputNames = $_POST['names'];
$active = (isset($_POST['activate'])) ? $_POST['activate'] : false;
//checks if activate checkbox is being used
$email = '#grabby.com';
echo "<br>";
echo "<br>";
$fullnames = explode(", ", $_POST['names']);
if ($active == true) {
$active = '1';
//sets activate checkbox to '1' if it has been selected
}
/*----------------------Function to Insert User---------------------------*/
A Function is here to place names and other fields in database.
/*-------------------------End Function to Insert User--------------------*/
/*-----------------------Function for Errors---------------------*/
function errorCheck($fullname,$nameSplit,$formInputNames){
if ($formInputNames == empty($fullname)){
echo 'Error: Name Missing Here: '.$fullname.'<br><br>';
redirect('form.php');
}
elseif ($formInputNames == empty($nameSplit[0])) {
echo 'Error: First Name Missing in: '.$fullname.'<br><br>';
redirect('form.php');
}
elseif ($formInputNames == empty($nameSplit[1])) {
echo 'Error: Last Name Missing in: '.$fullname.'<br><br>';
redirect('form.php');
}
elseif (preg_match('/[^A-Za-z, ]/', $fullname)) {
echo 'Error: Found Illegal Character in: '.$fullname.'<br><br>';
redirect('form.php');
}
}
/*-----------------------------End Function for Errors------------------------*/
/*--------------------------Function for Redirect-------------------------*/
function redirect($url){
$string = '<script type="text/javascript">';
$string .= 'window.location = "' .$url. '"';
$string .= '</script>';
echo $string;
}
/*-------------------------End Function for Redirect-----------------------*/
// Connect to database
I connect to the database here
foreach ($fullnames as $fullname) {
$nameSplit = explode(" ", $fullname);
//opens the database
I Open the database here
errorCheck($fullname,$nameSplit,$formInputNames);
$firstName = $nameSplit[0];//sets first part of name to first name
$lastName = $nameSplit[1];//sets second part of name to last name
$emailUser = $nameSplit[0].$email;//sets first part and adds email extension
newUser($firstName,$lastName,$emailUser,$active,$conn);
redirect('viewAll.php');
//echo '<META HTTP-EQUIV="Refresh" Content="0; URL=viewAll.php">';
//if you try this code out, you can see my redirect to viewAll doesn't work when errors are found...I would appreciate help fixing this as well. My immediate fix is using the line under it but I don't like it.
}
Any help is certainly appreciated.Thank You
Also it's worth noting I'm new to php. I would like to have an answer in php as well (if possible).
There's multiple ways of doing so. I personally would use AJAX. On a 'form submit', run a javascript function calling an AJAX request to a .php file to check the form information, all using post method. Calculate all the $_POST['variables'] checking for your defined errors. You would have an html element print the errors via AJAX request.
If there are 0 errors then in the request back return a string as so that your javascript function can look for if its ready to go. If ready to go, redirect the user to where ever you please.
AJAX is not hard and I only suggested the idea sense you put javascript in your tags.
Another method:
Having all your code on one .php file. When you submit the form to the same .php file check for the errors (at the top of the file). If $_POST['variables'] exist, which they do after you submit the form, you echo your errors in the needed places. If zero errors then you redirect the page.
I don't know if this is possible so I'm very open to trying other methods to achieve similar results.
Basically I have a website and a certain div
<div id="mainContent">Content here...</div>
What I want to do with this, is be able to send an email to a certain address or something similar and the body of the email will define the "innerHTML" of this div.
I can imagine it would look something like this in Javascript:
document.getElementbyId("mainConetent").innerHTML = emailBody;
With obviously "emailBody" being a pre-defined variable.
I am almost certain nothing like this could work but is there any way to achieve a similar thing?
I also know that 'innerHTML' in javascript becomes restored when a page is refreshed. I would like it to be there permenantly on the original document, until a new email is recieved with the new content. This method with javascript is probably not the way to do is. I just used it to explain bettter
Store email body in input hidden field and then using javascript you can retrieve them based on id and store them in respective div.Try this:
html:
<div id="mainContent">Content here...</div>
<input type="hidden" value="<?php echo $inputbody;?>" id="emailbody">
javascript:
var emailBody = document.getElementbyId("emailbody").value;
document.getElementbyId("mainContent").innerHTML = emailBody;
Updated Example:
<?php
$to = "someone#example.com";
$subject = "Test mail";
$inputbody = "Hello! This is a simple email message."; // insert this into hidden field
$from = "someonelse#example.com";
$headers = "From:" . $from;
?>
In your index.php file add the following piece of code for database connection
<?php
// Create connection
$con=mysqli_connect("localhost","username","password","db_name");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_fetch_array(mysqli_query($con,"SELECT * FROM table_name Where type='mail'"));
//Inside your mainContent div
<div id="mainContent"><?php echo $result['innerhtml'] ?></div>
?>
In your js file
If your email is being sent on button click perform this
$('#button').on('click',function(){
emailBody = document.getElementbyId("mainConetent").innerHTML;
$.ajax({
type: "POST",
url: "update_mail content.php",
data: "emailBody="+ emailBody,
success: function(){
}
});
})
//Updates the content in the databse table usinganother php file named update_mail content.php .This flow might help u mate.. :)