Call Ajax on href click - javascript

I have a series of links which I want to call using Ajax
Link
Link
Link
I have tried the below to no avail:
<a id="data" href="#" data-href="Example">
<script type="text/javascript">
$(document).on('click','#data',function(e) {
e.preventDefault();
e.stopPropagation();
var data = $(this).data('href');
$.ajax({
method: 'get',
url: 'AddElement.php?Type=',
data: data,
async: true,
cache: false,
success: function (data){
alert('Success');
}
});
});
</script>
Can anyone help?

Define custom attributes and use those in the script as below.
data-url="AddElement.php?Type=" href="#" data-value="Example"
$(document).on('click','#data',function(e) {
e.preventDefault();
e.stopPropagation();
var URL = $(this).data('url');
var data = $(this).data('value');
$.ajax({
method: 'get',
url: URL,
data: data,
async: true,
cache: false,
success: function (data){
alert('Success');
},
error: function (data) {
console.log('Error');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a a id="data" data-url="AddElement.php?Type=" href="#" data-value="Example">Text</a>

You need to use the data-href value in the url option, not in the data option. Therefore it should be
var hrefVal = $(this).data('href');
$.ajax({
method: 'get',
url: 'AddElement.php?Type=' + hrefVal,
async: true,
cache: false,
success: function (data){
alert('Success');
}
});

Related

jquery ajax function not do anything

all Ajax not working in my project,
my structure project is
http://localhost/aaa/beranda.php?h=Add-Pengeluaran
The jquery code is as follows
<script type="text/javascript">
$(document).ready(function() {
$('#tampil').load("tampil.php");
$("#Submit").click(function() {
var data = $('#form').serialize();
$.ajax({
type: 'POST',
url: "insert.php",
data: data,
cache: false,
success: function(data) {
$('#tampil').load("tampil.php");
}
});
});
});
</script>
please help me

how to pass named route parameter with ajax

I need to pass route parameter with ajax but I am using named route method in ajax code.
route I want to go
Route
Route::post('/edit/{id}', 'ArticleController#updateArticle')->name('updateArticle');
Ajax
var id= $("input[name=editId]").val();
$.ajax({
type:'POST',
enctype: 'multipart/form-data',
url:"{{ route('updateArticle',"id") }}",
data: formdata,
contentType: false,
processData: false,
success:function(data){
$('.alert-success').html(data.success).fadeIn('slow');
$('.alert-success').delay(3000).fadeOut('slow');
}
});
I want to use variable id in ajax URL.
Try to use replace function:
var id = $("input[name=editId]").val();
var url = "{{ route('updateArticle', ":id") }}";
url = url.replace(':id', id);
$.ajax({
type:'POST',
enctype: 'multipart/form-data',
url: url,
data: formdata,
contentType: false,
processData: false,
success:function(data){
$('.alert-success').html(data.success).fadeIn('slow');
$('.alert-success').delay(3000).fadeOut('slow');
}
});
I had the same problem, just change your ajax url with this one.
var id= $("input[name=editId]").val();
$.ajax({
type:'POST',
enctype: 'multipart/form-data',
url:"{{ route('updateArticle') }}" + '/' + id,
data: formdata,
contentType: false,
processData: false,
success:function(data){
$('.alert-success').html(data.success).fadeIn('slow');
$('.alert-success').delay(3000).fadeOut('slow');
}
});
Put + around id variable and make sure you are passing X-CSRF-Token via formdata variable or try sending manualy :
replace this line :
url:"{{ route('updateArticle',"id") }}",
with this :
url:"{{ route('updateArticle',"+id+") }}",
var id= $("input[name=editId]").val();
$.ajax({
type:'POST',
enctype: 'multipart/form-data',
url:"{{ route('updateArticle',"+id+") }}",
data: formdata,
contentType: false,
processData: false,
success:function(data){
$('.alert-success').html(data.success).fadeIn('slow');
$('.alert-success').delay(3000).fadeOut('slow');
}
});
Try this:
$(document).on("click", ".delete", function() {
var $ele = $(this).parent().parent();
var id= $(this).val();
var url = '{{ route("student.destroy_academic_qualifications", ":id") }}';
url = url.replace(':id', id);
$.ajax({
url: url,
type: "GET",
cache: false,
data:{
_token:'{{ csrf_token() }}'
},
success: function(dataResult){
var dataResult = JSON.parse(dataResult);
if(dataResult.statusCode==200){
$ele.fadeOut().remove();
}
}
});
});
You can do it like this.
In your blade file
<script>
window.your_route = "{{ route('updateArticle',['id'=>$id]) }}";
</script>
In you JavaScript you can use created variable.
$.ajax({
type:'POST',
enctype: 'multipart/form-data',
url:window.your_route,
data: formdata,
contentType: false,
processData: false,
success:function(data){
$('.alert-success').html(data.success).fadeIn('slow');
$('.alert-success').delay(3000).fadeOut('slow');
}
});
You can do it like this below, just hardcode the url and id
var id= $("input[name=editId]").val();
$.ajax({
type:'POST',
enctype: 'multipart/form-data',
url:"edit/1",
data: formdata,
contentType: false,
processData: false,
success:function(data){
$('.alert-success').html(data.success).fadeIn('slow');
$('.alert-success').delay(3000).fadeOut('slow');
}
});
in form
<form id="form-create-role" action="{{route('role-create')}}" >
in file role-create.js
$(function(){
$('#form-create-role').submit(function (event) {
event.preventDefault();
$.ajax({
type: "post",
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: "json",
success: function (response) {
}
});
});
});
I do this by two ways
By using full url
$(document).on('click', '.view', function(){
let contactId = $(this).attr('data-id');
$.ajax({
type: "GET",
url: window.location.origin + "/view-contact-details/" + contactId,
success: function (response) {
console.log(response);
}
});
});
By using named route parameter
$(document).on('click', '.view', function(){
let contactId = $(this).attr('data-id');
let url = "{{ route('view.contact', ['id' => ":contactId"]) }}";
url = url.replace(":contactId", contactId);
$.ajax({
type: "GET",
url: url,
success: function (response) {
console.log(response);
}
});
});
You can use any of these :)

Post files with AJAX + jQuery with input element ID

I am trying to POST form data with AJAX + jQuery using the code below
<script>
$("#submit1").click(function(){
testSubmit(event);
});
function testSubmit(event) {
event.preventDefault();
var data = new FormData();
var file_data = $('input[type="file"]')[0].files; // for multiple files
for(var i = 0;i<file_data.length;i++){
data.append("file_"+i, file_data[i]);
}
var other_data = $('#form_id').serializeArray();
$.each(other_data,function(key,input) {
data.append(input.name,input.value);
});
$.ajax({
url: 'test.php',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
}
});
}
</script>
Here submit1 is a button on form form_id
This code is working fine, however the below line
data.append("file_"+i, file_data[i]);
as you can see posts the file with id of file_0, file_1 and so on. How can I get this to be the actual id of the input element rather than being a generic file_0, file_1 etc ?
Thanks for reading this
If you are using jQuery then why not something like this
$('input[type="file"]').each(function($i){
data.append($(this).prop("id"), $(this)[0].files[0]);
});
Entire Code :-
<script>
$("#submit1").click(function(){
testSubmit(event);
});
function testSubmit(event) {
event.preventDefault();
var data = new FormData();
$('input[type="file"]').each(function($i){
data.append($(this).prop("id"), $(this)[0].files[0]);
});
var other_data = $('#form_id').serializeArray();
$.each(other_data,function(key,input){
data.append(input.name,input.value);
});
$.ajax({
url: 'test.php',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
}
});
}
</script>

Do something after window load

I'm doing a (simple) ajax call on window load:
$(window).load(function () {
$.ajax({
url: someUrl,
type: "get",
dataType: "",
success: function(data) {
...........
How can I do something, for instance a function or event after this ajax proces is finished. The problem is I have to append something to the data recieved by the ajax call. But I can't append on window load because the data is still being processed.
Put it in the success handler of the ajax call:
$(window).load(function () {
$.ajax({
url: someUrl,
type: "get",
dataType: "",
success: function(data) {
// do whatever you want with data
}
});
});
You can call that in the success callback function of Ajax request
success: function(data) {
myFunction() ; // If function
$('#elementID').click() // If you want to trigger a click event
}
You may use the
`$(document).ready`
So it will be similar to this:
$(document).ready(function(){
$.ajax({
url: someUrl,
type: "get",
dataType: "",
success: function(data) {
//Your code should be here
After
success: function(data) {
for (var ii = 0; ii < data.length; ii++){
building html here
}
your code here
}
you want to enter in your functions within the success function for the ajax call but before the call is complete.
You could also do
$.ajax({
url: someUrl,
type: "get",
dataType: "",
context: document.body
}).done(function() {
// do whatever when is done
onCompleteFunction();
});
this should execute your request when page is just loaded.
$(function(){
$.ajax({
url: someUrl,
type: "get",
dataType: "",
success: function(data) {
// do whatever you want with data
}
});
});
or you can do:
$(function(){
$.ajax({
url: someUrl,
type: "get",
dataType: "",
complete: function(data) {
// do whatever you want with data
}
});
});

ajax request not working on IE

function VReload()
{
$.ajax({
type: "GET",
url: "/foo/",
success: function (data) {
$("#myid").html(data);
}
});
}
$(document).ready(function() {
setInterval('VReload()', 1000)
});
This piece of code is working fine on Mozilla and chrome but not on IE. Ajax call is not firing on IE. What could be the reason.
Switch off caching by doing this:
$.ajax({
type: "GET",
cache: false,
url: "/foo/",
success: function (data) {
$("#myid").html(data);
}
});
set cache false
$.ajaxSetup({ cache: false });
or
$.ajax({
cache: false,
//other options
});
Try this:
function VReload()
{
var timestamp = new Date();
$.ajax({
type: "GET",
url: "/foo/" + "&timestamp=" + timestamp.getTime(),
success: function (data) {
$("#myid").html(data);
}
});
}
$(document).ready(function() {
setInterval('VReload()', 1000)
});
use jQuery's $.get() function
$.get('/foo/', {}, function(data){
// whatever
});

Categories