jQuery issues when using ajax and .attr('class', 'new_class') - php

I am using Zend Framework, and to illustrate what is working I added the saveAction() to this post and it works flawlessly. It will animate and change the class as I want. The function upload instead only change the text and ignore the javascript. I can do alerts that works, however jquery is not possible. I get error saying that $ is undefined. How could it be undefined in 1 case and not the other?
I am catching the upload form with ajax and just throw it into the #savecontainer.
Hope there's a solution, it seems to be a tiny issue somewhere, but I can't find it on my own. Thank you.
it looks like this:
$(document).ready(function() {
$('#newsForm').ajaxForm({
target: '#savecontainer'
});
$('#uploadForm').ajaxForm({
target: '#savecontainer'
});
$("#btn_save").click(function () {
$('#newsForm').submit();
});
$("#btn_upload").click(function () {
$('#uploadForm').submit();
});
});
public function saveAction()
{
$this->_helper->layout->disableLayout();
$db = new Admin_Model_DbAccess();
if(isset($_POST['active']))
$_POST['active'] = 1;
else
$_POST['active'] = 0;
if($_POST['id'] == 0){
// If it is a new post
$data = array(
'header' => $_POST['header'],
'message' => $_POST['message'],
'date' => time(),
'user' => Zend_Auth::getInstance()->getStorage()->read()->id,
'image' => $_POST['image'],
'active' => $_POST['active'],
'category' => $_POST['category']
);
if($db->addNews($data)){
// set the css variables to saved
echo "<script type='text/javascript'>
$('#savecontainer').fadeOut(200).attr('class', 'savecontainer_success').fadeIn(400);
$('#news_id').attr('value', '".$db->lastInsertId()."');
$('#upload_box').show('slide', {direction: 'up'}, 500);
$('#news_id_upload').attr('value', '".$db->lastInsertId()."');
</script>";
echo "Status: Added.";
}else{
// set the css variables to failed
echo "<script type='text/javascript'>
$('#savecontainer').fadeOut(200).attr('class', 'savecontainer_fail').fadeIn(400);
</script>";
echo "Status: Error.";
}
}else{
$data = array(
'header' => $_POST['header'],
'message' => $_POST['message'],
'image' => $_POST['image'],
'active' => $_POST['active'],
'category' => $_POST['category']
);
$db = new Admin_Model_DbAccess();
if($db->updateNews($_POST['id'], $data)){
// set the css variables to saved
echo "<script type='text/javascript'>
$('#savecontainer').fadeOut(200).attr('class', 'savecontainer_success').fadeIn(400);
</script>";
echo "Status: Updated.";
}else{
// set the css variables to failed
echo "<script type='text/javascript'>
$('#savecontainer').fadeOut(200).attr('class', 'savecontainer_fail').fadeIn(400);
</script>";
echo "Status: Error.";
}
}
}
public function uploadAction(){
$this->_helper->layout->disableLayout();
if ($this->_request->isPost()) {
//Startup the adapter to upload
$adapter = new Zend_File_Transfer_Adapter_Http();
//Define the upload path
define('UPLOAD_NEWS_IMAGE_PATH', APPLICATION_PUBLIC_PATH. "/img/news/");
// Fixa upload path
$adapter->addValidator('Extension', false, array('jpg', 'jpeg' , 'gif' , 'png'))
->addValidator('Count', false , array( 'min' => 0, 'max' => 0));
$file = $adapter->getFileInfo();
$adapter->receive();
$messages = $adapter->getMessages();
if(isset($messages['fileCountTooMany']) && !isset($messages['fileExtensionFalse'])){
//If the file does exists (Everything went fine);
$fileinfo['ext'] = end(explode(".", $file['upload_0_']['name']));
$uploaded_filename = $_POST['id'].".".$fileinfo['ext'];
// Change name to id.jpg for example
move_uploaded_file($file['upload_0_']['tmp_name'], UPLOAD_NEWS_IMAGE_PATH.$uploaded_filename);
// resize to
$full_thumb = Butikadmin_Model_PhpThumbFactory::create(UPLOAD_NEWS_IMAGE_PATH.$uploaded_filename);
$full_thumb->resize(960, 500);
$id = $_GET['id'];
if($full_thumb->save(UPLOAD_NEWS_IMAGE_PATH.$uploaded_filename)){
// set the css variables to saved
echo "<script type='text/javascript'>
$('#savecontainer').fadeOut(200).attr('class', 'savecontainer_success').fadeIn(400);
$('#upload_box').fadeOut(500);
</script>";
echo "Status: Uploaded.";
}
}else{
// If the file is not right format
// set the css variables to saved
echo "<script type='text/javascript'>
$('#savecontainer').fadeOut(200).attr('class', 'savecontainer_fail').fadeIn(400);
</script>";
echo "Status: Error.";
}
}
}

why not using an ajax call instead of .submit?
and in the php code, remove the js record and return data (array or ojbect) from the function and handle it back in the js script with a callback function which return that data

Related

Problem saving multiple JSON records to a file

I made an HTML form that sends the data to JSON, but I experienced a problem with code I took from a tutorial. It makes a new JSON file every time I submit a new form. How to make it so it adds the data to it, not rewrite it?
This is the PHP code I'm using
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
function get_data() {
$datae = array();
$datae[] = array(
'Name' => $_POST['name'],
'Strategy' => $_POST['strategy'],
'Teams' => $_POST['team'],
);
return json_encode($datae);
}
$name = "strategies";
$file_name = $name . '.json';
if(file_put_contents(
"$file_name", get_data())) {
echo $file_name .' file created';
}
else {
echo 'There is some error';
}
}
?>

PHP Variable from another file without include or session

I've tried using $_SESSION and include, none which have worked. What I'm doing is uploading an image to my server. Using Ajax to run a file called upload.php which has the upload script in it. When the file gets uploaded I want to pass the filename to my main.php page to use as a php variable. Include would just throw errors of undefined variables and session just wouldn't work.
Ajax
$(document).ready(function(){
$(document).on('change', '#file', function(){
var name = document.getElementById("file").files[0].name;
var form_data = new FormData();
var ext = name.split('.').pop().toLowerCase();
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("file").files[0]);
var f = document.getElementById("file").files[0];
var fsize = f.size||f.fileSize;
if(fsize < 4000000)
{
form_data.append("file", document.getElementById('file').files[0]);
$.ajax({
url:"upload.php",
method:"POST",
data: form_data,
contentType: false,
cache: false,
processData: false,
success:function(data)
{
$('#image_upload_info').html(data);
}
});
}
});
Part of the upload script, $imagenameupload is the variable I want to pass back to my main.php page
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
echo '<div class="container">';
echo '<div class="row">';
echo '<div class="col-md-8">';
echo '<div class="alert alert-success">';
echo "Pilt: ". basename( $_FILES["file"]["name"]). " on lisatud!";
move_uploaded_file($_FILES["file"]["tmp_name"], $target_file);
echo '</div>';
echo '</div>';
echo '</div>';
echo '</div>';
$imageNameUpload = basename( $_FILES["file"]["name"]);
}
EDIT
I explained it a little rought before. I want to be able to insert said variable into a database with other data. Heres a little more code.
SQL INSERT
if(isset($_POST['submit'])){
date_default_timezone_set('Europe/Tallinn');
$typeSelector = $_POST['typeSelector'];
if (isset($_POST['regionSelector']) ? $_POST['regionSelector'] : null) {
$checkBox = implode(',', $_POST['regionSelector']);
}
if(isset($_SESSION['imageNameUpload'])) {
$uploadedPic = $_SESSION['imageNameUpload'];
}
$now = new DateTime();
$timestring = $now->format('d.m.Y H:i');
$_POST = array_map('stripslashes', $_POST);
//$_POST = json_decode(stripslashes(json_encode($_POST)), true);
extract($_POST);
if($title ==''){
$error[] = 'Pealkiri on puudu.';
}
if($newstext ==''){
$error[] = 'Uudise sisu on puudu.';
}
if ($checkBox == '') {
$error[] = 'Regioon on puudu.';
}
if(!isset($error)){
try {
$stmt = $db->prepare('INSERT INTO news (title,shortdesc,newstext,tag,region,publish_date,imageName) VALUES (:title, :shortdesc, :newstext, :tag, :region, :publish_date, :imageName)') ;
$stmt->execute(array(
':title' => $title,
':shortdesc' => $shortdesc,
':newstext' => $newstext,
':tag' => $typeSelector,
':region' => $checkBox,
':imageName' => $imageName,
':publish_date' => $timestring
));
header('Location: index.php?news=addednews');
exit;
} catch(PDOException $e) {
echo $e->getMessage();
}
}
}
In upload.php
First you must start the seesion via session_start();
directly after the opening PHP 'tag' ()
Then you must save your variable to the session.
You can do this like,
$_SESSION['imageNameUpload'] = $imageNameUpload;
For main.php
And in the other file you must also use session_start(); at the very first after the
Then you could access the old variable via $imageNameUpload = $_SESSION['imageNameUpload'];.
You now can also use $imageNameUpload in the main.php file. But you only can use it if it's set (and you where at the first file before).
upload.php
<?php
session_start();
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
echo '<div class="container">';
echo '<div class="row">';
echo '<div class="col-md-8">';
echo '<div class="alert alert-success">';
echo "Pilt: ". basename( $_FILES["file"]["name"]). " on lisatud!";
move_uploaded_file($_FILES["file"]["tmp_name"], $target_file);
echo '</div>';
echo '</div>';
echo '</div>';
echo '</div>';
$imageNameUpload = basename( $_FILES["file"]["name"]);
$_SESSION['imageNameUpload'] = $imageNameUpload;
}
main.php
<?php
session_start();
if(isset($_SESSION['imageNameUpload'])) {
$imageNameUpload = $_SESSION['imageNameUpload'];
}
// Other content of file
?>
If you don't want to refresh the page after image upload just want to show the uploaded image name without refreshing the page
Then,Change in your upload.php
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
$imageNameUpload = basename( $_FILES["file"]["name"]);
$data = '<div class="container"><div class="row"><div class="col-md-8"><div class="alert alert-success">Pilt: '. $imageNameUpload. ' on lisatud!</div></div></div></div>';
echo $data;
exit();
}
And if you want to refresh the page then show image name on main.php. In that case you have to store data in session as i explain above. and add page refresh statement in ajax success block. And check in main.php if isset $imageNameUpload varible then first show it on html and then unset it. SO it will not seen in another page refresh request.
Hope this helps

php json return creating syntax error on responce

I have looked at many posts here and elswhere on this error without success of resolving my error. In console the form data is being sent via json as expected to my php processing page, the php process is not returning any errors so I'm confident the process is completing. I have checked the way the result is formatted and cannot see anything wrong there, although I'm no expert at ajax/json so I could be wrong, Here is my code
Jquery code
<script type="text/javascript">
$(document).ready(function() {
$("#admin_login_but").click(function() {
if($("#admin_name").val()=="" || $("#admin_password").val()=="" || $("#admin_email").val()=="") {
$(".adminloginError").html("Please enter Admin Name, Admin Email and Admin Password");
return false;
}else{
$(".adminloginError").html('<img src="image/ajax-loader.gif" width="16" height="16" alt=""/>');
var adminName=$("#admin_name").val();
var adminPassword=$("#admin_password").val();
var adminEmail=$("#admin_email").val();
$.post("includes/admin_login.inc.php",{admin_name:adminName,admin_password:adminPassword, admin_email:adminEmail},function(json) {
if(json.result === "success") {
$(".adminloginError").html( "Welcome "+adminName+"!");
setTimeout(function(){
window.location= "admin_secure.php";
},2000);
}else{
$(".adminloginError").html(json.message);
}
});
}
Here is my php processing code
<?php
include_once 'functions.php';
include_once 'db_connect.php';
header("Content-Type: application/json"); //this will tell the browser to send a json object back to client not text/html (as default)
//convert variable (array) into a JSON object
function result($var){
echo json_encode($var);
exit();
}
sec_session_start();
error_reporting(E_ALL); ini_set('display_errors', 1);
//check if surname is empty
if (isset($_POST["admin_login_but"])) {
//check if first_name is empty
if (empty($_POST["admin_name"])) {
$response = array('result'=>'fail', 'message' => 'Missing Admin Name');
result($response);
}else{
// if not empty sanitize first_name input
$admin_name = filter_input(INPUT_POST, 'admin_name', FILTER_SANITIZE_STRING);
}
//Check if email is empty and santize and validate email
if (empty($_POST['admin_email'])) {
$response = array('result'=>'fail', 'message' => 'Missing Admin Email');
result($response);
}else{
$admin_email = filter_var($_POST['admin_email'], FILTER_SANITIZE_EMAIL);
}
if (!filter_var($admin_email, FILTER_VALIDATE_EMAIL)) {
$response = array('result'=>'fail', 'message' => 'The Email is not in a Valid Email Format!');
result($response);
}
//check if register password input is empty
if (empty($_POST["admin_password"])) {
$response = array('result'=>'fail', 'message' => 'Missing Admin Password');
result($response);
} else {
//Sanitize the data passed in 'password'
$admin_password = filter_input(INPUT_POST, 'admin_password', FILTER_SANITIZE_STRING);
}
//validate the data passed in 'password'
if (!preg_match("/^.*(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$/", $admin_password)) {
$response = array('result'=>'fail', 'message' => 'Password is in the Wrong Format!');
result($response);
}
//query database
$results = mysqli_query($mysqli, "SELECT * FROM admin WHERE name = '$admin_name' AND email = '$admin_email' AND hash = '$admin_password'");
// Check if SQL query had erors
if(!$results){
$response = array('result'=>'fail', 'message' => 'sql error: ' . mysqli_error($mysqli));
result($response);
}
// If query was successfull and there are rows do this:
if (mysqli_num_rows($results)>0){
$_GET['name'] = $admin_name;
$response = array('result'=>'success', 'message' => 'User is Authenticated');
result($response);
} else {
$response = array('result'=>'fail', 'message' => 'User Authentication Failed');
result($response);
}
}
?>
I cannot figure out how to resolve this. Can anyone help please
I just figured it out, I hadn't put an else option at the end of my php for the initial post check
if(!isset($_POST)) {
//all the processing code
}else{
$response = array('result'=>'success', 'message' => 'Post is Empty');
result($response);
}

How can I pass an extra variable with this JSON and jQuery code?

I am trying to set up an AJAX file upload script with jQuery and JSON.
I have some experience with AJAX and jQuery, but have never used JSON in my life.
While going through this tutorial, I found that their method of retrieving uploaded files was to get all the files from the database.
This does not suit my current needs. This will be part of a form for writing articles to the database, so the script needs to work only with attachments associated with the article being created.
I basically had to create a DB table for attachment sessions which I use to determine the attachments that are currently being worked with.
This is fine, however, I now need a way to pass an extra variable for the session id to the jQuery script.
I have encoded the JSON data in my PHP script, but now how do I access the certain variable in the jQuery script? In the code below, I will indicate where I encoded the JSON data, and also where I would like to add that data in the jQuery script.
PS: This is in CodeIgniter.
This is the PHP script
function upload_file()
{
$status = '';
$msg = '';
$config = array(
'upload_path' => FCPATH.'attachments',
'allowed_types' => 'jpg|gif|png',
'min_height' => ($this->session->flashdata('img_min_height')) ? $this->session->flashdata('img_min_height') : 0,
'min_width' => ($this->session->flashdata('img_min_width')) ? $this->session->flashdata('img_min_width') : 0,
'max_height' => ($this->session->flashdata('img_max_height')) ? $this->session->flashdata('img_max_height') : 0,
'max_width' => ($this->session->flashdata('img_max_width')) ? $this->session->flashdata('img_max_width') : 0,
'max_size' => 300,
'encrypt_name' => TRUE
);
$this->load->library('upload', $config);
if(!$this->upload->do_upload('user_files')){
$status = 'error';
$msg = $this->upload->display_errors('', '');
} else {
$data = $this->upload->data();
$this->attachment->create($data);
if($this->attachment->error == NULL){
$status = "success";
$msg = "File uploaded.";
$session_id = $this->attachment->_session_id;
} else {
unlink($data['full_path']);
$status = "error";
$msg = $this->attachment->error;
$session_id = '';
}
}
#unlink($_FILES['user_files']);
echo json_encode(array('status' => $status, 'msg' => $msg, 'session_id' => $session_id )); **//I added the session id variable here.**
}
This is the jQuery script that gets the uploaded files:
function refresh_files()
{
$.get('./upload/files/') //The session ID should go at the end of this URL...
.success(function (data){
$('#files').html(data);
});
}
You simply add an extra parameter next to the url.
Reference: http://api.jquery.com/jquery.get/
$.get('./upload/files/', required_data_here)
.success(function (data){
$('#files').html(data);
});
Then in your server-side script:
<?php
var sess_id = $_GET['your_variable_here'];
?>
Here's an example from the reference:
$.get( "test.php", { name: "John", time: "2pm" } );

Saving variable value in a text file using PHP

by clicking on a button I am setting a variable in php using Ajax.
submitInfo(var1);
function submitInfo(var1)
{
$.ajax({
type: "POST",
url: "js/info.php",
data: {Info:var1},
success: function (result)
{
alert(result);
}
});
}
in my php code, How can I save "var1" in a text file? I have used this to save variable in a text file but it is not saving anything there:
<?php
if (isset($_POST['var1']))
{
echo $_POST['var1'];
}
$file = fopen("js/test.txt","w");
echo fwrite($file,$var1);
fclose($file);
?>
The first issue is that in your JQuery you actually assigning the var1 variable to 'Info'
so the $_POST array will contain this rather than var1.
You then only want to manage your attempts to write to the file in order to get nicer, more user friendly error messages which will give you something nicer to send back and help you if debug any other problems.
<?php
$var1 = "";
$filename = "js/test.txt";
// Get the correct $_POST object
if (isset($_POST['Info']) {
$var1 = $_POST['Info'];
}
// If the variable is not empty try to write your file
if (!empty($var1)) {
if(!$file = fopen($filename,"w")) {
$msg = "Cannot open file");
} else if (fwrite($file,$var1) === false) {
$msg = "Cannot write to file");
} else {
$msg => 'all was good'
}
fclose($file);
$result = array(
'error' => 'false',
'msg' => $msg
);
} else {
$result = array(
'error' => 'true',
'msg' => 'Info was empty'
);
}
// Send your message back
echo "{\"result\":".json_encode{$result)."}";
PS: Not tested this so fingers crossed there are no typos.
Try this:
<?php
if (isset($_REQUEST['Info'])){
$var1 = $_REQUEST['Info'];
$file = fopen("js/test.txt","w");
echo fwrite($file,$var1);
fclose($file);
}
?>

Categories