I'm working on converting a jQuery ajax request into plain JavaScript just so I know how to do it both ways. What I'm trying to do is pass a JSON object from my PHP script into my JavaScript file and display the values of the JSON object on the page.
I'm just beginning to dive into AJAX and I've gotten the jQuery version to work on my own easily enough, but I'm having difficult with the plain JavaScript version. For the plain JavaScript part, I'm following along with a JavaScript book that I have. That's why the code structure may seem different.
Also, I'm aware there are no real security implementations and that is fine. This is just for my own learning purposes.
Here is the HTML:
<body>
<h3>Grab the location of a person in the database below</h3>
<form action="ajax/name.php" method="POST" name="ajaxForm" id="ajaxForm">
<label for="name">Name: </label>
<input type="text" id="name" name="name">
<input type="submit" id="name-submit" name="name-submit" value="Grab">
</form>
<div id="results">
<label for="location">Location: </label>
<input type="text" name="name-data" id="name-data" disabled>
</div>
<div id="insert">
<h3>Insert a new person with a new location below</h3>
<form action="ajax/name.php" method="POST" name="insForm" id="insForm">
<label for="name">Name: </label>
<input type="text" name="ins-name" id="ins-name">
<label for="location">Location: </label>
<input type="text" name="ins-location" id="ins-location">
<input type="submit" id="ins-submit" name="ins-submit" value="Insert">
</form>
<div id="insresults_name"></div>
<div id="insresults_loc"></div>
</div>
<script src="js/ajax.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="js/global.js"></script>
</body>
Here is my jQuery code that works fine:
$('document').ready(function() {
var locForm = $('#ajaxForm');
var insForm = $('#insForm');
locForm.submit(function() {
$.ajax({
type: 'POST',
url: locForm.attr('action'),
data: locForm.serialize(),
success: function (response) {
$('#name-data').val(response);
}
});
return false;
});
insForm.submit(function() {
$.ajax({
type: 'POST',
url: insForm.attr('action'),
data: insForm.serialize(),
dataType: 'json',
success: function (response) {
$('#insresults_name').text('Name: ' + response[0]);
$('#insresults_loc').text('Location: ' + response[1]);
}
});
return false;
});
});
Here is my PHP Script:
<?php
if (isset($_POST['name'])) {
require '../db/connect.php';
$conn = new Con();
$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
$stmt = $conn->prepare('SELECT * FROM names WHERE name=:name');
$stmt->bindParam(':name', $name);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
echo (isset($result['location'])) ? $result['location'] : 'That name isn\'t listed';
}
if (isset($_POST['ins-name']) && isset($_POST['ins-location'])) {
require '../db/connect.php';
$conn = new Con();
$name = filter_input(INPUT_POST, 'ins-name', FILTER_SANITIZE_STRING);
$loc = filter_input(INPUT_POST, 'ins-location', FILTER_SANITIZE_STRING);
$stmt = $conn->prepare('INSERT INTO names (name, location) VALUES (:name, :loc)');
$stmt->bindParam(':name', $name);
$stmt->bindParam(':loc', $loc);
try {
$stmt->execute();
$result = $stmt->rowCount();
if ($result) {
$stmt = $conn->prepare('SELECT * FROM names WHERE name=:name');
$stmt->bindParam(':name', $name);
$stmt->execute();
$res = $stmt->fetch(PDO::FETCH_ASSOC);
$val = array();
$val[0] = $res['name'];
$val[1] = $res['location'];
echo json_encode($val);
} else {
echo 'Fail';
}
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage() . '';
}
}
?>
And here is the plain JavaScript that I've come up with, but doesn't work:
function getData() {
'use strict';
var name = document.getElementById('ins-name').value();
var location = document.getElementById('ins-location').value();
var url = document.getElementById('ins-name').getAttribute('action');
if ((name.length > 0) && (location.length > 0)) {
var ajax = getXMLHttpRequestObject();
ajax.ononreadystatechange = function () {
if (ajax.readyState == 4) {
// Check the status code:
if ((ajax.status >= 200 && ajax.status < 300) || (ajax.status == 304)) {
// if ajax.responseText isn't empty
if (ajax.responseText) {
var arr = Array();
arr = JSON.parse(responseText);
document.getElementById('insresults_name').innerHTML('Name: ' + arr[0]);
document.getElementById('insresults_loc').innerHTML('Location: ' + arr[1]);
} else {
alert('Something went wrong!');
}
} else {
alert('Bad Status Code!');
}
}
};
ajax.open('POST', '../ajax/name.php', true);
ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
var data = 'name=' + encodeURIComponent(name) + 'location=' + encodeURIComponent(location);
ajax.send(data);
return false;
} else {
alert('Please complete the form!');
}
}
function init() {
'use strict';
if (document && document.getElementById) {
var form = document.getElementById('insForm');
form.onsubmit = getData;
}
}
window.onload(init);
Related
Is there any way to send data from php to html without refreshing page.
i open html to upload images..
so i will go to process.php and i got target-path of that images when it has success uploaded.
my problem is. how can i send that target-path to my html back without refreshing page.
This is my javascript:
function startUpload(){
..
return true;
}
function stopUpload(success){
var result = '';
if (success == 1){
.. //get data from php
} else {
..
}
return true;
}
process.php
$destination_path = "../dir/";
$result = 0;
$target_path = $destination_path . basename( $_FILES['myfile']['name']);
if(#move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) {
$result = 1;
//$target-path need to send to input in html
}
sleep(1);
My suggestion would be ajax. It's cleaner and efficient.
Example is how you parse the data
This is for HTML to PHP
$('#submit').click(function()
{
$.ajax({
url: send_email.php,
type:'POST',
data:
{
email: email_address,
message: message
},
success: function(msg)
{
alert('Email Sent');
}
});
});
If you want to pass a value from PHP to HTML
An example would be :
<?php
if( isset($_GET['submit']) )
{
//be sure to validate and clean your variables
$val1 = htmlentities($_GET['val1']);
$val2 = htmlentities($_GET['val2']);
//then you can use them in a PHP function.
$result = myFunction($val1, $val2);
}
?>
<?php if( isset($result) ) echo $result; //print the result above the form ?>
<form action="" method="get">
Inserisci number1:
<input type="text" name="val1" id="val1"></input>
<?php echo "ciaoooo"; ?>
<br></br>
Inserisci number2:
<input type="text" name="val2" id="val2"></input>
<br></br>
<input type="submit" name="submit" value="send"></input>
</form>
In your case it would be :
$destination_path = "../dir/";
$result = 0;
$target_path = $destination_path . basename( $_FILES['myfile']['name']);
if(#move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) {
$result = 1;
$val1 = htmlentities($_GET['val1']); // this value could be obtain via HTML
}
sleep(1);
If your Javascript will handle upload event through AJAX. you can return back correct image url and append back to your webpage.
Try this before add jquery to your html page:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
Html Form:
<span id="returnImage"></span>
<form id="uploadImage">
<label id="img">Upload Image<label>
<input name="images" type="file" class="img"/>
<input type="submit"/>
</form>
JS:
$("#uploadImage").submit(function(e){
e.preventDefault();
var data = new FormData();
$.each($('.img'), function(i, obj) {
$.each(obj.files,function(j, file){
data.append('upload_files['+i+']', file);
});
});
$.ajax({
type: 'post',
data: data,
url: "image_processor.php",
cache: false,
contentType: false,
processData: false,
success: function(data){
var dataArray = $.parseJSON(data);
$("#returnImage").html('<img src="'+dataArray["img"]+'"/>')
});
});
});
image_processor.php
<?php
$array_add_counter = 0;
foreach ($_FILES['upload_files']['name'] as $imageNameArray){
$NewImage[$array_add_counter]['name'] = $imageNameArray;
$array_add_counter++;
}
$array_add_counter = 0;
foreach ($_FILES['upload_files']['type'] as $imageTypeArray){
$NewImage[$array_add_counter]['type'] = $imageTypeArray;
$array_add_counter++;
}
$array_add_counter = 0;
foreach ($_FILES['upload_files']['tmp_name'] as $imageTmpArray){
$NewImage[$array_add_counter]['tmp_name'] = $imageTmpArray;
$array_add_counter++;
}
$array_add_counter = 0;
foreach ($_FILES['upload_files']['error'] as $imageErrorArray){
$NewImage[$array_add_counter]['error'] = $imageErrorArray;
$array_add_counter++;
}
$array_add_counter = 0;
foreach ($_FILES['upload_files']['size'] as $imageSizeArray){
$NewImage[$array_add_counter]['size'] = $imageSizeArray;
$array_add_counter++;
}
foreach ($NewImage as $images) {
move_uploaded_file($images["tmp_name"], "ImageLocation/".$images["name"]);
$return['img'] = "ImageLocation/".$images["name"];
}
echo json_encode($return);
?>
I tested and it work in my localhost.
I have a website using the Kohana framework. I have a problem when I tried upload multiple image using AJAX. I tried with many methods but without success. I think the problem is in function _save_images($image) at line:
if ($file = Upload::save($image, NULL, $directory))
Because I tried echo this values but receive result like:
Website not support width less than 900px on Computer
A function to save image with parameter $image is array list image.
In ProductImage.php:
protected function _save_images($image)
{
$directory = DOCROOT.'uploads/';
if ($file = Upload::save($image, NULL, $directory))
{
$filename = strtolower(Text::random('alnum', 20)).'.jpg';
Image::factory($file)
->resize(200, 200, Image::AUTO)
->save($directory.$filename);
// Delete the temporary file
unlink($file);
return $filename;
}
}
And I have a function to upload multiple image.
public function action_create()
{
$user = Auth_Jelly::instance()->get_user();
$iduser = $user->id;
if($user->has_role('admin') || $user->check_permission($iduser,'CREATE_PRODUCT')==1){
$this->auto_render = false;
if(Request::$is_ajax)
{
$name_img = Security::xss_clean($_POST['name_img']);
$type_img = Security::xss_clean($_POST['type_img']);
$size_img = Security::xss_clean($_POST['size_img']);
$new_array = array();
foreach($name_img as $item){
$new_array['name'][] = $item;
}
foreach($type_img as $item){
$new_array['type'][] = $item;
}
foreach($size_img as $item){
$new_array['size'][] = $item;
}
$files = $new_array;
unset($new_array);
$ilosc = count($files['name'])-1;
for($i=0; $i<=$ilosc; $i++) {
$_FILES['image_list'.$i]['name'] = $files['name'][$i];
$_FILES['image_list'.$i]['type'] = $files['type'][$i];
$_FILES['image_list'.$i]['size'] = $files['size'][$i];
$array_new[] = array(
'name'=>$_FILES['image_list'.$i]['name'],
'type'=>$_FILES['image_list'.$i]['type'],
'error'=>0,
'size'=>$_FILES['image_list'.$i]['size'],
);
}
foreach ($array_new as $key => $value) {
$this->_save_images($value);
if($this->save_images($value)==FALSE){
echo "Faild Upload";
}else{
echo "Upload Success";
}
}
}
}else{
// Request::current()->redirect('admin/home/denied');
}
}
And in ProductImage.js:
$("#"+form).click(function(){
var image_list = Array();
var imageFiles = document.getElementById("image_list"),
filesLength = imageFiles.files.length;
for (var i = 0; i < filesLength; i++) {
image_list[i] = imageFiles.files[i].name;
}
var myFileList = document.getElementById('image_list').files;
var file ;
var name_img= Array();
var type_img= Array();
var size_img= Array();
// loop through files
for (var i = 0; i < myFileList.length; i++) {
// get item
file = myFileList.item(i);
//or
file = myFileList[i];
name_img[i]= file.name;
type_img[i]= file.type;
size_img[i]= file.size;
}
var local = window.location;
var val_content = tinyMCE.editors[0].getContent();
var language = $.trim($('#product-create-language option:selected').val());
var category = $.trim($('input[name=category]').val());
var status = $.trim($('input[name=createstatus]:checked').val());
var position = $.trim($('input[name=createposition]:checked').val());
var matches = [];
$(".addcheck:checked").each(function() {
matches.push(this.value);
});
if(matches.length>0)
matches=matches;
else
matches=null;
if(validateSpace(title,"<img src='"+base_url+"themes/admin/images/false.png' alt='false'>",titleinfo) && validateSpace(image,"<img src='"+base_url+"themes/admin/images/false.png' alt='false'>",imageinfo) && validateSpace(imagebig,"<img src='"+base_url+"themes/admin/images/false.png' alt='false'>",imagebiginfo) && validateSpace(imagemobile,"<img src='"+base_url+"themes/admin/images/false.png' alt='false'>",imagemobileinfo) && validateSpace(keywords,"<img src='"+base_url+"themes/admin/images/false.png' alt='false'>",keywordsinfo) && validateSpace(description,"<img src='"+base_url+"themes/admin/images/false.png' alt='false'>",descriptioninfo) && validateSpace(date,"<img src='"+base_url+"themes/admin/images/false.png' alt='false'>",dateinfo)){
var data = {name_img:name_img,type_img:type_img,size_img:size_img,category:category,mycolor: matches,language:language,title:$("#"+title).val(),image:$("#"+image).val(),imagebig:$("#"+imagebig).val(),imagemobile:$("#"+imagemobile).val(),fileupload:$("#"+fileupload).val(),price:$("#"+price).val(),pricesale:$("#"+pricesale).val(),idproduct:$("#"+idproduct).val(),color:$("#"+color).val(),packing:$("#"+packing).val(),cbmpsc:$("#"+cbmpsc).val(),size:$("#"+size).val(),container:$("#"+container).val(),excerpt:$("#"+excerpt).val(),content:val_content,keywords:$("#"+keywords).val(),description:$("#"+description).val(),date:$("#"+date).val(),status:status,position:position};
$(".product-content-create-total").fadeOut(); // hidden div content field register // children div of div class //register-form-center\\
$(".product-content-create").css("height","auto"); // set height/auto after hidden div class //register-form-center\\
$(".product-content-create-alert").html(""); // remove text div alert register // parent div of div id //register-form-content\\
$(".product-content-create-alert").css("margin-bottom","25px");
$(".product-content-create-alert").fadeIn("slow");
$(".product-content-create-alert").html('<img src="'+base_url+'themes/admin/images/loader.gif" alt="loader">');
$.ajax({
url: admin_url +"product/create",
type: "POST",
data: data,
cache: false,
success: function(html) {
console.log(html);
}
});
}else{
return false;
}
});
});
That seem many code, so, I hope anyone can be help me.
Updated:
Here my code of form include submit button:
<form enctype="multipart/form-data" name="form-product-create" method="post">
<input type="file" id="image_list" name="image_list[]" multiple>
<input type="button" name="btnproductcreateclick" value=" " id="btn-product-create-click" style="margin-left:119px;" class="form-btn-create-click" />
</form>
HTML
<form enctype="multipart/form-data" action="upload.php" method="post">
<input name="file[]" type="file" />
<button class="add_more">Add More Files</button>
<input type="button" value="Upload File" id="upload"/>
</form>
Javascript
$(document).ready(function(){
$('.add_more').click(function(e){
e.preventDefault();
$(this).before("<input name='file[]' type='file'/>");
});
});
PHP
for($i=0; $i<count($_FILES['file']['name']); $i++){
$target_path = "uploads/";
$ext = explode('.', basename( $_FILES['file']['name'][$i]));
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1];
if(move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
echo "The file has been uploaded successfully <br />";
} else{
echo "There was an error uploading the file, please try again! <br />";
}
}
Ajax
$('body').on('click', '#upload', function(e){
e.preventDefault();
var formData = new FormData($(this).parents('form')[0]);
$.ajax({
url: 'upload.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
success: function (data) {
alert("Data Uploaded: "+data);
},
data: formData,
cache: false,
contentType: false,
processData: false
});
return false;
})
Source : How to upload multiple files using PHP, jQuery and AJAX
In your code error looks like near,
foreach ($array_new as $key => $value) {
$this->_save_images($value);
if($this->save_images($value)==FALSE){
echo "Faild Upload";
}else{
echo "Upload Success";
}
}
when you call $this->_save_images($value); you don't save file name for uploaded image. $file_name = $this->_save_images($value); and than save this $file_name,
foreach ($array_new as $key => $value) {
$file_name= $this->_save_images($value);
if($this->save_images($file_name)==FALSE){
echo "Faild Upload";
}else{
echo "Upload Success";
}
}
HTML form must be have the “method” attribute with the “post” value. Because the file will only send to the server when the value of the method attribute of the form is post.
<form method="post" name="multiple_upload_form" id="multiple_upload_form" enctype="multipart/form-data" action="upload.php">
<input type="hidden" name="image_form_submit" value="1"/>
<label>Choose Image</label>
<input type="file" name="images[]" id="images" multiple >
<div class="uploading none">
<label> </label>
<img src="uploading.gif"/>
</div>
</form>
PHP
Demo
Hey So I have an issue with my code where I am trying to filter the data coming from the database and display it in a table. I am using AJAX to send the request to the PHP page. I have not had any luck in searching for a solution. (It will be similar to your common real estate website, or retail, etc. where the user can input a location in the search box, search for it, and then filter the displayed data using the 2 dropdown menus).
My index.php page has 3 inputs (a textbox and 2 dropdowns)
<form action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" class="searchForm" id="search" placeholder="Stuff" autocomplete="off">
<div id="here"></div>
<select class="orderType" name="type" id="orderByType" data-toggle="dropdown" onchange="displaySelection(this.value)">
<option value="" selected>--------</option>
<option value="dropdown1" selected>Dropdown1</option>
<option value="dropdown1" selected>Dropdown1</option>
</select>
<select class="order" name="order" id="orderBy" data-toggle="dropdown">
<option value="" selected>--------</option>
<option value="lowest">Lowest</option>
<option value="highest">Highest</option>
</select>
</form>
<div id="searchTable">
Then my ajax calls on the index.php page (The AJAX will be another question later, as I'm sure there is a better way than what I have, to send the data)
function fill(Value)
{
$('#search').val(Value);
$('#here').hide();
}
$(document).ready(function(){
$("#search").keyup(function(){
var x = $('#search').val();
if(x==""){
$("#here").html("");
$('#searchTable').html("");
}
else{
$.ajax({
type:'POST',
url:'test.php',
data:'q='+x,
success:function(html){
$("#here").html(html).show();
}
});
}
});
$('.searchForm').change(function(){
var type = $('#search').val();
var city = $('#city').text();
$.ajax({
type: 'POST',
url: 'test.php',
data: { search : type, city : city },
success: function(response){
$("#searchTable").html(response);
$('#search').live("keypress",function(e){
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13){
e.preventDefault();
e.stopPropagation();
$('#searchTable').show();
}
});
}
});
});
$('.orderClass').change(function(){
var order = $('#orderBy').val();
var city = $('#city').text();
$.ajax({
type: 'POST',
url: 'test.php',
data: { orderBy : order, city : city },
success: function(response){
$("#searchTable").html(response);
}
});
});
$('.orderType').change(function(){
var type = $('#orderByType').val();
var city = $('#city').text();
$.ajax({
type: 'POST',
url: 'test.php',
data: { orderByType : type, city : city},
success: function(response){
$("#searchTable").html(response);
}
});
});
});
And then on test.php
(I can filter the data with the 2 dropdown menus and that will work fine, but i'm not sure how to filter the data that is displayed from the search input box.)
$stmt = "SELECT * FROM places";
if(isset($_POST['search'])){
$search = htmlspecialchars($_POST['search']);
$stmt .= " WHERE name = :search";
}
if(isset($_POST['orderByType'])){
$selection = $_POST['orderByType'];
$stmt .= " AND type = :selection";
}
if(isset($_POST['orderBy'])){
$order = $_POST['orderBy'];
$selection = $_SESSION['id'];
$stmt .= " ORDER BY".$order;
}
$stmt = $conn->prepare($stmt);
$search = "%".$search."%";
$stmt->bindValue(':search', $search, PDO::PARAM_STR);
$stmt->bindParam(":selection", $selection);
if($stmt->rowCount() > 0){
$result = $stmt->fetchAll();
foreach($result as $row){
echo $row['data'];
}
}
//Search input live search
if(!empty($_POST['q'])){
$name = $_POST['q'];
$name = htmlspecialchars($name);
$liveSearch = $conn->prepare("SELECT name, city FROM places WHERE name LIKE :name OR city LIKE :name");
$name = "%".$name."%";
$liveSearch->bindValue(':name', $name, PDO::PARAM_STR);
$result = $liveSearch->fetchAll();
if($liveSearch->rowCount() > 0){
foreach($result as $row){
echo $row['name'];
}
}
else{
echo "No results found";
}
}
(If there is a great system in place that can search using user input and then filter it using dropdown menus, then please let me know)
Thanks in advance.
If I was going to do this, I would probably make an ajax object for reuse reasons and a php object to handle queries:
/defines.php
You may or may not have defines for your db credentials. I use these in the class below.
define("DB_USER",'root');
define("DB_PASS",'password');
define("DB_HOST",'localhost');
define("DB_NAME",'dbname');
/classes/Query.php
This is a stripped-down query engine which makes basic queries. I use it to save on rewriting a bunch of prepares and executes, but you can do whatever you like there.
class Query
{
private static $singleton,
$con;
private $rquery,
$bind;
public function __construct()
{
if(self::$singleton instanceof Query)
return self::$singleton;
self::$singleton = $this;
}
public function connect()
{
if(self::$con instanceof PDO)
return self::$con;
self::$con = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME,DB_USER,DB_PASS);
return self::$con;
}
public function query($sql,$bind = false)
{
$this->bind = false;
try {
if(empty($bind)) {
$this->rquery = $this->connect()->query($sql);
}
else {
foreach($bind as $key => $value) {
$bkey = ":{$key}";
$this->bind[$bkey] = $value;
}
$this->rquery = $this->connect()->prepare($sql);
$this->rquery->execute($this->bind);
}
}
catch (PDOException $e){
die('An application error occurred.');
}
return $this;
}
public function getResults()
{
while($results = $this->rquery->fetch(PDO::FETCH_ASSOC)) {
$row[] = $results;
}
return (!empty($row))? $row : 0;
}
}
/functions/searchPlaces.php
function searchPlaces($search,$type = false,$orderby = false)
{
$sVal = "%".$search."%";
array();
$sql[] = 'SELECT * FROM places WHERE `name` LIKE :0 or `city` LIKE :1';
$bind = array_fill(0,2,$sVal);
if(!empty($type)) {
$bind[] = $type;
$sql[] = 'AND `type` = :2';
}
if(!empty($orderby)) {
$order = ($orderby == 'lowest')? 'ASC' : 'DESC';
$sql[] = "order by `ID` {$order}";
}
// Here is where I use the query to send back results from DB
// you can just use a regular prepare/bind/execute if you like
$qEngine = new Query();
return $qEngine->query(implode(' ',$sql),$bind)->getResults();
}
/test.php
<?php
// Put our db credentials
require_once(__DIR__.'/defines.php');
if(!empty($_POST)) {
// Needs the search function and the query class
// (disregard class if you don't use it)
require_once(__DIR__.'/functions/searchPlaces.php');
require_once(__DIR__.'/classes/Query.php');
// I am just sending an array back, but you can format it as you please
print_r(searchPlaces($_POST['search'],$_POST['type'],$_POST['order']));
exit;
}
/index.php
<script>
// I like to make an ajax engine, it saves on rewriting all the same stuff
// on later ajax calls
var AjaxEngine = function($)
{
this.send = function(data,func)
{
$.ajax({
url: '/test.php',
data: data,
type: 'post',
success: function(response){
func(response);
}
});
return this;
};
}
// You only need one document ready
$(document).ready(function(){
// Make an ajax engine
var Ajax = new AjaxEngine($);
// If form changes or key up in text field
$('.searchForm,.ajaxer>select').on('keyup change',function(e) {
e.preventDefault();
// Serialize the form
var formData = $('.ajaxer').serialize();
// Send the ajax and return results
Ajax.send(formData,function(response) {
$('#searchTable').html(response);
});
});
});
</script>
<!-- Note changes to the form for classes and ids -->
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" class="ajaxer">
<input name="search" type="text" class="searchForm" id="search" placeholder="Stuff" autocomplete="off" />
<div id="here"></div>
<select class="orderType" name="type" data-toggle="dropdown">
<option value="" selected>--------</option>
<option value="dropdown1" selected>Dropdown1</option>
<option value="dropdown1" selected>Dropdown1</option>
</select>
<select class="order" name="order" data-toggle="dropdown">
<option value="" selected>--------</option>
<option value="lowest">Lowest</option>
<option value="highest">Highest</option>
</select>
</form>
<div id="searchTable"></div>
I want to get data from database and change it, all with ajax but when I try to change the input ajax send the same data that was on database.
<script>
function showMore(str) {
var xhttp;
if (str.length == 0) {
document.getElementById("txtMore").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("txtMore").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "getmore.php?q="+str, true);
xhttp.send();
}
</script>
<body>
<div class="content">
<button id="edit">Update</button>
<form action="">
<h3>Last Name:</h3><input type="text" id="txt1" onkeyup="showHint(this.value)">
</form>
<span id="txtMore"></span>
</div>
</body>
<script type="text/javascript">
$('#edit').click(function(){
var ID = $('#id_field').attr('value');
var name_field = $('#FirstName').attr('value');
var last_field = $('#LastName').attr('value');
var telefone_field = $('#Telefone').attr('value');
var email_field = $('#Email').attr('value');
var check = $('#CheckIn').attr('value');
var dataString = 'id=' +ID+ '&FirstName=' +name_field+ '&LastName=' +last_field+ '&Telefone=' +telefone_field+ '&Email=' +email_field+ '&CheckIn=' +check;
alert(dataString);
$.ajax({
type: "GET",
url: "edit_ajax.php",
data: dataString,
cache: false,
success: function(html)
{
$("#txtHint").html('Actualizado');
}
});
});
</script>
And the php file where I get the data from database
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$con = mysqli_connect('localhost','root','root','client_db');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$q = mysqli_real_escape_String($con, $_GET['q']);
mysqli_select_db($con,"client_db");
$sql='SELECT * FROM user WHERE id = "'.$q.'" ';
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
echo'<form method="GET" class="form_user">';
echo'<input type="hidden" name="id" id="id_field" value="'.$row['id'].'" class="inputForm"><br><br>';
echo'Primeiro Nome<br>';
echo'<input type="text" name="FirstName" id="FirstName" value="'.$row['FirstName'].'" class="inputForm"><br><br>';
echo'Ultimo Nome<br>';
echo'<input type="text" name="LastName" id="LastName" value="'.$row['LastName'].'" class="inputForm"><br><br>';
echo'Telefone<br>';
echo'<input type="text" name="Telefone" id="Telefone" value="'.$row['Telefone'].'" class="inputForm"><br><br>';
echo'Email<br>';
echo'<input type="text" name="Email" id="Email" value="'.$row['Email'].'" class="inputForm"><br><br>';
echo'<input type="checkbox" name="Check" id="CheckIn" value="Check">Check-in<br><br>';
echo'</form>';
}
mysqli_close($con);
?>
Thanks.
EDIT: The problem isn't the sql query but the values inside <input> if I change that values javascript read the old values and send them to php.
You're missing an UPDATE request on your DB.
Right now your request only do a SELECT, so no matter what data are sent to your server, you're not using it.
$sql='SELECT * FROM user WHERE id = "'.$q.'" ';
$result = mysqli_query($con,$sql);
You could to something like this :
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$con = mysqli_connect('localhost','root','root','client_db');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$q = mysqli_real_escape_String($con, $_GET['q']);
$Username = $GET['Firstname'];
$Lastname= $_GET['Lastname']
// Do so for every inputs your form will give you
$sql = "UPDATE 'user' SET 'Firstname' = '$Firstname','Lastname' = '$Lastname', etc...";
$result = mysqli_query($con,$sql);
mysqli_close($con);
When I upload image and text by separate form, its work well. But Its not work when I add together.
My form text upload by js and image upload by a php file.
And I think my problem in my form.
If I upload together with js, What change in my js and submit.php, which also add below.
Here is my form code that not work together
<form action="" method="post" id="cmntfrm" enctype="multipart/form-data">
<fieldset id="cmntfs">
<legend class="pyct">
What's your mind
</legend>
<input type="hidden" name="username" size="22" tabindex="1" id="author" value="'.$pname.'"/>
<input type="hidden" name="email" size="22" tabindex="2" id="email" value="'.$email.'"/>
<p><textarea name="comment" rows="10" tabindex="4" id="comment"></textarea></p>
<div id="ajaxuploadfrm">
<form action="uploadpostimg.php" method="post" enctype="multipart/form-data">
<b>Select an image (Maximum 1mb)</b>
<input type="file" name="url" id="url" />
</form>
</div>
<p><input type="submit" name="submit" value="Post comment" tabindex="5" id="submit"/></span></p>
</fieldset>
<input type="hidden" name="parent_id" id="parent_id" value="0" />
<input type="hidden" name="tutid2" id="tutid" value="'.$tutid2.'" />
</form>
js
$(document).ready(function(){
var inputAuthor = $("#author");
var inputComment = $("#comment");
var inputEmail = $("#email");
var inputUrl = $("#url");
var inputTutid = $("#tutid");
var inputparent_id = $("#parent_id");
var commentList = $(".content > comment");
var commentCountList = $("#updatecommentNum");
var error = $("#error");
error.fadeOut();
function updateCommentbox(){
var tutid = inputTutid.attr("value");
//just for the fade effect
commentList.hide();
//send the post to submit.php
$.ajax({
type: "POST", url: "submit.php", data: "action=update&tutid="+ tutid,
complete: function(data){
commentList.prepend(data.responseText);
commentList.fadeIn(2000);
}
});
}
function updateCommentnum(){
var tutid = inputTutid.attr("value");
//just for the fade effect
commentList.hide();
//send the post to submit.php
$.ajax({
type: "POST", url: "submit.php", data: "action=updatenum&tutid="+ tutid,
complete: function(data){
commentCountList.html(data.responseText);
commentList.fadeIn(2000);
}
});
}
function error_message(){
error.fadeIn();
}
function checkForm(){
if(inputAuthor.attr("value") && inputComment.attr("value") && inputEmail.attr("value"))
return true;
else
return false;
}
//on submit event
$("#cmntfrm").submit(function(){
error.fadeOut();
if(checkForm()){
var author = inputAuthor.attr("value");
var url = inputUrl.attr("value");
var email = inputEmail.attr("value");
var comment = inputComment.attr("value");
var parent_id = inputparent_id.attr("value");
var tutid = inputTutid.attr("value");
//we deactivate submit button while sending
$("#submit").attr({ disabled:true, value:"Sending..." });
$("#submit").blur();
//send the post to submit.php
$.ajax({
type: "POST", url: "submit.php", data: "action=insert&author="+ author + "&url="+ url + "&email="+ email + "&comment="+ comment + "&parent_id="+ parent_id + "&tutid="+ tutid,
complete: function(data){
error.fadeOut();
commentList.prepend(data.responseText);
updateCommentbox();
updateCommentnum();
//reactivate the send button
$("#submit").attr({ disabled:false, value:"Submit Comment!" });
$( '#cmntfrm' ).each(function(){
this.reset();
});
}
});
}
else //alert("Please fill all fields!");
error_message();
//we prevent the refresh of the page after submitting the form
return false;
});
});
Submit.php
<?php header('Content-Type: charset=utf-8'); ?>
<?php
include("db.php");
include_once("include/session.php");
switch($_POST['action']){
case "update":
echo updateComment($_POST['tutid']);
break;
case "updatenum":
echo updateNumComment($_POST['tutid']);
break;
case "insert":
date_default_timezone_set('Asia/Dhaka');
echo insertComment($_POST['author'], $_POST['comment'], $_FILES['url']['name'], $_POST['email'], $_POST['tutid'], $_POST['parent_id'], $date = date("M j, y; g:i a"));
break;
}
function updateNumComment($tutid) {
//Detail here
}
function updateComment($tutid) {
//Detail here
}
function insertComment($username, $description, $url, $email, $qazi_id, $parent_id, $date ){
global $dbh;
//Upload image script that not work here when i try together so i took it at separate file and then tried with above form
$output_dir = "comimage/";
$allowedExts = array("jpg", "jpeg", "gif", "png","JPG");
$extension = #end(explode(".", $_FILES["url"]["name"]));
if(isset($_FILES["url"]["name"]))
{
//Filter the file types , if you want.
if ((($_FILES["url"]["type"] == "image/gif")
|| ($_FILES["url"]["type"] == "image/jpeg")
|| ($_FILES["url"]["type"] == "image/JPG")
|| ($_FILES["url"]["type"] == "image/png")
|| ($_FILES["url"]["type"] == "image/pjpeg"))
&& ($_FILES["url"]["size"] < 504800)
&& in_array($extension, $allowedExts))
{
if ($_FILES["url"]["error"] > 0)
{
echo "Return Code: " . $_FILES["url"]["error"] . "<br>";
}
if (file_exists($output_dir. $_FILES["url"]["name"]))
{
unlink($output_dir. $_FILES["url"]["name"]);
}
else
{
$pic=$_FILES["url"]["name"];
$conv=explode(".",$pic);
$ext=$conv['1'];
$user = $_SESSION['username'];
//move the uploaded file to uploads folder;
move_uploaded_file($_FILES["url"] ["tmp_name"],$output_dir.$user.".".$ext);
$pic=$output_dir.$user.".".$ext;
$u_imgurl=$user.".".$ext;
}
}
else{echo '<strong>Warning !</strong> File not Uploaded, Check image' ;}
}
//Submit main comment
if ($parent_id == 0){
$username = mysqli_real_escape_string($dbh,$username);
$description = mysqli_real_escape_string($dbh,$description);
$sub = "Comment to";
$query = "INSERT INTO comments_lite VALUES('','$qazi_id','0','$username','$email','$description','','$parent_id','$date')";
mysqli_query($dbh,$query);
} else {
if ($parent_id >= 1){
global $dbh;
$username = mysqli_real_escape_string($dbh,$username);
$description = mysqli_real_escape_string($dbh,$description);
$sub2 = "Reply to";
$query = "INSERT INTO comments_reply VALUES('','$qazi_id','0','$username','$email','$description','','$parent_id','$date')";
mysqli_query($dbh,$query);
}
}
}
?>
on click of submit you can put the code in js you have to make change in the js file
$.post('phpapgename.php',data:jquerydata,function(){
})
in the .php page you can put your query to submit your data.
You cannot have nested form. Try to avoid it and separate out the forms as below. And while submitting any form if you data from other form, create a hidden fields in this form and submit it.
Another suggestion: Since you're working with javascript anyway, outsource the upload-form to an invisible div and make it pop up by clicking/hovering an upload-button or entering the last field of form1 or whatever.