Can't get image data when using WordPRess Ajax call - javascript

I am trying to upload image and crop that image and then get the image using following script:
https://github.com/trigo-at/slim-image-cropper-test
Without WordPress I am using this HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Slim Image Cropper Test</title>
<link href="slim/slim.min.css" rel="stylesheet">
<link href="styles/styles.css" rel="stylesheet">
<body>
<form action="" class="form" method="POST" id="form" enctype="multipart/form-data">
<div class="frame">
<input type="file" id="myCropper"/>
<input type="submit" name="submit" id="register_btn" value="Register" class="btn btn-primary">
</div>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="slim/slim.kickstart.min.js"></script>
<script src="scripts/scripts.js"></script>
</body>
</html>
and the Ajax Script is
$("#form").submit(function( e ) {
e.preventDefault();
var data = new FormData($('#form')[0]);
$.ajax({
type: 'POST',
url : 'test.php',
data : data,
dataType: 'json',
cache: false,
processData: false,
contentType: false,
success: function( result ) {
console.log( result );
}
});
});
Now, on the test.php page I can get the image array data
<?php
require_once( 'server/slim.php' );
$imgs = Slim::getImages();
print_r( $imgs );
NOW, for this WordPRess Ajax call it's not getting the image data :(
WordPress Ajax Call
$("#form").submit(function( e ) {
e.preventDefault();
var register_type = '' ;
register_type = $(this).data('register-type');
var data = new FormData($('#form')[0]);
data.append("action", "register_action");
data.append("register_type", register_type);
$.ajax({
type: 'POST',
url : settings.ajaxurl,
data : data,
dataType: 'json',
cache: false,
processData: false,
contentType: false,
success: function( result ) {
console.log( result );
}
});
});
WordPress HTML form part:
<form action="" class="form" method="POST" id="form" enctype="multipart/form-data">
<div class="form-group">
<div class="frame">
<input type="file" id="myCropper"/>
</div>
</div>
<div class="form-group">
<div id="form_result"></div>
<?php wp_nonce_field( 'register_action' ); ?>
<input type="submit" name="submit" data-register-type="<?php echo hashMe('ccroipr_register_p', 'e'); ?>" id="register_btn" value="Register" class="btn btn-primary">
</div>
</form>
WordPress PHP Part ( get nothign :():
echo '<pre>';
$imgs = Slim::getImages();
print_r( $imgs );
echo '</pre>';
**PHP output:**
<pre>Array
(
[0] => Array
(
[input] =>
[output] =>
[actions] =>
[meta] =>
)
)
</pre>
But without WordPress, I can get the image array data.
Can someone tell me what's going wrong here please?

Related

How to send HTML form by Ajax, save data to file and display them in div

I'm new to Web Development. I'm learning JavaScript now(JQuery) and I chose Simple Chat as a project to get started.
Unfortunately, I can't figure out how to prevent the page from refreshing after a message is sent.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<title>Chat</title>
</head>
<body>
<h1>Chat room</h1>
<div id="status"></div>
<form id="send" class="ajax" action="action.php" method="POST">
<label for="fname">Type your message</label>
<input type="text" id="fname" name="myMessage">
<input id="upload" type="submit" name="myButton"value="Submit" />
</form>
<div id="result"></div>
<script>
$(document).ready(function () {
$("form").submit(function (event) {
var formData = {
name: $("#fname").val(),
};
var posting = $.post(url, {
name: $('#fname').val(),
});
/* So far, just listing whether the Form has managed to prevent its classic sending */
posting.done(function(data) {
$('#result').text('success');
});
$.ajax({
type: "POST",
url: "process.php",
data: formData,
dataType: "json",
encode: true,
}).done(function (data) {
console.log(data);
});
event.preventDefault();
});
});
</script>
</body>
</html>
PHP:
<?php
$path = 'messages.txt';
if (isset($_POST['myButton']) ) {
$fh = fopen($path,"a");
$string = $_POST['myMessage' ];
fwrite($fh,$string . PHP_EOL);
fclose($fh);
}
?>
I have created a text file messages.txt, where I want to save newly created messages using Ajax.
I would like the newly added message to be displayed on the page below the chat( in the div with id #result)
Thanks everybody for advices, this is how I have solved it
$("#send").submit(function() {
event.preventDefault();
var $messageSent = $("#send").serialize();
$.ajax({
type: 'POST',
url: 'action.php',
data: $messageSent,
});
});
To save data to file in PHP with this jquery ajax code, try this:
<?php
$path = 'messages.txt';
if (isset($_POST['name']) ) {
$fh = fopen($path,"w");
$string = $_POST['name']. PHP_EOL;
fwrite($fh,$string);
fclose($fh);
}
?>

Jquery Form Submission with Image

Please refer question: Jquery Image Upload in Form with Plugin goes Null
I am trying to submit a form using JQuery Ajax and trying to retrieve in a PHP file and save. for the particular form there are two file inputs.
Image
Note
when I debug using var_dump($_FILES), I was able to see only Note's array but not Image's. for image upload I am using a plugin called FancyUpload, that is what probably causing the issue. below is the form
<form id="form" action="add.php" method="post" autocomplete="off" enctype="multipart/form-data">
<div>
<input aria-label="cxname" id="cxname" name="cxname" class="form-control" placeholder="Name" type="text">
</div>
<div>
<select name="sales" id="sales" class="SlectBox form-control">
<option value='0'>Sales</option>
<?php echo sales(); ?>
</select>
</div>
<div>
<input class="custom-file-input" placeholder="choose note" name="note" id="note" type="file">
<label class="custom-file-label">Choose Note</label>
</div>
<div>
<input class="custom-file-input" placeholder="Choose Image" name="image" id="image" type="file" multiple>
</div>
<div>
<button id="submit" class="btn btn-primary btn-size">Add</button>
</div>
</form>
Jquery Below along with its fancy uploader classes
<!-- JQuery min js -->
<script src="assets/plugins/jquery/jquery.min.js"></script>
<script src="assets/plugins/jquery-ui/ui/widget.js"></script>
<script src="assets/plugins/fancyuploder/jquery.ui.widget.js"></script>
<script src="assets/plugins/fancyuploder/jquery.fileupload.js"></script>
<script src="assets/plugins/fancyuploder/jquery.iframe-transport.js"></script>
<script src="assets/plugins/fancyuploder/jquery.fancy-fileupload.js"></script>
<script>
$(document).ready(function(e){
var image = $('#image').FancyFileUpload({
maxfilesize : 1000000,
params : {
action : 'form'
},
autoUpload: false
});
$("#form").on('submit', function(e){
e.preventDefault();
var fd = new FormData();
fd.append('pimage', $(image)[0].files[0]);
fd.append('deliveryNote', $("#note")[0].files[0]);
fd.append('cxname', $('input[name=cxname]').val());
fd.append('sales', $('select[name=sales]').val());
$.ajax({
type: 'POST',
url: 'add.php',
data: fd,
dataType: 'json',
processData:false,
contentType: false,
cache: false,
async: false,
success: function(response){
$('.statusMsg').html('');
if(response.status == 1){
$('#form')[0].reset();
$('.statusMsg').html('<p class="alert alert-success">'+response.message+'</p>');
alert('received');
}else{
$('.statusMsg').html(alert(response.message));
}
$('#form').css("opacity","");
$(".submit").removeAttr("disabled");
}
});
});
});
Retreiving PHP
upload_dir = 'uploads/';
pdf_dir = 'doc/';
if (isset($_POST['cxname']) || isset($_POST['deliveryNote']) || isset($_POST['pimage']) || isset($_POST['sales'])) //even tried with ($_FILES['pimage'])
{
$cxname=$_POST['cxname'];
$sales=$_POST['sales'];
var_dump($_FILES);
//MOVE IMAGE -> Comes Empty
if(!empty($_FILES['pimage']['tmp_name']))
{
$temp = $_FILES['pimage']['tmp_name'];
$name = $_FILES['pimage']['name'];
$result = move_uploaded_file($temp,$upload_dir.$name);
$response['status'] = 1;
$response['message'] = 'IMAGE HAS BEEN SAVED';
}
else{
$name = '';
$response['status'] = 0;
$response['message'] = 'IMAGE CAME EMPTY!';
}
//SAVE NOTE
$_pdfDN = $_FILES['deliveryNote']['name'];
$Tempfile = $_FILES['deliveryNote']['tmp_name'];
$_pdfResult = move_uploaded_file($Tempfile,$pdf_dir.$_pdfDN);
}
If I do without image upload plugin, it works fine. Please advice.

Upload an excel in my view to display it in the controller

I want...
Upload an excel file to my server in my view (only temporary because I will only read it, get its data and save it to a DB), then use fopen () on my controller, and open that file that the user uploaded in the view . (I am using CI)
Issue...
When I try to open the file in my controller it does not exist.
What I have...
view
<?php
print_r($_FILES);
$archivo = fopen($_FILES["csv"]["tmp_name"], 'r');
?>
<?php echo form_open_multipart('',array('id' => 'envio', 'role'=>'form')); ?>
<legend>Importar Datos</legend>
<?php if (isset($alerta) && $alerta): ?>
<div class="alert alert-danger">
<?=$alerta ?>
</div>
<?php endif; ?>
<div class="form-group">
<label for="">Archivo CSV</label>
<input type="file" class="form-control" id="csv" name="csv" placeholder="Archivo CSV">
</div>
<div class="checkbox">
<label>
<input type="checkbox" value="1" name="has_header" checked>
El archivo contiene cabeceras
</label>
</div>
<input type="hidden" name="key" value="1">
<button type="submit" class="btn btn-primary">Enviar</button>
</form>
<script type="text/javascript">
function al_inicio()
{
console.log("on submit set");
$( '#envio-t' )
.submit( function( e ) {
console.log('submitting');
e.preventDefault();
$.ajax( {
// url: 'http://host.com/action/',
type: 'POST',
data: new FormData( this ),
processData: false,
contentType: false,
dataType: 'script'
} );
} );
}
</script>
Controller_api
function dev_get(){
print_r($_FILES);
$archivo = fopen($_FILES["csv"]["tmp_name"], 'r');
}
Images
This is in View
This is in Controller

Ajax form submit using mongodb

i am trying to use ajax submit form but for some reason it doesn't work for me, any suggestions how to fix it.
I'm getting the alert message when I submit but it takes me to another page, what am i doing wrong with ajax request ?
<!DOCTYPE html>
<html>
<head>
<title>Get Data From a MySQL Database Using jQuery and PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
// AJAX forms
$("#search_form").submit(function(e){
e.preventDefault();
//var data = $(this).serialize();
var method = $(this).attr("method");
var action = $(this).attr("action");
var username = $('#username').val();
$.ajax({
url: 'process.php',
type: 'POST',
data: { name: username },
cache: false,
success: function(data){
$('#results').html(data);
}
})
})
});
</script>
</head>
<body>
<span>Search by name: </span>
<form method="POST" action="process.php" id="search_form">
<input type="text" id="username" name="name">
<input type="submit" id="submit" value="Search">
</form>
<div id="results"></div>
</body>
</html>
process.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
// Check if $_POST is set
if ( empty ( $_POST['name'] ) ) {
echo "Something wrong!";
exit;
}
$name = $_POST['name'];
$m = new MongoClient();
//echo "Connection to database successfully";
// select a database
$address = array(
'name'=>$name,
'city' => 'test',
'state' => 'test2',
'zipcode' => 'test3'
);
$db = $m->local;
//echo "Database mydb selected";
$collection = $db->user;
//echo "Collection selected succsessfully";
$collection->insert($address);
$user = $collection->findOne(array('name' => $name));
?>
<ul>
<li><?php echo $user['name']; ?>: <?php echo $user['city']; ?></li>
<script>
alert('test 1234');
</script>
</ul>
I had to change:
$("#search_form").submit(function(e){
to:
$(document).on('submit', '#search_form', function(){
Now it works fine.
<!DOCTYPE html>
<html>
<head>
<title>Get Data From a MySQL Database Using jQuery and PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
// AJAX forms
$(document).on('submit', '#search_form', function() {
//e.preventDefault();
//var data = $(this).serialize();
var method = $(this).attr("method");
var action = $(this).attr("action");
var username = $('#username').val();
$.ajax({
type: 'POST',
url: 'process.php',
data: {
name: username
},
cache: false,
success: function(data) {
$('#results').html(data);
}
})
return false;
});
});
</script>
</head>
<body>
<span>Search by name: </span>
<form method="POST" action="process.php" id="search_form">
<input type="text" id="username" name="name">
<input type="submit" id="submit" value="Search">
</form>
<div id="results"></div>
</body>
</html>

How to Insert and display record without refreshing web page in codeigniter version?

I have a code here of inserting and displaying record without refreshing web page using ajax and plain php but I don't know how to set this up using codeigniter. Please help. Here are the codes
inserting.php
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js">
</script>
<script type="text/javascript" >
$(function() {
$(".comment_button").click(function() {
var test = $("#content").val();
var dataString = 'content='+ test;
if(test=='')
{
alert("Please Enter Some Text");
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="ajax-loader.gif" align="absmiddle">
<span class="loading">Loading Comment...</span>');
$.ajax({
type: "POST",
url: "demo_insert.php",
data: dataString,
cache: false,
success: function(html){
$("#display").after(html);
document.getElementById('content').value='';
document.getElementById('content').focus();
$("#flash").hide();
}
});
} return false;
});
});
</script>
// HTML code
<div>
<form method="post" name="form" action="">
<h3>What are you doing?</h3>
<textarea cols="30" rows="2" name="content" id="content" maxlength="145" >
</textarea><br />
<input type="submit" value="Update" name="submit" class="comment_button"/>
</form>
</div>
<div id="flash"></div>
<div id="display"></div>
demo_insert.php
PHP Code display recently inserted record from the database.
<?php
include('db.php');
if(isSet($_POST['content']))
{
$content=$_POST['content'];
mysql_query("insert into messages(msg) values ('$content')");
$sql_in= mysql_query("SELECT msg,msg_id FROM messages order by msg_id desc");
$r=mysql_fetch_array($sql_in);
}
?>
<b><?php echo $r['msg']; ?></b>
In your wellcome controller you can add the following:
public function inserting()
{
$this->load->view('inserting');
}
public function process()
{
$content=$this->input->post('content');
if($this->db->insert('mytable', array('msg' => $content))){
echo "<b>{$content}</b>";
}
You should then use inserting.php as your view, in application/views, and the ajax url would be /process.
Didn't test it, but this should do the trick. Also, you should check this example http://runnable.com/UXczcazDrMMiAAGl/how-to-do-ajax-in-codeigniter-for-php

Categories