how to get codeigniter url parameters in jquery ajax function - ajax

I have the following url in codeigniter.
Add to wishlist
and I have the following jquery function
<script>
$(document).ready(function(){
$('body').on('click', 'a.wishlist_item', function(e){
$.ajax({
url:"../add-item-to-wishlist",
data : "the query string",
success: function(result){
// success code.
}
});
e.preventDefault();
});
});
</script>
how do I get the query string value and pass to the above url ? the add-to-wishlist route redirect to a controller function which take exactly two parameters.
function add_to_wishlist($itemID,$wishlistID = NULL)
What I want to do is call this function using ajax but I dont know how do I call this using ajax

change your anchor URL to the controller method
href = "add_to_wishlist/5/21"
Then you can do a get request with the full URL
<script>
$(document).ready(function(){
$('body').on('click', 'a.wishlist_item', function(e){
e.preventDefault();
var obj = $(this);
$.ajax({
type:'get',
url:obj.attr('href'),
success: function(result){
// success code.
}
});
});
});
</script>

Related

AJAX form redirecting on submit when using CKeditor

I am trying to submit an AJAX form with Laravel using the code shown below. After I submit the form, all the data is saved in the database as expected apart from the following field which is displayed as NULL in the database.
<textarea name="content" id="editor"></textarea>
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(".btn-submit-add-video").each(function(){
$(this).on("click",function(e){
e.preventDefault();
let form = $(this).closest('form');
$.ajax({
type:'POST',
url: form.attr('action'),
data: form.serialize(),
success:function(data){
alert(data.successful);
}
});
})
});
</script>
public function addVideo(Request $request)
{
$addVideo = new cms_videos;
$addVideo->VideoStatus = $request->VideoStatus;
$addVideo->VideoTitle = $request->VideoTitle;
$addVideo->VideoStrapline = $request->VideoStrapline;
$addVideo->VideoURL = $request->VideoURL;
$addVideo->VideoDescription = $request->content;
$addVideo->VideoTags = $request->VideoTags;
$addVideo->MetaActName = $request->MetaActName;
$addVideo->MetaRegion = $request->MetaRegion;
$addVideo->MetaGenre = $request->MetaGenre;
$addVideo->MetaVenue = $request->MetaVenue;
$addVideo->VideoCoverPhoto = $request->VideoCoverPhoto;
$addVideo->save();
return response()->json(['successful'=>'Video successfully added']);
}
After doing some research I was told to add the following code to the top of the code shown above:
CKEDITOR.instances.SurveyBody.updateElement();
Now all the data is submitted to the database as expected. However when I now submit the form instead of an alert popping up saying "Successful" I am now redirected to the form action URL where it displays "Successful". How can I stop this redirection and display the alert on the page the form was submitted?
I'm not sure but I think the issue is here when you do e.preventDefault() because it works for the button click not for form submission. Try this out and hope it will help you.
Notice: you have to add upload_video class to your forms
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
// If the button is type of submit you can remove this part of code
$(".btn-submit-add-video").each(function(){
$(this).on("click",function(e){
e.preventDefault();
let form = $(this).closest('form.upload_video');
form.submit();
})
});
//
$("form.upload_video").on('submit',function(e){
e.preventDefault();
let form = $(this),data=form.serialize();
//
let content=FCKeditorAPI.GetInstance('content').getData();
data['content']=content;
//
$.ajax({
type:'POST',
url: form.attr('action'),
data: data,
success:function(data){
alert(data.successful);
}
});
});
</script>
This part
let content=FCKeditorAPI.GetInstance('content').getData();
May not be true because I don't work with CKEDITOR right now and i can't test it but you can console.log() it before you send the ajax request and make sure the content exists in the variable as you expected.

Store Data Using Ajax

I want to insert data using Ajax in Laravel 5.3.But when I press submit button screen gets refreshed.
My Code
$(document).ready(function(){
//button id//
$('#submit').click(function(){
//form id//
$('#new_form').submit(function(e){
e.preventDefault();
var name = $('#name').val();
$.ajax({
type: "POST",
url: "/store_form", //controller function
data: "name="+ name ,
success: function(){
alert("sucess");
});
});
});
});
How I can I do it ?
Remove the line of the button $('#submit').click(...
And only left the code as follow
$(document).ready(function(){
//form id//
$('#new_form').submit(function(e){
e.preventDefault();
var name = $('#name').val();
$.ajax({
type: "POST",
url: "/store_form", //controller function
data: "name="+ name ,
success: function(){
alert("sucess");
});
});
});
You can replace
$('#submit').click(function(){
//form id//
$('#new_form').submit(function(e){
with only
$('#new_form').submit(function(e){ if you are talking about same form and submit button is ```<input type=submit``` and if there are two forms
you can do $('#new_form, #new_form2').submit(function(e){
and add your js with {!! Html::script('js/script.js') !!} using illuminate
if you are still facing problem please post the error as well as php code.

Laravel 5.2 post route returns plain html text

whenever I send a post request to 'tasks/add' i want the user to return to a new page, but all I get is plain html text in a popup.
Route.php code
Route::post('tasks/add', function() {
return view('secrets');
});
this is my ajax request :
$("#frm").submit(function(e){
e.preventDefault();
var customer = $("input[name=customer]").val();
var details = $("input[name=details]").val();
var dataString = 'customer='+customer+'&details='+details;
$.ajax({
url: "tasks/add",
type:"POST",
beforeSend: function (xhr) {
var token = $('meta[name="csrf_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
data : dataString,
success:function(data){
console.log(dataString);
alert(data);
},error:function(){
alert("error!!!!");
}
}); //end of ajax
});
});
Anybody has had this issue before?
You are using Ajax to call your Route method. So when Route::post(...) returns the view 'secrets', it returns it to the Ajax method and becomes held by the data variable. Saying return in your Routes file doesn't magically mean redirect to a certain view, it is just like any other function that returns a value.
You currently have alert(data) which just says make an alert with whatever is held by data which in this case is the html text of your view.
Instead, take out the alert() and put
window.location.replace('<path/to/secrets>')
to redirect to the page you want upon success.
Assuming your Routes file has something like :
Route::get('/secrets', function() {
return view('secrets');
});
You could say
window.location.replace('/secrets')

pagination using ajax in codeigniter

i want to create a pagination using ajax but i am getting trouble for it.
i use folliwing ajax function for that.
<script type="text/javascript">
$(function(){
$('#ajax_pagi a').click(function(e){
var url = $(this).attr('href');
$.ajax({
url:url,
type:'POST',
success:function(data){
$('body').html(data);
}
});
e.preventDefault();
return false;
});
});
</script>
and following is pagination link
<ul id="ajax_pagi"> <?php echo $this->pagination->create_links(); ?></ul>
it refresh page when click on the next page link.
so any one can help me to solve this.
thanks in advance.
This is because of event delegation. for the first time it will work, next time it will refresh the page.
So use on() instead of click().
$(document).on("click","#ajax_pagi a",function(e){
var url = $(this).attr('href');
$.ajax({
url:url,
type:'POST',
success:function(data){
$('body').html(data);
}
});
e.preventDefault();
return false;
});
For current page href will be equal to #, if user click on that it will generate 404 error.
Add if() for ajax
if(url != "#") {
//ajax here
}

Ajaxify hyperlink so on success will load content otherwise redirect as default

I have a <a href> hyperlink. I used JQuery so clicking the link will load contents into a div in the current page (i.e. stay in the same page), and it works now.
However I also want that, if the request fails, the link act normally and go to the href url.
I tried e.preventDefault(); and return false; in the success: callback function, but they are not in the correct scope. If I place e.preventDefault() in the calling function, I can't reverse that effect later.
Here is my code:
$('a.more-link').click(function(e){
var postId=$(this).closest('div.post').attr("id").replace(/^post-(.*)$/,'$1');
var postContent=$(this).parent();
$.ajax({
url:"?action=ajax_load_post&id="+postId,
success:function(data){
postContent.html(data);
// Can't access e.preventDefault, nor return false;
},
error:function(data){
}
});
e.preventDefault();
});
Don't worry about the preventDefault(), just redirect the user in the error function like this:
$('a.more-link').click(function(e){
var postId=$(this).closest('div.post').attr("id").replace(/^post-(.*)$/,'$1');
var postContent=$(this).parent();
var _this = $(this);
$.ajax({
url:"?action=ajax_load_post&id="+postId,
success:function(data){
postContent.html(data);
},
error:function(data){
window.location = _this.attr('href');
return false;
}
});
});

Resources