How to make a ajax request using post method - ajax

I made an ajax request using post method in django..its wokring perfectly..the problem is its calling the complete html page rahter than a div..i want to call only a div..i tried but unable to find the exact solution..
<script>
$(document).ready(function(){
$('#Category').change(function(event){
event.preventDefault();
var e = document.getElementById("Category");
var value = e.options[e.selectedIndex].value;
$.ajax({
url: "/charts/",
type: "post",
dataType: "html",
data: value,
success: function(data) {
$('#div1').html(data);
}});
return false;
});
});
</script>
I want only div content with id #div1..i already tried find and replace method

What is the nature of the event ? Is it a button ? an Input ?
If it is an input as <input type="submit">, the default action is to reload the page like a form.

Did you check if your div id is really div1?
$("#div1").append("your html code"+data+" your html code")

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.

UPDATE CART ITEMS USING AJAX IN MAGENTO

I want to update the cart item without loading the page i.e with the help of ajax.
can anyone tell me in which file did i put this code.
jQuery(document).ready(function(){
jQuery('#shopping-cart-table')
.on(
'change',
'input[name$="[qty]"]',
function(){
var form = jQuery(jQuery(this).closest('form'));
// we'll extract the action and method attributes out of the form
// kick off an ajax request using the form's action and method,
// with the form data as payload
jQuery.ajax({
url: form.attr('action'),
method: form.attr('method'),
data: form.serializeArray()
});
}
);
});
The easy way is to put this code in a Javascript script tag into the checkout cart template: magento/app/design/frontend/base/default/template/checkout/cart.phtml
Be carefull, you have to set update_cart_action data to "update_qty", to be in update qty mode.
var formData = form.serializeArray();
formData.push({'update_cart_action' : 'update_qty'})
jQuery.ajax({
url: form.attr('action'),
method: form.attr('method'),
data: formData
});

when ajax post success i want to refresh a particular <div> in page

i want to refresh a particular div on ajax success, im using the below code but the whole page getting refreshed.
<script type="text/javascript">
$('#post_submit').click(function() {
var form_data = {
csrfsecurity: $("input[name=csrfsecurity]").val(),
post_text: $('#post_text').val()
};
$.ajax({
url: "<?php echo site_url('/post_status'); ?>",
type: 'POST',
data: form_data,
success: function(response){
$(".home_user_feeds").html("markUpCreatedUsingResponseFromServer");
}
return false;
});
return false;
});
</script>
you have an extra return false which is inside the $.ajax block which most probably causes an error so your form isn't submitted via ajax. If you remove that, you shouldn't have any issues.
Use the submit event of the form and remove the return false from the ajax callback:
$('#myFormId').on('submit', function() {
var form_data = {
csrfsecurity: $("input[name=csrfsecurity]").val(),
post_text: $('#post_text').val()
};
$.ajax({
url: "<?php echo site_url('/post_status'); ?>",
type: 'POST',
data: form_data,
success: function(response){
$(".home_user_feeds").html("markUpCreatedUsingResponseFromServer");
}
});
return false;
});
Remove the return false from inside your $.ajax function. Its a syntax error. The $.ajax function only expects a json object as an argument. "return false" cannot be part of a json object. You should keep the JavaScript console open during testing at all times - Press Ctrl-Shift-J in Chrome and select console to see any JS errors.
Also suggest you use <input type=button> instead of <input type=submit> or <button></button>

How do I use data passed back in the response from ajax jQuery?

I am trying to use the response from a jQuery ajax request to set the innerHTML of a div with a certain id. This is the code I am using:
$(".show_comments").click(function(){
var articleName = $(this).closest("article").find(".articlename").attr('id')
$.ajax({
url: "commentView.php",
data: { 'articleName': articleName },
cache: false,
dataType: "html", // so that it will auto parse it as html
success: function(response){
$(this).closest("article").find(".comments").html(response);
}
});
however it doesn't seem to be doing anything at all, I've tried googling around, but everything I can find says to do it the way I am doing it... I have tested in Firebug and the ajax request is giving me the exact response I want it too... But I just cant access this to set the innerHTML of the div to the response!
In your ajax success handler there is another scope and this points to not what you think. So change your code to:
var articleName = $(this).closest("article").find(".articlename").attr('id'),
that = this;
$.ajax({
url: "commentView.php",
data: { 'articleName': articleName },
cache: false,
dataType: "html", // so that it will auto parse it as html
success: function(response){
$(that).closest("article").find(".comments").html(response);
}
});
What I've changed: I added that variable that points to this instance and use it in the success handler instead.
How would you debug it yourself: if you tried to output console.log(this) and console.log($(this).closest("article").find(".comments")); you would see that it returns a wrong object (in first case) and nothing in second.

Using jQuery AJAX to Invoke Rails Server Method on Client Side

I am using Ruby on Rails, and I want to invoke a controller method as an onclick event of my pre-existing links.
I am using jQuery and AJAX to do the same. But I don't know much about AJAX.
Here is my code.
<script type="text/javascript">
$("a.browse_history").live("click", function()
{
alert("i am here");
$.ajax({
url: "/user_profile_controller.rb/save_user_history",
type: 'PUT'
});
});
</script>
In user_profile_controller.rb:
def save_user_history
$doc_list << "hello hi"
end
And my link is:
Click here
But this is not working..
Any solutions would be appreciated.
Your URL looks wrong. Run rake routes to get a list of existing routes in your app.
Should be something like
url: "/user_profile/save_user_history"
or
url: "/user_profiles/save_user_history"
Thank you for your reply Stefan.
I changed my code like this:
<script type="text/javascript">
function u_profile(user,url,query)
{
$.ajax({
type: 'POST' ,
url: "http://localhost:3000/user_profiles",
data : {
user_profile : {
user_id : user ,
query_term : query,
visited_url: url
}
} ,
success: function(data){
alert(data);
}
});
};
</script>
And i am invoking it as onclick event of link.
It full fills my requirement of creating an object in database with passed data.

Resources