Hi I have a wordpress php class that receives my ajax and works good.
Now i have to upload a file in the same POST request i use to pass parameters to the PHP class ( i have a switch in the class that sends me to the proper function based on the parameters in the POST data ).
this is the code:
$(document).ready(function (e) {
$('#imageUploadForm').on('submit',(function(e) {
e.preventDefault();
var formData = new FormData(this);
var userID = <?php echo get_current_user_id(); ?>;
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
var data = {
'action': 'romme_call',
'whatever': 1234,
'userID': userID,
'function_call': 'upload_profile_photo',
**'form_data' : formData**
};
console.log(data);
jQuery.post(ajaxurl, data, function(response) {
console.log("done");
console.log(data);
});
this code will of course return a "Uncaught TypeError: Illegal invocation"
because it does not accept formData as parameter in data.
how can i handle this?
It returns Illegal invocation because jQuery is trying to parse the form data with $.param.
When submitting files with jQuery's ajax processing must be turned off
$('#imageUploadForm').on('submit', (function (e) {
e.preventDefault();
var formData = new FormData(this);
var userID = <? php echo get_current_user_id(); ?> ;
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
formData.append('action', 'romme_call');
formData.append('whatever', '1234');
formData.append('userID', userID);
formData.append('function_call', 'upload_profile_photo');
$.ajax({
url : ajaxurl,
type : 'POST',
data : formData,
contentType: false,
processData: false
}).done(function(response) {
console.log("done");
console.log(data);
});
});
Related
I want to send a file from an input to a php script, using ajax.
Here is what I've done so far:
HTML
<div id="inserting">
<button id="inserting_btn">Upload</button>
<input type="file" id="inserting_file"/>
</div>
JS
$('#inserting_btn').click(function(){
var file = $('#inserting_file').val();
$.ajax({
method: 'POST',
url: 'input_text/import.php',
data: 'file='+file,
success: function(data){
alert(data);
}
});
});
PHP file import.php
if ($_FILES['file']['tmp_name'] ){
echo 'yes';
}
else {
echo 'no';
}
(Sorry for my english.)
data: {file: file}
try replacing your data line with this
and in php
$file = $_POST['file'];
Try to change this in your code :
$('#inserting_btn').click(function(){
var file_rec = $('#inserting_file').prop("files")[0]; // get the file
var form_data = new FormData();
form_data.append('file', file_rec);
$.ajax({
method: 'POST',
url: 'input_text/import.php',
data: form_data,
success: function(data){
alert(data);
}
});
});
PHP file import.php
if ($_FILES['file']){
echo 'yes';
}
else {
echo 'no';
}
Hello I have the following AJAX code:
var formData = new FormData($('form')[0]);
$.ajax({
url: 'saveImage.php', //Server script to process data
type: 'POST',
data: formData,
processData: false,
success: function(data){
console.log(data);
}
});
It works great and it loads up the PHP page it the background like it should:
<?php
include_once "mysql_connect.php";
$imageName = mysql_real_escape_string($_FILES["Image1"]["name"]);
$imageData = '';
$imageext = '';
if($imageName != null){
$imageData = mysql_real_escape_string(file_get_contents($_FILES["Image1"]["tmp_name"]));
$imageType = mysql_real_escape_string($_FILES["Image1"]["type"]);
$imageSize = getimagesize($_FILES["Image1"]["tmp_name"]);
$imageType = mysql_real_escape_string($_FILES["Image1"]["type"]);
$FileSize = FileSize($_FILES["Image1"]["tmp_name"]);
$imageext = mysql_real_escape_string($imageSize['mime']);
}
$query=mysql_query("INSERT INTO pictures (`id`, `imagedata`, `imageext`) VALUES ('', '$imageData', '$imageext');");
echo $imageext;
?>
The only problem is that the PHP page cant find the variable Image1 which is the name of the input in the form. Have I done something wrong. I was thinking that maybe in the data parameter in the Ajax it would be something like this but correct:
data: "Image1"=formData,
Is that a thing, if not why cant my PHP see that input field?
You forgot cache and contentType properties in your Ajax function. Try that it should work :
var formData = new FormData($('form')[0]);
$.ajax({
type: "POST",
url: "saveImage.php",
processData: false,
contentType: false,
cache:false,
data: formData,
success: function(data){
console.log(data);
}
});
I am using jQuery mobile to pass form data to a PHP script but I can't access the data in PHP. I have tried this:
$.post('http://127.0.0.1/tum_old/testi.php', $('form#login_form').serialize(), function(data) {
console.log(data);
});
After checking on the data being passed through $('form#login_form').serialize() by
var param = $('form#login_form').serialize();
console.log(param);
I get:
username=ihfufh&passwordinput=dfygfyf
The PHP script:
<?php
$username = $_POST['username'];
echo "$username";
?>
Gives me this error:
Undefined index: username
Serialise and send your data with something like this:
jQuery / AJAX
$('#form').on('submit', function(e){
e.preventDefault();
$.ajax({
// give your form the method POST
type: $(this).attr('method'),
// give your action attribute the value yourphpfile.php
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: 'json',
cache: false,
})
})
Then receive it in PHP like this:
<?php
// assign your post value
$inputvalues = $_POST;
$username = $inputvalues['username'];
?>
I have an error here I'm sure:
var username = $("#username").val();
var password = $("#password").val();
var login = $("#login").val();
var remember = $("#remember").val();
console.log(username, password, login, remember); //this shows up fine
$.ajax({
url: 'php/login.php',
//here i think
data: {username:username,password:password,login:login,remember:remember},
type: 'POST',
dataType: 'application/json',
success: function(data)
{ ....
Because when I get to my login.php I get undefined index on lines:
<?php
$username = $_POST['username']; //here
$password = $_POST['password']; //here
if ($_POST['login']) //check if the submit button is pressed
{
$remember = $_POST['remember']; and here
.....
I return in login.php further down:
echo json_encode("true"); //or "false"
in the response pane in firebug:
<br />
<b>Notice</b>: Undefined index: username in <b>C:\xampp\htdocs\www\php\login.php</b> on line <b>5</b><br />
<br />
<b>Notice</b>: Undefined index: password in <b>C:\xampp\htdocs\www\php\login.php</b> on line <b>6</b><br />
123123123<br />
<b>Notice</b>: Undefined index: login in <b>C:\xampp\htdocs\www\php\login.php</b> on line <b>8</b><br />
Try using php://input
This allows you to read raw data. Since your are using application/json you must be getting data in raw
Try using:
$.ajax({
url: 'php/login.php',
data: JSON.stringify({'username':'username','password':'password','login':'login','remember':'remember'}),
type: 'POST',
dataType: 'json',
contentType: "application/json",
success: function(data) {.....
i am also getting same problem using this method $.ajax and passing everything by : separated but how i reslove this issue using the following snippet.
<script type="text/javascript">
$(function(){
$('#submit').on('click',function(){
var formdata ={
username:$('#username').val(),
password:$('#password').val(),
message:$('#message').val(),
submit:$('#submit').val()
};
var url=$('form').attr('action');
console.log(url);
console.log(formdata);
var posting = $.post(url,formdata);
posting.success(function(data){
$('.success').empty().append(data.username);
});
});
});
</script>
in this snippet .success is a vriable where it spit out the username after success. following is the sample PHP code.
<?php
foreach($_POST as $key => $val)
{
$result[$key] = $val;
}
header('Content-Type: application/json');
echo json_encode($result);
?>
try this method and let me know it does resolve your issue or not ??
Regards
Try this way. I ran into the same issue before and this is the only way I can get JQuery to properly send the key/value pairs when you're using your own string as the key.
var username = $("#username").val();
var password = $("#password").val();
var login = $("#login").val();
var remember = $("#remember").val();
$.ajax({
url: 'php/login.php',
data: "username="username + "&password="+password + "&login="+login + "&remember="+remember,
type: 'POST',
dataType: 'json',
success: function(data)
{ ....
How can I use some PHP variables from the ajax-send.php to the index.php file? I use AJAX as shown below. Do I have to replace AJAX with something else?
index.php
$.ajax({
type: 'POST',
url: 'ajax-send.php',
data: { one: hash },
success: function(data) {
}
});
ajax-send.php
$token = $_POST['one'];
echo "ok"
$toINDEX = "use this in index.php"
Try this
Ajax
$.ajax({
type: 'POST',
url: 'ajax-send.php',
data: { one: hash },
success: function(data) {
var response = data;
//alert(data);To see what you have received from the server
}
});
PHP
if(isset($_POST['one'])){
$token = $_POST['one'];
echo "ok";
$toINDEX = "use this in index.php";
die();
}
In PHP just echo variable or json_encode array. In JS do the following:
var result = $.ajax({
url: this.fileUrl,
type: "POST",
data: data,
async: false,
dataType: 'json'
}).responseText;
Your vaiable is fully accessable.
take the variables in php sessions
//On page 1(ajax-send.php)
session_start();
$_SESSION['token'] = $_POST['one'];
//On page 2(index.php)
session_start();
$var_value = $_SESSION['token'];
You can simply echo the variable and then access it via javascript inside the success function.
But a better approach would be to json_encode the data. The beauty of this is that it will help you to pass multiple values/variables in a single echo. So
PHP
.
..
if(<all is okay>)
{
$toINDEX = "use this in index.php"
$data['result'] = 'ok';
$data['msg'] = $toINDEX;
$data['some_other_value'] = 'blah blah';
// notice how I'm able to pass three values using this approach
}
else
{
$data['result'] = 'notok';
}
echo json_encode($data);
Javascript
$.ajax({
type: 'POST',
url: 'ajax-send.php',
data: { one: hash },
dataType:'json',
success: function(data) {
if(data.result == 'ok')
{
console.log(data.msg);
console.log(data.some_other_value);
}
else
{
// something went wrong
}
}
});
The important thing to note here is dataType:'json' which tells the function to expect the returned data in json format.
EDIT:
As per you comment, you could do this
$toINDEX = "use this in index.php";
// now use the variable here itself
mysql_query("SELECT * FROM table WHERE column = '$toINDEX'");
.
.
if(<all is okay>)
{
$data['result'] = 'ok';
$data['msg'] = 'anything you would like to show the user';
$data['some_other_value'] = 'blah blah';
// notice how I'm able to pass three values using this approach
}
else
{
$data['result'] = 'notok';
}
echo json_encode($data);