admin-ajax.php 400 bad request problem (Wordpress) - ajax

I want to filter the data I pulled from the table with wordpress by date.
<script>
$(document).ready(function(){
var ajaxscript = 'http://localhost/wp-admin/admin-ajax.php'; //absolute ref for testing
$.datepicker.setDefaults({
dateFormat: 'yy-mm-dd'
});
$(function(){
$("#from_date").datepicker();
$("#to_date").datepicker();
});
$('#filter').click(function(){
var from_date = $('#from_date').val();
var to_date = $('#to_date').val();
if(from_date != '' && to_date != '')
{
$.ajax({
method: "POST",
url: ajaxscript,
dataType: 'json',
data:{from_date:from_date, to_date:to_date},
success:function(data)
{
$('#order_table').html(data);
}
});
}
else
{
alert("Please Select Date");
}
});
});
The value code I want to send is as follows:
<div class="col-md-3">
<input type="text" name="from_date" id="from_date" class="form-control" placeholder="From Date" />
</div>
<div class="col-md-3">
<input type="text" name="to_date" id="to_date" class="form-control" placeholder="To Date" />
</div>
<div class="col-md-5">
<input type="button" name="filter" id="filter" value="Filter" class="btn btn-info" />
</div>
But I keep getting POST http://localhost/wp-admin/admin-ajax.php 400 (Bad Request) error.

Related

My previously edited data is edited again when I update second data in codeigniter using ajax

I am using codeigniter framework to develop my project. I am also using AJAX to edit the data. When I edit the first data it is being edited correctly but when I am updating the second data without refreshing the browser then previous edited data or current editing data both are updated with new result. Please solve my problem. Thanks in advance.
function editFunction(id)
{
$.ajax({
url: "edit_result/" +id,
data: {id:id},
type: "post",
async: false,
dataType: 'json',
success: function(response){
$('#reg_no').val(response.reg);
$('#total_marks').val(response.tot_marks);
$('#grade').val(response.grade);
},
error: function()
{
alert("error");
}
});
$('#updateBtn').click(function(event){
event.preventDefault();
var grade_id = document.getElementById("grade").value;
var total_id = document.getElementById("total_marks").value;
if(grade_id=='' || total_id=='')
{
$('#updateBtn').prop('disabled',true);
setTimeout(function(){document.getElementById("updateBtn").disabled = false;},2000);
$('.message').html('Please fill all fields').fadeIn().delay(1000).fadeOut('slow');;
}
else
{
$.ajax({
url: "edit_result_valid/" +id,
data: $(this).serialize(),
type: "post",
async: false,
dataType: 'json',
success: function(response){
alert('success');
},
error: function()
{
alert("error");
}
});
}
});
}
I am performing edit operation on modal. Please check also HTML code
<div class="modal fade" id="editModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span></button>
<h2 class="modal-title">Edit Result</h2>
<p class="message" style="color: red;"></p>
</div>
<div class="modal-body">
<form role="form" id="updateForm">
<div class="box-body">
<div class="form-group">
<label for="exampleInputEmail1">Reg No :</label>
<input type="text" class="form-control" id="reg_no" readonly="">
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label>Total Marks :</label>
<input type="number" class="form-control" id="total_marks" placeholder="Enter total marks" onfocus="colorFunction(this)" name="tot_marks">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label>Grade</label>
<?php
$firstItem[''] = 'Please select one...';
$options = array(
'A++' => 'A++ (90% & above)',
'A+' => 'A+ (80% to 89%)',
'A' => 'A (60% to 79%)',
'B+' => 'B+ (50% to 59%)',
'B' => 'B (40% to 49%)',
);
$options = array_merge($firstItem, $options);
$selected_option = $this->input->post('grade', TRUE);
echo form_dropdown('grade', $options,$selected_option,['class'=>'form-control','id'=>'grade','onfocus'=>'colorFunction(this)']); ?>
</div>
</div>
</div>
</div>
<!-- /.box-body -->
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger pull-left" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-success pull-right" data-dismiss="modal" id="updateBtn">Update</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
I have got an answer of my question. I am using off('click') in code you can see update code below.
$('#updateForm').off('click','#updateBtn').on('click','#updateBtn',function(event){
event.preventDefault();
var grade_id = document.getElementById("grade").value;
var total_id = document.getElementById("total_marks").value;
if(grade_id=='' || total_id=='')
{
$('#updateBtn').prop('disabled',true);
setTimeout(function(){document.getElementById("updateBtn").disabled = false;},2000);
$('.message').html('Please fill all fields').fadeIn().delay(1000).fadeOut('slow');;
}
else
{
$.ajax({
url: "edit_result_valid/" +id,
data: $("#updateForm").serialize(),
type: "post",
async: false,
dataType: 'json',
success: function(response){
if(response=='1')
{
$('.alert-success').show();
$('.alert-success').html('Result Updated Successfully').fadeIn().delay(4000).fadeOut('slow');
$('#example1').DataTable().ajax.reload();s
}
},
error: function()
{
alert("error");
}
});
}
});
play a game at view first. i guess you are not using primary key of db to update. let me explain.
at view:
at one more input element which type is hidden and has value your primary key . assign it an id having value tbl_id example
<input type="hidden" value="<?php echo {variable that has your primary key } ?>" id="tbl_id" >
and at ajax call before you start writing it
var id = $("#tbl_id").val();
when you call controller check you have id available or not
next you are going to call a model to update.
that is where your other all data get update.
when you are going to call model use statement before it
if($id != '') { // $id is what you have shared via ajax call
$this->model_name->update_function($id,$array); // $array is all other fields as per codeigniter need
} else { echo "unable to capture id"; exit; }
and last you update model..
all done by ajax :)

Cannot read multipart/form-data from request in Laravel

I am trying to send form with upload file and multipart/form-data encoding using AJAX. I am using this form:
{!! Form::model($user, ['method' => 'PATCH', 'url' => ['/administrator/users', $user->id], 'class' => 'form-horizontal', 'files' => 'true', 'id' => 'userEdit']) !!}
<div class="modal-body">
<div class="form-group">
<label class="col-sm-3 control-label">Avatar:</label>
<div class="col-sm-9">
<img src="/dashboard/assets/img/avatar/{{ $user->profile->avatar }}" class="img-circle m-b" />
<input type="file" name="avatar" />
</div>
</div>
<hr />
<div class="form-group">
<label class="col-sm-3 control-label">Name:</label>
<div class="col-sm-9">
<input type="text" name="first_name" value="{{ $user->profile->first_name }}" class="form-control" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Surname:</label>
<div class="col-sm-9">
<input type="text" name="last_name" value="{{ $user->profile->last_name }}" class="form-control" />
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-info" data-user-id="{{$user->id}}">Save</button>
</div>
{!! Form::close() !!}
I try to send data with Ajax like this:
$('#editUser').submit('#userEdit', function(event) {
event.preventDefault();
$.ajax({
type: 'PATCH',
url: '/administrator/users/1',
data: new FormData(userEdit),
processData: false,
contentType: false,
mimeType: "multipart/form-data",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function(data) {
alert(data);
},
error: function(xhr, str){
alert(str);
}
});
});
And in result, I cannot read inputs from request in controller. It returns an empty array.
public function update($id, Request $request){
dd($request->all());
}
I think that I'm doing something wrong with sending multipart data. How to send it correctly?
It seems that you aren't adding FormData properly and your event seems to be broken, you should add the data in ajax like this:
$('#editUser').on('submit', function(event) {
event.preventDefault();
var form = $(this); // You need to use standard JS object here
var formData = new FormData(form);
$.ajax({
type: 'PATCH',
url: '/administrator/users/1',
data: formData,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function(data) {
alert(data);
},
error: function(xhr, str){
alert(str);
}
});
});
Hope this helps!

Two ajax call for two forms, latter not working

I've tried everything. The form posts fine when not using Ajax, I switch the places so it would be first, I deleted everything and just gave it an alert to show when clicking submit... I can't pin-point the problem.
The second ajax just won't submit!
$(document).ready(function() {
$('#writeform').submit(function(event) {
var formData = {
'from': $('input[name=from]').val(),
'to': $('input[name=to]').val(),
'textbox': $('input[name=textbox]').val()
};
$.ajax({
type: 'POST',
url: 'process.php',
data: formData,
dataType: 'json',
encode: true
})
.done(function(data) {
console.log(data);
});
event.preventDefault();
});
});
// ajax the login
$(document).ready(function() {
$('#loginform').submit(function(event) {
var formData = {
'username': $('input[name=username]').val(),
'pass': $('input[name=pass]').val()
};
$.ajax({
type: 'POST',
url: 'login.php',
data: formData,
dataType: 'json',
encode: true
})
.done(function(data) {
console.log(data);
});
event.preventDefault();
});
});
function loadLogDiv(){
$("#logfunction").load("login.php");
}
$(document).ready(function () {
$.ajaxSetup({
cache: false
});
loadLogDiv();
setInterval( loadLogDiv, 4000);
});
Heres the page itself:
<div id="loginpage">
<form id="loginform" action="login.php" method="POST">
<div id="username">
<label for="username">User Name</label>
<input type="text" name="username" placeholder="User Name" />
<!-- errors will go here -->
</div>
<div id="pass">
<label for="pass">Password</label>
<input type="password" name="pass" placeholder="Password" />
<!-- errors will go here -->
</div>
<input type="submit">Submit</input>
</form>
<div id="logfunction"></div>
</div>
<div id="footer">
<form id="writeform" action="process.php" method="POST">
<div id="from">
<label for="from">From</label>
<select name="from">
<?php
$result = mysqli_query($conn, "SELECT user_name FROM `users`");
while($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['user_name'] . "'>" . $row['user_name'] . "</option>";
}
?>
</select>
</div>
<div id="to">
<label for="to">To</label>
<select name="to">
<?php
$result = mysqli_query($conn, "SELECT user_name FROM `users`");
while($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['user_name'] . "'>" . $row['user_name'] . "</option>";
}
?>
</select>
</div>
<div id="textbox">
<label for="textbox">Text</label>
<input type="text" name="textbox" placeholder="text" />
</div>
<input type="submit">Submit</input>
</form>

laravel 5.1 formData - AJAX - PHP- Uploading multiple files

I can not get the formData from the file upload
form.blade.php
<form method="POST" class="form-horizontal" enctype="multipart/form-data" id="modal-file-upload">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="hidden" name="folder" value="" id="modal-file-upload-folder">
<div class="modal-header">
<h4 class="modal-title">Upload New File</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="file" class="col-sm-3 control-label">
File
</label>
<div class="col-sm-8">
<input multiple="true" accept="image/*" required="true" id="fileToUpload" type="file" name="file[]">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" onclick="close_upload_view()">Cancel</button>
<button class="btn btn-primary" id="btn-upload">Upload File</button>
</div>
</form>
Controller
public function uploadMultiFile(Request $request) {
// getting all of the post data
$data = $request->input('formData');
var_dump($data); current return null
}
<script>
// Confirm file delete
function close_upload_view() {
$("#modal-file-upload").modal("hide");
return false;
}
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
$("#modal-file-upload").submit(function(e){
e.preventDefault();
//var formData = new FormData(document.getElementById('modal-file-upload')[0]);
var fd = new FormData();
var ins=document.getElementById('fileToUpload').files.length;
for(var x=0;x<ins;x++)
{
fd.append("fileToUpload[]", document.getElementById('fileToUpload').files[x]);
}
var folder = $("input#modal-file-upload-folder").val();
var token = $("input[name=_token]").val();
var dataString = 'formData='+fd+'&folder='+folder+'&token='+token;
$.ajax({
type: "POST",
url: '{!! url() !!}/admin/upload/multifile',
cache: false,
data : dataString,
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server it
dataType: 'JSON',
success : function(data){
console.log(data);
}
},"json");
});
</script>

how to get the start date in date range picker?

How to get the start date just like here in the picture.
that is something like this?
date:$('#reservation')daterangepicker.val.startDate()
here is the form
<form id="form4">
<div class="modal-body">
<div class="form-group">
<label>Date range:</label>
<div class="input-group">
<div class="input-group-addon">
<i class="fa fa-calendar"></i>
</div>
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="text" class="form-control pull-right" id="reservation" name="reservation"/>
</div><!-- /.input group -->
</div><!-- /.form group -->
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal"><i class="fa fa-remove"></i> <span>Close</span></button>
<button type="submit" type="button" class="btn btn-outline"><i class="fa fa-check"></i> <span>Search</span></button>
</div>
</form>
and here is the ajax
<script type="text/javascript">
$(function () {
//Datemask dd/mm/yyyy
$("#datemask").inputmask("dd/mm/yyyy", {"placeholder": "dd/mm/yyyy"});
//Date range picker
$('#reservation').daterangepicker();
});
$("#form4").submit(function(){
$("#submit").prop('disabled', true);
$.ajax({
url:'{{ url('dashboard/add1') }}',
type: 'get',
data: {date:$('#reservation').daterangepicker.val.startDate()},
dataType:"json",
success: function(data){
if(!data.success)
{
alert('failed');
}
else
{
alert('success');
}
}
});
return false;
});
</script>
any replies will be appreciated. thank you.
Can't find any source in the internet regarding this. I hope it is possible.
i've sliced it
id= reservation value="2015-05-06, 2015-05-26"
data: {
startDate:$('#reservation').val().slice(0,10)+' 00:00:00',
endDate :$('#reservation').val().slice(12,22)+' 23:59:59'
},
startDate gives : 2015-05-06 00:00:00
endDate gives : 2015-05-26 23:59:59

Resources