How to upload image file with ajax? - php

problem when upload image MVC with ajax, i have controls_class.php content function upload_img_admin in class settings calling from page c_ajax_img.php
page c_ajax_img.php
include_once('controls_class.php');
$ajax_up_img = new settings;
$ajax_up_img->upload_img_admin(#$_FILES['file_upload']);
function upload_img_admin in class settings
function upload_img_admin()
{
$dir_name=dirname(__FILE__)."/upload/";
$path=#$_FILES['file_upload']['tmp_name'];
$name=#$_FILES['file_upload']['name'];
$size=#$_FILES['file_upload']['size'];
$type=#$_FILES['file_upload']['type'];
$error=#$_FILES['file_upload']['error'];
...
...
if( isset($_FILES['file_upload']) )
{
move_uploaded_file($path,$dir_name.$name);
...
...
echo "ok";
}
else
{
echo "File not found";
}
}
function ajax get data form and send to function previous for upload image
$(document).ready(function() {
$(".btn_upload_avatar").click(function(e) {
$('.msgerror').hide().fadeIn(1000).html( '<div class="loading"></div>');
e.preventDefault();
$.ajax({
type:"POST",
url: "../controls/c_ajax_img.php",
cache: false,
processData:false,
contentType: false,
data:$("#form_up_img").serialize(),
success: function (data)
{
if(data == 0){
$('.msgerror').addClass('msgerror_in2').html(data);
}else{
$('.msgerror').addClass('msgerror_in2').html(data);
}
}
});
});
});

Something like this might help you mate.. :)
$(document).ready(function () {
$('#UploadForm').on('submit',(function(e) {
$('.msgerror').hide().fadeIn(1000).html('<div class="loading"></div>');
e.preventDefault();
var formData = new FormData(this);
formData.append('file', input.files[0]);
$.ajax({
url: '../controls/c_ajax_img.php',
data: formData,
contentType: false,
type: 'POST',
processData: false,
success: function (data) {
console.log("success");
console.log(data);
},
error: function (data) {
console.log("error");
console.log(data);
}
});
});
});
FYI
FormData
ProcessData is set to false so that it prevents jQuery from automatically transforming the data into a query string

Related

Ajax getting 400 Bad Request when submitting Form only on Firefox

I have written a php code in wordpress to submit a form using ajax. It working fine on chrome but getting 400 Bad request on Firefox. This is my code:
jQuery(document).ready(function($){
jQuery( 'form[name="contact-me"]' ).on( 'submit', function(e) {
e.preventDefault();
var form_data = {};
$(this).serializeArray().forEach( function(element){
form_data[element.name] = element.value;
});
$.post(zt_send_form_obj.ajax_url, {
action: "zt_save_campain_form_data",
_ajax_nonce: zt_send_form_obj.nonce,
type: "POST",
contentType: 'application/json; charset=utf-8',
values: JSON.stringify(form_data),
}, function(data) {
if (data.success) {
if(data.data.info.message=='no'){
$('#myModal').show();
console.log('cod is in')
}
if(data.data.info.message=='yes'){
$('#CodeModal').show();
$('.the_cod_div').append('<span>'+data.data.info.code+'</span>');
console.log('data saved');
}
}
else{
console.log("not working");
}
});
});
});
Try this
$('form[name="contact-me"]').submit(function (e) {
e.preventDefault();
var form = $('#form_id')[0]; //set form id
var varform = new FormData(form);
varform.append("action", "zt_save_campain_form_data");
$.ajax({
url: ajaxurl,
type: 'POST',
dataType: 'json',
data: varform,
processData: false,
contentType: false,
cache: false,
crossDomain: true,
success: function (response) {
//if success do this...
console.log(response);
},
error: function (xhr, textStatus, error) {
console.log(xhr, textStatus, error);
}
})
});
Inside your form you can put this code for nonce validation
<?php wp_nonce_field( 'name_of_my_action', 'name_of_nonce_field' ); ?>

Wordpress ajax request not working properly

I am new to wordpress, i make a ajax request on click button and it print the data, but ajax is not giving me any response. Please help me to find out the error.
Here is my code
add_action("wp_ajax_delivery_options", "delivery_options");
add_action("wp_ajax_nopriv_delivery_options", "delivery_options");
function delivery_options()
{
echo json_encode(array('type' => 'success'));
wp_die();
}
wp_enqueue_script("my-ajax-handle", get_stylesheet_directory_uri() . "/js/custom.js", array('jquery'));
wp_localize_script('my-ajax-handle', 'the_ajax_script', array('ajaxurl' => admin_url('admin-ajax.php')));
Ajax
(function($) {
$(document).ready(function() {
$('#delivery_option button').on('click', function(e) {
e.preventDefault();
var data = e.currentTarget.id;
$.ajax({
type: 'POST',
dataType: 'json',
url: the_ajax_script.ajaxurl,
data: { delivery_option: data },
success: function(response) {
console.log(response);
}
});
});
});
})(jQuery);
Any solution appreciated!
you have to pass "callback function name" in data: { action: 'delivery_options', delivery_option: data },
(function($) {
$(document).ready(function() {
$('#delivery_option button').on('click', function(e) {
e.preventDefault();
var data = e.currentTarget.id;
$.ajax({
type: 'POST',
dataType: 'json',
url: the_ajax_script.ajaxurl,
data: { action: 'delivery_options', delivery_option: data },
success: function(response) {
console.log(response);
}
});
});
});})(jQuery);

Pass data from ajax to laravel 5.1 Controller in order to save to mysql?

I need to pass data from jquery (version 1.9.1) to my Controller (Laravel 5.1) and then save it to mysql.
How to do that and pass the variable slot? It didn't work so far. For any further details, please asked me.
jquery:
$(".tic").click(function(){
var slot = $(this).attr('id');
playerTurn(turn, slot);
$.ajax({
url: '/addhistory',
type: 'POST',
data: { _token: {{ csrf_token() }}, moves: slot },
success: function()
{
alert("Data has been saved successfully!");
}
});
});
Controller:
public function addhistory(Request $request)
{
$history = new History();
$history->game_id = Game::orderBy('id', 'desc')->first()->id;
$history->moves = $request->moves;
$history->save();
return redirect()->back();
}
Routes:
Route::post('/addhistory', 'GameController#addhistory');
Errors in console:
(index):198 Uncaught ReferenceError: HAmcYRScL9puItnUGbd2kHx.... is not defined
at HTMLAnchorElement.<anonymous> ((index):198)
at HTMLAnchorElement.dispatch (191.js:3)
at HTMLAnchorElement.v.handle (191.js:3)
191.js file is the jquery version of 1.9.1
You can use this code, it may works
$(".tick").click(function (event) {
event.preventDefault();
$('.loading').show();
var form = $(this);
var data = new FormData($(this)[0]);
var url = form.attr("action");
$.ajax({
type: "POST",
url: url,
data: data,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (data) {
alert("Data has been saved successfully.");
},
error: function (xhr, textStatus, errorThrown) {
alert(errorThrown);
}
});
return false;
});
Try this code-
$(".tic").click(function(){
var slot = $(this).attr('id');
var token= $("input[name='_token']").val();
playerTurn(turn, slot);
$.ajax({
url: '/addhistory',
type: 'POST',
data: { '_token': token, 'moves': slot },
success: function()
{
alert("Data has been saved successfully!");
}
});
});
And in your controller you don't need return redirect because the request is asynchronous. So I am returning true. Make sure you include History model at the top of your controller
public function addhistory(Request $request)
{
$game_id=Game::orderBy('id', 'desc')->first()->id;
History::create([
'game_id'=>$game_id,
'moves'=>$request->moves
]);
return true;
}

How to retrieve textbox value in a controller which is supplied with ajax?

I want to pass value of text box to my controller, i can pass that but i cant retrieve it at controller. Help me to identify my mistake.
Form.php (dept_name is a id of my textbox)
<script>
$(document).ready(function() {
$("#submitbutton").click(function(e) {
var deptname=$('#dept_name').val();
$.ajax({
url: 'http://localhost/finalProjectWork/admin_department_controller/adddept/',
type: 'POST',
method: 'POST',
headers: {'Cache-Control': 'no-cache'},
data: {name:deptname},
contentType: false,
processData: false,
success: function(test) {
alert(test);
},
error: function() {
alert("Already Exists");
}
});
e.preventDefault();
});
});</script>
controller :
public function adddept()
{
$deptname=$this->input->post('name');
$this->load->model('admin_department_model');
$this->admin_department_model->insertdept($deptname);
echo "Successfully inserted";
}
Try this
<script>
$(document).ready(function() {
$("#submitbutton").click(function(e) {
var deptname=$('#dept_name').val();
$.ajax({
url: 'http://localhost/finalProjectWork/admin_department_controller/adddept/',
type: 'POST',
method: 'POST',
headers: {'Cache-Control': 'no-cache'},
data: {name:deptname},
success: function(test) {
alert(test);
},
error: function() {
alert("Already Exists");
}
});
e.preventDefault();
});
});</script>

Upload file via ajax jquery php api

I am having the code with the below format.
PHP file :
<form action="http://clientwebapi.com/createEvent" id="form_createEvent" method="post" enctype="multipart/form-data">
<input type="text" name="image_title" />
<input type="file" name="media" accept="image/*,video/*"/>
</form>
JQUERY file:
$('#form_createEvent').submit(function () {
var form = $(this);
$.ajax({
url: form.attr("action"),
type: form.attr("method"),
xhrFields: {
withCredentials: true
},
data: form.serialize()
}).done(function () {
showCurrentLocation();
alert('Event created successfully..');
location.reload();
}).fail(function () {
alert("fail!");
});
event.preventDefault();
});
The above Jquery code is submitting. Also While I am submitting the below format, It will redirect to the "http://clientwebapi.com/createEvent" and Event created successfully.
Form Submit and redirect to client page:
$('#form_createEvent').submit(function () {
var fd = new FormData();
fd.append('media', input.files[0]);
$.ajax({
url: form.attr("action"),
data: fd,
processData: false,
contentType: false,
type: form.attr("method"),
success: function (data) {
alert(data);
}
});
event.preventDefault();
});
Here How can I prevent while submit the form and create the event with the given image. Kindly help
You forgot to add event as argument to the submit function:
$('#form_createEvent').submit(function (event) {
I found the Answer for this. I made some mistake here. I resolved by using the below code..
$('#form_createEvent').submit(function() {
var form = new FormData($(this)[0]);
$.ajax({
url: 'http://clientwebapi.com/createEvent/',
type: 'POST',
xhrFields: {
withCredentials: true
},
async: false,
cache: false,
contentType: false,
processData: false,
data: form,
beforeSend: function () {
$("#output_process").html("Uploading, please wait....");
},
success: function () {
$("#output_process").html("Upload success.");
},
complete: function () {
$("#output_process").html("upload complete.");
},
error: function () {
//alert("ERROR in upload");
location.reload();
}
}).done(function() {
alert('Event created successfully..');
}).fail(function() {
alert("fail!");
});
event.preventDefault();
});
you can stop the form submission by return false;
$('#form_createEvent').submit(function () {
// some code
$.ajax({
// some code/objects
});
return false; // here, it will stop the form to be post to the url/action
});

Categories