Running Ajax request not working - ajax

I just migrated to a different bootstrap template now my ajax functions is not working and my php file which handles the functions is not appearing in the XHR inspect tool of chrome.
I only have this jquery script ? is this enough for running an ajax function? I
<!-- Jquery Core Js -->
<script src="../dashboard-assets/plugins/jquery/jquery.min.js"></script>
HTML CODE
<form id="upload_book_form" method="POST">
<p>Upload Books</p>
<input type="file" id="uploadbookinfo" name="uploadbookinfo" value="Import" />
</form>
SCRIPT FUNCTION
<script type="text/javascript">
$(document).ready(function() {
//upload book
$('#uploadbookinfo').change(function() {
$('#upload_book_form').submit();
});
$('#upload_book_form').on('submit', function(event) {
event.preventDefault();
$.ajax({
url: "adminfunctions.php",
method: "POST",
data: new FormData(this),
contentType: false,
processData: false,
success: function(data) {
var getdata = data.trim();
if (getdata == "SUCCESS") {
swal({
title: 'Success!',
text: 'Book Added , Try refreshing the page',
type: 'success',
confirmButtonClass: "btn btn-success",
buttonsStyling: false
}).then(function() {
$("#uploadbookinfo").val(null);
});
} else if (getdata == "ERRORFILETYPE") {
swal({
title: 'Oops...',
text: 'File type is not supported',
type: 'error',
confirmButtonClass: "btn btn-danger",
buttonsStyling: false
}).then(function() {
$("#uploadbookinfo").val(null);
});
} else {
swal({
title: 'Sorry for the inconvenience!',
text: "There's a problem. Please contact the technical support for any concerns and questions.!",
type: 'error',
confirmButtonClass: "btn btn-info",
buttonsStyling: false
}).then(function() {
$("#uploadbookinfo").val(null);
});
}
},
error: function(jqXHR, exception) {
console.log(jqXHR);
}
});
});
});
</script>

Related

Calling ActionResult using jquery ajax in .net core

Action in controller
Method GetById is the same as the Find method and EntityUpdate == Update
public IActionResult CategoryStatus(int id)
{
var data = cm.GetById(id);
if (data.CategoryStatus)
{
data.CategoryStatus = false;
}
else
{
data.CategoryStatus = true;
}
cm.EntityUpdate(data);
return RedirectToAction("Index");
}
I want to call this action from razor view with ajax, can anyone help , thanks.
I add some parts of razor view just in case
<a href="/Admin/Category/CategoryStatus/#item.CategoryID"
class="btn btn-outline-success btn-sm"
onclick="return functionConfirm(this)">
Aktivləşdir
</a>
<script>
function functionConfirm(event) {
swal({
title: 'Are you sure?',
text: "You will not be able to recover this item!",
type: 'warning',
showCancelButton: true,
cancelButtonText: 'No',
cancelButtonClass: 'btn btn-danger',
showConfirmButton: true,
confirmButtonText: 'Yes',
confirmButtonClass: 'btn btn-success'
}, function (isConfirm) {
if (isConfirm) {
$.ajax({//I need your help here
type: "GET",
url: '/Admin/Category/CategoryStatus',
success: function (msg) {
console.log(msg);
},
error: function (req, status, error) {
console.log(msg);
}
});
return true;
} else {
return false;
}
});
return false;
}
Change your code like below:
//add this....
<a data-id="#item.CategoryID"
class="btn btn-outline-success btn-sm"
onclick="return functionConfirm()">
Aktivləşdir
</a>
#section Scripts
{
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.css" integrity="sha512-gOQQLjHRpD3/SEOtalVq50iDn4opLVup2TF8c4QPI3/NmUPNZOk2FG0ihi8oCU/qYEsw4P6nuEZT2lAG0UNYaw==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.js" integrity="sha512-7VTiy9AhpazBeKQAlhaLRUk+kAMAb8oczljuyJHPsVPWox/QIXDFOnT9DUk1UC8EbnHKRdQowT7sOBe7LAjajQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script>
function functionConfirm() {
swal({
title: 'Are you sure?',
text: "You will not be able to recover this item!",
type: 'warning',
showCancelButton: true,
cancelButtonText: 'No',
cancelButtonClass: 'btn btn-danger',
showConfirmButton: true,
confirmButtonText: 'Yes',
confirmButtonClass: 'btn btn-success'
}, function (isConfirm) {
var id = $(event).data("id"); //add....
if (!isConfirm) return;
$.ajax({
type: "GET",
url: '/Admin/Category/CategoryStatus/'+id, //modify...
success: function (msg) {
window.location.href="/xxx/Index"
},
error: function (req, status, error) {
console.log(msg);
}
});
});
}
</script>
}

I want to delete data without refreshing whole page using ajax

I am new at Laravel, I am trying to delete data with ajax, when I click to delete button, the page is refreshing but data is deleting perfectly but that should not be reloaded.
Controller
public function destroy($id)
{
$delete = Digitizing::where('id', $id)->delete();
return back();
}
HTML view
<a href="{{route('digitizing.delete',$digitizing->id)}}"
class="btn btn-danger" onclick="deleteConfirmation({{$digitizing->id}})">Delete</a>
<script type="text/javascript">
function deleteConfirmation(id) {
Swal.fire({
title: "Delete?",
text: "Please ensure and then confirm!",
type: "warning",
showCancelButton: !0,
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, cancel!",
reverseButtons: !0
}).then(function (e) {
if (e.value === true) {
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
type: 'POST',
url: "{{url('digitizing/delete')}}/" + id,
data: {_token: CSRF_TOKEN},
dataType: 'JSON',
success: function (results) {
if (results.success === true) {
swal("Done!", results.message, "success");
} else {
swal("Error!", results.message, "error");
}
}
});
} else {
e.dismiss;
}
}, function (dismiss) {
return false;
})
}
</script>
**Delete wants a get method because you have to give only ID to delete.**
**WEB.PHP**
Route::get('digitizing/delete/{id}','YourController#destroy');
**SCRIPT**
let id = $('#my_id').val();
$.ajax({
type: 'GET',
url: "{{url('digitizing/delete')}}/" + id,
data: {
_token: '{{csrf_token()}}',
},
success: function () {
alert('Successfully Deleted');
}
}).fail(function(){
console.log('problem with route = digitizing/delete');
});

Jquery validation is working but the ajax is not submitted

I'm trying to validate fields inside the form and then fire a function to submit the form using Ajax, the validation is working very well, but the ajax is not working at all
can you please help me figure the solution out
$(function() {
$.validator.addMethod("urlRegex", function(value, element) {
return this.optional(element) ||regex here .test(value);
}, "this should be url.");
$("#songvalid").validate({
rules:
{
song:
{
required: true,
urlRegex: true
}
},
messages:
{
song:
{
urlRegex:"من فضلك أدخل حروف وأرقام فقط"
}
},
submitHandler: function(form){
$("#error").fadeOut();
$("#song-btn").html('<img src="btn-ajax-loader.gif" /> انتظر لحظات ...', );
$.ajax({
url: 'song_process.php',
type: this.method,
data: $(this).serialize(),
success: function(responsd) {
if(responsd=="song"){
$("#song-btn").html(' تم الإرسال');
}
else{
$("#error").fadeIn(1000, function(){
$("#error").html('<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span> '+responsd+' !%</div>');
});
}
}
});
return false;
}
});
});
I found the answer!
I changed this:
type: this.method,
data: $(this).serialize(),
to this:
type: 'POST',
data: $("#formName").serialize(),

chat.js:89 Uncaught ReferenceError: bind is not defined(…) In React js

Hi I am a beginner in react js and making a project while running my code I have an error in the console
chat.js:89 Uncaught ReferenceError: bind is not defined(…)
I am unable to find the mistake kindly help me.
class CommentBox extends React.Component{
constructor(){
super();
this.state = {data: []}
}
loadCommentsFromServer() {
$.ajax({
url: 'api/get-latest-comments.php',
dataType: 'json',
cache: false,
success(data) {
bind(this.setState({data: data}))
},
error(xhr, status, err) {
bind(console.error(this.props.url, status, err.toString()))
}
});
}
handleCommentSubmit(comment) {
// TODO: submit to the server and refresh the list
var comments = this.state.data;
var newComments = comments.concat([comment]);
this.setState({data: newComments});
$.ajax({
url: 'api/save-comment.php',
dataType: 'json',
type: 'POST',
data: comment,
success(data) {
bind(this.setState({data: data}))
},
error(xhr, status, err) {
bind(console.error(this.props.url, status, err.toString()))
}
});
}
componentDidMount() {
this.loadCommentsFromServer();
setInterval(this.loadCommentsFromServer, this.props.pollInterval);
}
render() {
return (
<div className="commentBox">
<CommentForm onCommentSubmit={this.handleCommentSubmit} />
<div className="page-header">
<h1>Comments</h1>
</div>
<CommentList data={this.state.data} />
</div>
);
}
}
Old index.php's scripts
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.0/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.6.15/browser.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/marked/0.3.2/marked.min.js"></script>
New index.php's scripts
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/marked/0.3.6/marked.min.js"></script>
The way you are using bind() is wrong. You need to bind the success and error function in ajax to the correct context and not the data inside the function. Use bind as
success: function(data) {
this.setState({data: data})
}.bind(this),
Code:
class CommentBox extends React.Component{
constructor(){
super();
this.state = {data: []}
}
loadCommentsFromServer = () => {
$.ajax({
url: 'api/get-latest-comments.php',
dataType: 'json',
cache: false,
success: function(data) {
this.setState({data: data})
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString())
}.bind(this)
});
}
handleCommentSubmit = (comment) => {
// TODO: submit to the server and refresh the list
var comments = this.state.data;
var newComments = comments.concat([comment]);
this.setState({data: newComments});
$.ajax({
url: 'api/save-comment.php',
dataType: 'json',
type: 'POST',
data: comment,
success: function(data) {
this.setState({data: data})
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString())
}.bind(this)
});
}
componentDidMount() {
this.loadCommentsFromServer();
setInterval(this.loadCommentsFromServer, this.props.pollInterval);
}
render() {
return (
<div className="commentBox">
<CommentForm onCommentSubmit={this.handleCommentSubmit} />
<div className="page-header">
<h1>Comments</h1>
</div>
<CommentList data={this.state.data} />
</div>
);
}
}

Getting textbox value from X-editable

How do you get the value of the textbox field and send as data inside of ajaxOptions? I tested my view and it prints out the test variable successfully from my Django views. I am using X-editable for Jquery. Heres what textbox input looks like:
http://jsfiddle.net/xBB5x/197/
views.py
def create_post(request):
print request.POST.get("test", "");
return HttpResponse(json,content_type="application/json")
HTML
<a id="other1" data-pk="First Name" data-name="test">First Name</a>
AJAX
$(document).ready(function() {
$('#other1').editable({
type: 'text',
pk: 1,
url: '/create_post/',
ajaxOptions: {
data: {
csrfmiddlewaretoken: '{{ csrf_token }}',
test: "hi",
},
},
placement: 'top',
title: 'New Expense',
success: function(response, newValue) {
if(response.status == 'error') return response.msg; //ms
},
});
});
Instead of ajaxOptions, use params. If I remember correctly, test and its value will be included in your POST request by x-editable. Try something like this:
Html
<a id="other1" data-pk="1" data-name="test">First Name</a>
AJAX
$(document).ready(function() {
$('#other1').editable({
type: 'text',
url: '/create_post/',
params : function(params) {
params.csrfmiddlewaretoken = '{{ csrf_token }}';
return params;
},
placement: 'top',
title: 'New Expense',
success: function(response, newValue) {
if(response.status == 'error') return response.msg; //ms
},
});
});

Resources