Schedule Downtime for a Service in Nagios using ajax POST - ajax

I'm trying to schedule a downtime for the service in nagios using ajax call. I can able to schedule it through NAgios GUI and found a method to use curl for scheduling.
I Found one link How to set downtime for any specific nagios host for certain time from commandline through curl? which explains how to achieve it through curl command.
I tried to achieve it through curl command.
curl \
--data cmd_typ=56 \
--data cmd_mod=2 \
--data host=jenkins \
--data "service=Jenkins+PROD+GUI" \
--data "com_author=Nagios Admin"\
--data "com_data=Test" \
--data trigger=0 \
--data "start_time=05-09-2018+14%3A05%3A14" \
--data "end_time=05-09-2018+16%3A05%3A14" \
--data fixed=1 \
--data btnSubmit=Commit \
http://xx.xx.xx:8087/nagios/cgi-bin/cmd.cgi -u "nagiosadmin:nagiosadmin"
It works fine.
I tried to convert the same curl functionality to ajax post call.
HTML :
<form name="NAME" id="avialform" class="avail" action="">
<fieldset id="availfield">
<legend style="color:white" id="availegend">SCHEDULED DOWNTIME</legend>
<table width="100%" cellpadding="0" cellspacing="0" class="vzuui-detailpanel">
<tr>
<td><label>Service :</label>
<select id = "ServiceList">
<option value = "Jenkins+PROD+GUI">Jenkins Prod</option>
</select>
</td>
</tr>
<tr>
<td><label>From Date :</label><input id="from" type="datetime-local" name="fromdate" /></td>
</tr>
<tr>
<td><label>To Date :</label><input id="to" type="datetime-local" name="todate" /></td>
</tr>
<tr>
<td><label>Comment :</label><input id="comment" type="text" name="Servicecommt" /></td>
</tr>
</table>
</fieldset>
<button class="vzuui-btn-red-active" type="button" id="getrepo">Submit</button>
</form>
Ajax:
var posdata = {"cmd_typ":56,"cmd_mod":2,"host":"jenkins","service":"Jenkins+PROD+GUI","com_author":"Nagios Admin","com_data":"Test","trigger":0,"start_time":"2018-05-09T18:00","end_time":"2018-05-09T19:00","fixed":1,"btnSubmit":"Commit"}
posdata["service"] = select.options[select.selectedIndex].value;
posdata["com_data"] = document.getElementById("comment").value;
posdata["start_time"] = document.getElementById("from").value;
posdata["end_time"] = document.getElementById("to").value;
console.log(JSON.stringify(posdata));
$.support.cors = true;
$.ajax({
url: "http://xx.xx.xx:8087/nagios/cgi-bin/cmd.cgi",
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization',
make_base_auth("nagiosadmin", "nagiosadmin"));
},
type: 'POST',
dataType: 'json',
contentType: 'application/json',
processData: false,
data: posdata,
success: function (data) {
alert(JSON.stringify(data));
},
error: function(){
alert("Cannot get data");
}
});
But I got 500 Internal Server Error. Kindly guide me to achieve this using ajax.

Seems like the data is supposed to be sent as a form and not as json. Remove contentType: 'application/json' and it should work
contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8')
Type: Boolean or String
When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded;
http://api.jquery.com/jquery.ajax/
Edit-1: 09-May-2018
You should update your code as below
var posdata = {
"cmd_typ": 56,
"cmd_mod": 2,
"host": "jenkins",
"service": "Jenkins+PROD+GUI",
"com_author": "Nagios Admin",
"com_data": "Test",
"trigger": 0,
"start_time": "2018-05-09T18:00",
"end_time": "2018-05-09T19:00",
"fixed": 1,
"btnSubmit": "Commit"
}
posdata["service"] = select.options[select.selectedIndex].value;
posdata["com_data"] = document.getElementById("comment").value;
posdata["start_time"] = document.getElementById("from").value;
posdata["end_time"] = document.getElementById("to").value;
console.log(JSON.stringify(posdata));
$.support.cors = true;
$.ajax({
url: "http://xx.xx.xx:8087/nagios/cgi-bin/cmd.cgi",
beforeSend: function(xhr) {
xhr.setRequestHeader('Authorization',
make_base_auth("nagiosadmin", "nagiosadmin"));
},
type: 'POST',
data: posdata,
success: function(data) {
alert(JSON.stringify(data));
},
error: function() {
alert("Cannot get data");
}
});
The will make sure that data goes as application/x-www-form-urlencoded and also jQuery checks the response and decides the types

Related

How to send other variable datas along with new FormData() inside AJAX?

Here I am sending the upload files into FormData() to be accessed in expressjs. And it is working perfectly.
$(".commonForm").submit(function (e) { //For Submitting the Uploaded Files
e.preventDefault();
if(validateForm($(this).attr('name'), text))
{
$.LoadingOverlay("show");
var formData = new FormData(this);
$.ajax({
type: "POST",
url: $(this).attr('action'),
data: formData,
processData: false,
contentType: false,
dataType: "json",
success: function(response){
if (response.status == '200') {
$.LoadingOverlay("hide");
swal({
title: "Excellent!",
text: "Files submitted successfully!",
icon: "success",
button: "Ok",
showCancelButton: true
}).then((result) => {
if (result) {
window.location.reload();
}
});
}
},
error: function (e) {
console.log("some error", e);
}
});
}
});
But along with that I want to send one another field data along with formData.
var text = 'Done';
How to send this along with formData in data ?
I am trying this:
data : {
formData:formData,
text:text
}
But then I don't think that I will be able to retrieve the uploaded files data directly with req.files
UPDATE:
route code/expressjs
router.post('/api/upload/:cid',function(req,res,next){
console.log("req.body.text = " + req.body.text + req.query.text);
upload2(req,res,function(err) {
if(err) {
console.log("Error is important = "+ err);
}
else
{
console.log("Uploaded successfully.");
}
})
})
MULTER CODE:
var upload2 = multer({storage: storage2, limits: { fileSize: 1024 * 1024 * 1 }}).array('FileUploadForClient',4);
HTML HANDLEBAR FORM CODE:
<form name="{{this.status}}" class="commonForm" enctype="application/x-www-form-urlencoded" action="/api/upload/{{this.commonID}}" method="post">
<td class="col-sm-2">
<div class="center">
<select name="sourcesSelect" id="{{this.commonID}}" data-notUse="{{this._id}}" data-Id4AddtasksBigpaths="{{this.Id4AddtasksBigpaths}}" class="custom-select sources" placeholder="{{this.status}}" style="font-size:20px; background: {{this.background}}; color: white;" {{this.statusDisabled}}>
<option value="0" >In Progress</option>
<option value="1" >Done</option>
<option value="2" >Rejected</option>
</select>
</div>
</td>
<!-- <td class="col-sm-2"><span id="deadline" style="font-size:14px"><input type="text" class="form-control" value="{{this.deadline}}" readonly/></span></td> -->
<td class="col-sm-1">
<!-- <input type="file" class="btn btn-light" name="FileUploadForClient" multiple required/> -->
<input type="file" id="{{this._id}}" class="form-control" name="FileUploadForClient" multiple required {{this.statusDisabled}} />
</td>
<td>
<button type="submit" class="btn btn-primary btn-block col-sm-2" style="font-size:16px" {{this.statusDisabled}}>Submit</button>
</td>
</form>
Use the method append to add another parameter to the request
var formData = new FormData(this);
formData.append('text', 'text to send in the request ');

Rust Hyper CORS Policy error on Ajax GET request

I am working to get the JSON response from the Rust Hyper Server using the AJAX. Here is the Rust code.
extern crate hyper;
extern crate futures;
#[macro_use]
extern crate serde_json;
use hyper::{Body, Response, Server, Method, StatusCode};
use hyper::service::service_fn_ok;
use futures::Future;
fn main() {
let router = || {
service_fn_ok(|req| {
match(req.method(), req.uri().path()) {
(&Method::GET, "/") => {
Response::new(
Body::from(
json!([{
"id": "01",
"Name": "faheem"
},
{
"id": "02",
"Name": "waseem"
}]).to_string()
)
)
},
(_, _) => {
let mut res = Response::new(Body::from("not found"));
*res.status_mut() = StatusCode::NOT_FOUND;
res
}
}
})
};
let addr = "127.0.0.1:3000".parse().unwrap();
let server = Server::bind(&addr).serve(router);
hyper::rt::run(server.map_err(|e| {
eprintln!("server error: {}", e);
}));
}
The Ajax code. This code is working fine and well with NodeJS server. By just adding the header Access-Control-Allow-Origin in the middle ware. But, in the rust hyper environment I could find any documentation which will help to add the Access-Control-Allow-Origin in the Server environment of Hyper.
<script>
$(document).ready(function () {
BindTable();
$("#btnSend").click(function () {
$.ajax({
crossDomain: true,
url: "http://localhost:3000/add",
type: "POST",
contentType: 'application/json',
data: JSON.stringify({
'student': $('#student').val(),
}),
success: function(data){
console.log(data);
$("#tbDetails").text("");
BindTable();
}
});
});
});
function BindTable()
{
$.ajax({
type: 'GET',
async: false,
headers: {
'Access-Control-Allow-Origin': 'http://localhost:3000/'
},
crossDomain: true,
url: "http://localhost:3000/",
contentType: "application/json",
dataType: "json",
success: function (msg) {
console.log(msg);
$.each(msg, function (index) {
var row = '<tr><td> ' + msg[index].id + ' </td> <td> ' + msg[index].name + ' </td></tr>';
$("#tbDetails").append(row);
});
}
});
}
</script>
<label for="student">Add student</label>
<input id="student" name="student" type="text" value="" />
<input id="btnSend" type="button" value="Send" />
<table id="tbDetails" border="1" cellpadding="2">
<tr>
<td>ID</td> <td>Name</td>
</tr>
<tbody>
</tbody>
</table>
The error
You should add Access-Control-Allow-Header entry in the HTTPResponse settings of the server you have hosted. Further in your code in Ajax request the header value is commented after http. Close this entry in double quotation.

Laravel Ajax delete record with button

I do not understand why it does not work:
Route
Route::delete('/dashboard/booking/deletebooking/{id}','ResourceController#deletebooking')->name('works.deletebooking');
ResourceController
public function deletebooking($id){
$booking = Booking::where('id','=',$id)->get();
$booking->delete();
return response()->json(['success' => true],200);
}
Table
<tr id="{{$booking->id}}">
<td class="roomId">{{$booking->room_id}}</td>
<td class="roomName">{{$booking->name}}</td>
<td class="roomLocation">{{$booking->sede}}</td>
<td class="start">{{$booking->start_date}}</td>
<td class="end">{{$booking->end_date}}</td>
<td>
<input type="hidden" name="_method" value="delete" />
<button class="btn btn-danger btn-xs" id="destroy" data-id="{{$booking->id}}" data-token="{{ csrf_token() }}">
<span class="glyphicon glyphicon-trash"></span>
</button>
</td>
</tr>
Request Ajax
$(".btn").click(function(){
var id = $(this).data('id');
// var $tr = $(this).closest('tr');
$.ajax({
url: "/dashboard/booking/deletebooking/"+id,
dataType: "JSON",
type: 'POST',
data: {
'_token': $('meta[name=csrf-token]').attr("content"),
'_method': 'DELETE',
"id": id
},
success: function ()
{
console.log("it Work");
}
});
console.log("It failed");
});
I have this error:
Request URL: http://pickbooking.local/dashboard/booking/deletebooking/1
Request Method: POST
Status Code: 500 Internal Server Error
Remote Address: 192.168.10.10:80
The issue is in the method used for the ajax call post
// var $tr = $(this).closest('tr');
$.ajax(
{
url: "/dashboard/booking/deletebooking/"+id,
dataType: "JSON",
type: 'POST',
data: {
'_token': $('meta[name=csrf-token]').attr("content"),
'_method': 'DELETE',
"id": id
},
success: function ()
{
console.log("it Work");
}
});
the data will be sent in the body of the request, and in a DELETE request, there is no body. so laravel wont see the _method, or the _token. Either you send them in a GET request and let the _method do it's job (it will be in the url, not in the body), Or use the DELETE method in the ajax call
// var $tr = $(this).closest('tr');
$.ajax(
{
url: "/dashboard/booking/deletebooking/"+id,
dataType: "JSON",
type: 'DELETE',
data: {
'_token': $('meta[name=csrf-token]').attr("content"),
},
success: function ()
{
console.log("it Work");
}
});
Because I think you have an error something like
Method Illuminate\Database\Eloquent\Collection::delete does not exist.
Instead try something like this
$booking = Booking::where('id', '=', $id)->first();
$booking->delete();
so that $booking can have method delete()

Fetching name based on id in ajax

In the console,I am getting name based on id.How to bind that name into the html page.
Here is my code..
function getEventname(){
var clid=$('#eventid').val();
console.log("i am ok" + clid);
$.ajax({
type: "GET",
url: "EduManage.jsp",
data: {
control:'ajax',
ch:'1',
key:'1_0a1m_1',
eventid:clid
},
success: function(data) {
console.log("i am ok" + data);
(what to do to bind the name in the html page)
}
});
}
Now the HTML is;
<td class="bg1">
Event Id :
</td>
<td class="bg1" width="25%">
<input name="eventid" type="text" id="eventid" size="10" maxlength="10" onblur="getEventname()"/>
</td>
<td class="bg1" width="40%">
Event Name :
</td>
<td class="bg1" width="25%">
<input type="text" name="eventname" id="eventname">
</td>
In the console,I am getting name as i am ok seminar .How to bind that name in the HTML page automatically when id is given.
Can anyone help?
So your Javascript function should be;
function getEventname(){
var clid=$('#eventid').val();
console.log("i am ok"+clid);
$.ajax({
type: "GET",
url: "EduManage.jsp",
data: {
control:'ajax',
ch:'1',
key:'1_0a1m_1',
eventid:clid
},
success: function(data) {
console.log("i am ok"+data);
//The one line change
$("#eventname").val(data);
}
});
}
So you had already implemented everything. All you need to do is add data in some element. If you want to add it in td then use this:
$.ajax({type: "GET",url: "EduManage.jsp",data: {control:'ajax', ch:'1', key:'1_0a1m_1', eventid:clid},
success: function(data) {
console.log("i am ok"+data);
$("td.last").append(data);
(what to do to bind the name in the hmtl page)
}
});
and add a new html tag:
<td class="last"></td>
You can also update the html using jquery but its not a practice to do so.
Hope this works.

cross-domain form post with ajax jsonp returns error: {"readyState":4,"status":200,"statusText":"success"}

I'm trying to post form data to a php file that will then handle a mysql request. But before I do the mysql, I'm trying to connect to the php file.
The request is Cross-Domain.
When i submit the form, i get the error: {"readyState":4,"status":200,"statusText":"success"}
You can see the test page here: http://jonathan-tapia.mybigcommerce.com/store-locator/
form code:
<div class="map-search">
<h1>Give us your zip code. We'll tell you where to find us.</h1>
<div id="map-form">
<form id="lookup-form" action="http://dev.visioncourse.com/customers/baldguy/index.php" method="post">
<p>Within
<select id="distance" name="distance">
<option value="10">10</option>
<option selected="selected" value="25">25</option>
<option value="50">50</option>
<option value="100">100</option>
</select>
miles of
<input id="zipcode" type="text" name="postalcode" value="" size="8" />
<input id="lookup" type="submit" value="Look Up" />
</p>
</form>
</div>
</div>
<div class="map-results"> </div>
updated JS:
<script type="text/javascript">// <![CDATA[
//submit form
$('#lookup-form').submit(function(event) {
event.preventDefault();
var formdata = $(this);
var link = formdata.attr('action');
var distance = $('#distance').val();
var zipcode = $('#zipcode').val();
console.log('.\n..\n...\n....\nSubmitting Form\n....\n...\n..\n.');
$.ajax({
crossDomain: true,
type: 'POST',
url: link,
data: {
'distance': distance,
'postalcode': zipcode
},
dataType: 'jsonp',
error: function(data) {
console.log('error: ' + data);
},
success: function(data) {
console.log('success: ' + data);
},
xhrFields: {
withCredentials: true
}
});
});
// ]]>
updated php file:
<?php
$arr = array();
$distance = $_POST['distance']
$zip = $_POST['postalcode'];
if(isset($distance) && isset($zip)) {
array_push($arrr, {'d': $distance, 'z': $zip});
}
echo json_encode($arr);
?>
error i'm receiving from console:
GET http://dev.visioncourse.com/customers/baldguy/index.php?callback=jQuery17203092896034941077_1451698154204&distance=25&postalcode=85251 jquery.min.js:4
EDIT:
The php file will get the distance and zip code from the form and connect to a mysql database for a google maps store locator. so when a person submits the radius and the zip code it will display results. but all of this will be on the php file.
The file doing the form submission will submit the form, wait for the php to do it's work, then display the php file with the results
Try it with data: {"distance": distance, "zipcode": zipcode},.
In your code you insert the value of the variables twice instead of a name and a value.
Also, you need to send the zipcode with the name of 'postalcode'. Otherwise your phpscript wouldn't find it.
you can try this way:
javascript:
<script>
var formdata = $(this);
var link = formdata.attr('action');
var distance = $('#distance').val();
var zipcode = $('#zipcode').val();
$.ajax({
type: 'GET',
url: link,
data: {"distance": distance,"postalcode": zipcode},
async: false,
jsonpCallback: 'jsonp_callback',//name of function returned from php
contentType: "application/json",
dataType: 'jsonp',
success: function(r) {
console.log(r);
},
error: function(e) {
alert(e.message);
}
});
</script>
php:
<?php
$arr = array();
$distance = $_GET['distance'];//sample 123
$zip = $_GET['postalcode'];//sample 65455
if(isset($distance) && isset($zip)) {
$arr = array('d'=> $distance, 'z'=> $zip);
}
$json = 'jsonp_callback(';
$json .= json_encode($arr);
$json .= ');';
echo $json;
?>
response:
jsonp_callback({"d":123,"z":65455});

Resources