Issues when using Ajax for post request on WordPress plugin - php

I'm working on submitting a post request using Ajax in my WordPress plugin. My JavaScript looks like this:
var file_data = $("#fileID").prop("files")[0];
var form_data = new FormData();
form_data.append("action", "my_function");
form_data.append("file", file_data);
$.ajax({
type: "POST",
url: "' . admin_url("admin-ajax.php") . '",
cache: false,
dataType: "json",
processData: false,
data: form_data,
success: function(php_script_response) {
alert(php_script_response); // display response from the PHP script, if any
},
error: function(response) {
alert(response);
}
});
I have added two add_action's for my function (in my plugin's php file) like this:
add_action('wp_ajax_my_function', 'my_function');
add_action('wp_ajax_nopriv_my_function', 'my_function');
My function isn't getting called unless I use data: form_data + "&action=my_function", but then I don't have any data available in the function.
How can I correctly get this request sent with my data?

Related

How to POST dataform data and other datas through a single ajax call

I got struck in a point where i have to pass dataForm data's and other datas through a single ajax call, Actually am passing a Blob data by creating a DataFrom object Following code will give you a exact explanation
my ajax call with data's
Fr.voice.export(function(blob){
var data = new FormData();
data.append('file', blob);
console.log(blob);
$.ajax({
url: "upload1.php",
type: 'POST',
data: data,
contentType: false,
processData: false,
success: function(data) {
// Sent to Server
}
});
}, "blob");
In the above Ajax call am POSTing only the blob data where as i have to pass other data's like
id: student_id,
test_no: test_no,
attempt_no: attempt_no,
question_name: "audio" + audioNo.
What i have tried
Fr.voice.export(function(blob){
var data = new FormData();
data.append('file', blob);
console.log(blob);
var postData = {
"audio": base64,
"id": student_id,
"test_no": test_no,
"attempt_no": attempt_no,
"question_name": "audio" + audioNo
};
$.ajax({
url: "upload1.php",
type: 'POST',
data: {data,postData},
contentType: false,
processData: false,
success: function(data) {
// Sent to Server
}
});
}, "blob");
Am getting [object,object] while am posting the data.
Am new to php and Ajax call, please help me to solve this. Thank you in advance.
Have you tried it like this:
$.ajax({
url: "upload1.php",
type: 'POST',
data: { data: dataVar, postData: postDataVar},
contentType: false,
processData: false,
success: function(data) {
// Sent to Server
}
});

PHP Ajax Post File and Text Same Time

I can post only image and get it with $_FILES['foto']['name']. I need post image and text same time.
var fotoFile = new FormData();
$('#foto').on('change', function (evt) {
var files = evt.target.files;
if (files.length > 0) {
fotoFile.append("foto", files[0]);
}
});
It is post code
` $.ajax({
url: 'postpages/personelsave.php',
dataType: 'text',
type: 'post',
cache: false,
contentType: false,
processData: false,
data: {foto : fotoFile, tc_no : document.getElementById('tcNo').value},
success: function(php_script_response){
alert(php_script_response);
}
});`
and personelsave.php
$_FILES['foto']['type']
$_POST["tc_no"]
Error : undefined index foto.
What is wrong with it?
You can't use multiple dataTypes, if you use JSONP this will return a jsonp block which you could use to call a callback to handle the return data like this:
Basic example of using .ajax() with JSONP?
So through JSONP you can handle multiple dataTypes.
Just use below to submit all types of input data including file
var formData = new FormData($("#formID")[0]);
$.ajax({
type: "POST",
url: 'postpages/personelsave.php',
data: formData,
processData: false,
contentType: false,
});

Knockout and AJAX post request PHP

I am attempting to get our knockout form to submit to a php script and am getting undefinedIndex errors. I am pretty sure it is the way we are sending the data over in our ajax function.
Here is the ajax:
$.ajax({
url: '/orders/add',
type: 'post',
data: {payload:ko.toJSON(allModel)},
contentType: 'application/json',
success: function (result) {
alert(result);
}
});
Here is the PHP (we use laravel)
return json_decode($_POST["payload"]);
Pete is correct. You need to use just one data field. If you want a variable, define it before the $.ajax post
var dataPayload = ko.toJSON(allModel);
$.ajax({
url: '/orders/add',
type: 'post',
data: {payload: dataPayload},
contentType: 'application/json',
success: function (result) {
alert(result);
}
});

PHP isn't recognizing data posted by ajax

I'm sending an ajax call to my PHP script as follows:
function load(){
var request = {};
request['action'] = 'load';
request['file'] = 'lorem_ipsum.txt';
$.ajax({
type: 'POST',
url: cgi_file,
data: JSON.stringify(request),
processData: false,
dataType: 'html',
contentType: 'application/html',
success:function(response){
console.log("received " + response);
}
});
}
and my PHP script is as follows:
$content_dir = '/static/content/';
$action = $_POST['action'];
switch ($action){
case 'load':
$file = $_POST['filename'];
echo file_get_contents($content_dir . $file);
exit();
}
The PHP is responding with the following failure:
Notice: Undefined index: action in /var/www/river/api.php on line 5
What's the issue here?
Try ditch processData: false and contentType: 'application/html' and it should work
$.ajax({
type: 'POST',
url: cgi_file,
data: request,
dataType: 'html',
success:function(response){
console.log("received " + response);
}
});
Just leave data as it is:
data: request,
You don't need to stringify it.
Also, your file parameter allows an attacker to read arbitrary files from your filesystem. Sanitize it.
A few things wrong here, firstly the contentType property is for the data you are sending to the server, secondly dataType should be set to text as that is what you are recieveing from the server. If you want to receive the data in the $_POST array your javascript should look like this,
$.ajax({
type: 'POST',
url: cgi_file,
data: {
action: "load",
file: "lorem_ipsum.txt";
},
dataType: 'text',
success:function(response){
console.log("received " + response);
}
});
Jquery will send your data as a standard post to your server side code.

Passing AJAX variables to a Jquery ui dialog on the same page

Right now I've got a ui dialog on a page, and I need some way to pass a javascript variable to the php within the dialog via AJAX. Here's my code:
$('.user').click(function(){
var user = getID($(this).attr('id'),'User');
$.ajax({
type: "POST",
url: "test.php",
data: 'user=' + user,
success: function(){
$("#dialog").dialog('open');
}
});
});
and the beginning of the PHP:
<?php
if(isset($_POST['user'])){
echo '<center><b>User: '.ucfirst($_POST['user']).'</b></center><br />';
}
The problem is, it's just not getting passed. I'm very new with Ajax so I'm sure I'm messing something up.
This is not working because you don't specify the return variable, see your code with correction:
$('.user').click(function(){
var user = getID($(this).attr('id'),'User');
$.ajax({
type: "POST",
url: "test.php",
data: 'user=' + user,
success: function(data){ // Here you specify the callback variable from the AJAX call
alert(data); // Here will show '<center><b>User: UserExample </b></center><br />';
$("#dialog").dialog('open');
}
});
});
You can make your dialog content my loading some page like Userpage.php and then pass User as a url parameter
$('.user').click(function(){
var user = getID($(this).attr('id'),'User');
$.ajax({
type: "POST",
url: "test.php",
data: 'user=' + user,
success: function(){
$("#dialog").load('/userpage.php?User=' + user).dialog('open');
}
});
});

Categories