Ajax Form Submission with Files - php

I have a form that is handled via $.post, sending data to a php script. My client just asked me to include the ability to upload an image using this (and a few other) forms.
I have been googling around on this for about an hour, and haven't seen any evidence that you can actually do this using $.post(), so I wanted to reach out and see if there is a way to do this.
the form is handled this way:
jQuery( '.js-saveProduct' ).click(function(e) {
e.preventDefault();
acSaveProduct( jQuery(this).serializeArray() )
};
var acSaveProduct = function( form ) {
var _data = {
action: 'ac_save_product',
form: JSON.stringify( form )
}
jQuery.post(
ajaxscript.ajaxurl,
_data,
function( response ) {
// Do Stuff
}
);
};
If I console.log(form) after acSaveProduct() is called, the upload fields aren't even in the array of objects that gets logged.
I haven't even started on the PHP side of this, as I know that the form object that gets passed to my PHP function doesn't contain the values I am looking for.
EDIT TO SHOW NEW ATTEMPT
So, trying the technique linked by #Andreas, I'm still having trouble with this. Below is my update jQuery / PHP code:
HTML
<input type="file" name="acImageNew" id="acImageNew">
jQuery
var acSaveProductAlt = function( form ) {
var file_data = jQuery( '#acImageNew' ).prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
alert(form_data);
jQuery.ajax({
url: the_ajax_script.ajaxurl,
dataType: 'json',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
action: 'ac_ajax_save_product_alt',
success: function( response ) {
alert(JSON.parse(response.success));
}
});
};
PHP
function ac_ajax_save_product_alt(){
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}
$response = json_encode(
array(
'success' => true,
)
);
header( "Content-Type: application/json" );
echo $response;
exit;
}
At the end of it all, I get an alert with 0 as the contents of the alert. What am I doing wrong?

Try JSON parsing the response first, then accessing the success key.
jQuery.ajax({
url: the_ajax_script.ajaxurl,
dataType: 'json',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
action: 'ac_ajax_save_product_alt',
success: function( response ) {
alert(JSON.parse(response).success);
}
});

Related

Need help converting the ajax and php for wordpress

From guides I have gotten this far:
add_action('wp_enqueue_scripts', 'do_enqueue_scripts');
function do_enqueue_scripts()
{
wp_enqueue_script('Java', plugins_url( '/js/form.js', __FILE__ ), array('jquery'), '1.0', true);
wp_localize_script( 'Java', 'start', array(
'code' => admin_url( 'admin-ajax.php' )
));
}
add_action('wp_ajax_nopriv_func', 'func');
add_action('wp_ajax_func', 'func');
function func()
{
$From = $_POST['dateTo'];
$To = $_POST['dateFrom'];
$Name = $_POST['Name'];
echo $From . " - " . $To . " - " . $Name;
die();
}
$("#form").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: start.code,
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data) {
alert(data);
}
});
}));
My problem comes in with the AJAX call. I am still getting used to this action system WordPress is using and I am not sure what I need to change my data to. I have a generic form with 2 dates and a name; nothing crazy. However the returned data to my AJAX call is zero.
I believe my issue now is how I m either returning data to my ajax or with the data type I am send to my PHP function func().
No errors in chrome or mozilla consoles.
Add a hidden input field to your form with the name of the action so wp can execute the right function
<input type="hidden" name="action" value="func">
change your ajax to:
$("#form").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: start.code,
type: "POST",
data: $(this).serialize(),
cache: false,
success: function(data) {
alert(data);
}
});
}));

Jquery function cant access json object

I'm using bootstrap validator to validate my form data. If form is validated I'm posting those data to php. In php I'm returning json string. Even though my post is success and get correct response, I can't access json object.
$('#dealForm')
.bootstrapValidator({
message: 'This value is not valid',
fields: {
deal_description: {
message: 'The deal discription is not valid',
validators: {
notEmpty: {
message: 'The deal discription is required and can\'t be empty'
}
}
}
}
})
.on('success.form.bv', function(e) {
// Prevent form submission
e.preventDefault();
// Get the form instance
var formObj = $(e.target);
var formURL = formObj.attr("action");
$.ajax({
url: formURL,
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
dataType:JSON
}).done(function(data) {
console.log(data);
});
});
debugger output
php
$temp= $_POST['deal_description'];
if(!empty($_FILES['userfile']['name'])){$temp2='has';} else $temp2='no has';
echo json_encode(array(
'message' => $temp,
'test' => $temp2
));
Either set the correct header in php:
header('Content-Type: application/json');
echo json_encode(array(
'message' => $temp,
'test' => $temp2
));
Or use JSON.parse in js:
}).done(function(data) {
data = JSON.parse(data);
console.log(data);
alert(data.mesage);
});
EDIT just noticed you also have a spelling mistake in your js. data.mesage should have two s data.message
Try
.done(function(data) {
var res=$.parseJSON(data);
alert(res.message);
});
Your AJAX request is wrong I think. It should be
function getData(){
$.ajax({
url: formURL,
type: "POST",
data: new FormData(this),
contentType: 'application/json; charset=utf-8',
cache: false,
dataType: 'json'
}).success(function (data) {
console.log(data);
workWithData(data);
}).done(function(e){
console.log("I'm done");
});
}
function workWithData(data){
if (typeof data != 'undefined') {
var jsonData = $.parseJSON(data);
// do stuff with data
}
}
The reason for having it in a second function is that it is a callback. We don't know how long the AJAX request might take, so we must not interrupt execution of the page whilst waiting for a response. By using a callback, when the data eventually arrives it will be processed.
I'd like to recommend you go through this to learn more about AJAX requests http://api.jquery.com/jquery.ajax/

$.ajax POST is not posting

This is exactly what the title describes, when I hit submit, and use php file to echo the result its empty.
$( "form#fileupload" ).on( "submit", function( event ) {
event.preventDefault();
var formData = $( 'form#fileupload' ).serialize();
$.ajax({
url: 'create_adgroup.php',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (returndata) {
$("#footer").html(returndata);
}
});
return false;
});
and the php is as such:
ECHO "PRINT POST: ".print_r($_POST);
echo "le titre: ".$_POST['title'];
any suggestions please the alert returns the serialized string and it has all the data and title is one of them.
Try with this, usually i did the ajax POST with this kind of code:
$( "form#fileupload" ).on( "submit", function( event ) {
$.post('create_adgroup.php', $('form#fileupload').serialize(), function(data) {
$('#footer').html(data);
});
event.preventDefault();
return false;
});
For uploading file using ajax I prefer using jquery.form.js plugin.
Reference

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.

On click get JSON data into DIV

On click I am trying to get data from JSON via an URL into a <div>.
My JSON returns a single id and content I am trying to get content into div #west-container.
Can someone tell me what I am doing wrong?
My JSON Found at the url = [{"id":"2","title":"Generic Overview","content":"This is content here"}]
$('#jqxTree').bind('select', function (event) {
var loadPages = jQuery.parseJSON(
jQuery.ajax({
url: 'university/article/3',
async: false,
dataType: 'json'
}).responseText
);
for(i=0; i < loadPages.length ; i++){
var current = loadPages;
$("#west-container").load(current.content);
}
});
You can try this one:
$('#jqxTree').bind('select', function (event) {
jQuery.ajax({
url: 'university/article/3',
async: false,
dataType: 'json',
success:function(data){
$.each(data, function(i, item){
$("#west-container").html(item.content);
}); //-----------------^^^^^^^^^^^^---This will fetch you the
} //--------------------------------content from json
}); //-------------------------"content":"This is content here"
});
use
$.ajax({
url: "url",
type: 'POST',
contentType: 'application/json; charset=utf-8',
data:json,
dataType:'text',
async: false,
}).done(function( data1 ) {
data=jq.parseJSON(data1);
});
in order to use the data, use "data.id, data.title" etc.
in order to push data to a div, use
$('#DivId').test(data.id);
$.getJSON( 'university/article/3', function(data) {
// Do stuff here
var oDiv = $( 'west-container' ).html( '' );
for( var i in data ) {
oDiv.append( data[i].content );
}
} );

Categories