jQuery pass parameters into function call from ajax success - javascript

I want to call a function when a jQuery Ajax request is successfull. I want to pass a parameter into a second function that apparently (it doesn't work) doesn't exist inside the jquery anonymous function.
Here is my Ajax function:
function core_get_title(url,id_of_link){
$.ajax({
type: "POST",
url: "url_handler.php",
data: {
url: url,
cmd: "get_title",
},
success: function(data) {
core_title_auto(data,id_of_link);
}
});
}
And when it calls core_title_auto, the id_of_link parameter is empty.
Any ideas?

check and see whats in id_of_link before ajax call by placing an alert function
function core_get_title(url,id_of_link){
alert("id_of_link"+id_of_link);
$.ajax({
/*...... your code */
});
}

Related

How to make an AJAX call to an html element?

What I want to do is pretty simple. I want to make an AJAX call to a specific html class, so that whenever the html page is loaded, jquery will make an AJAX call to that specific html div class.
For example:
<div class="targeted"></div>
In jquery:
$('.targeted')
I know that the syntax to make an AJAX call is:
$.ajax({
type: "GET",
url: "/api/something",
success: function(data) {
console.log(data);
}
});
But how do I implement this AJAX call to the $('.targeted') whenever the page is loaded?
Thanks
If you mean you want to display the result of the ajax call in the element, you update the element from within the success callback:
$.ajax({
type: "GET",
url: "/api/something",
success: function(data) {
$('.targeted').html(data);
}
});
That example assumes
You want to replace the content of the element (rather than adding to it); more options in the jQuery API.
data will be HTML. If it's plain text, use .text(data), not .html(data). If it's structured data, then of course you'll need to do more work to put the information in the desired form.
window.onload = function() {
yourFunction();
};
function yourFunction(){
$.ajax({
type: "GET",
url: "/api/something",
success: function(data) {
$('.targeted').html(data);
}
});
}
OR Drectly you can pass that method in document ready it will execute automatically
$(document).ready(function(){
//This will execute onload oof your web page what you required
yourFunction();
})
function yourFunction(){
$.ajax({
type: "GET",
url: "/api/something",
success: function(data) {
$('.targeted').html(data);
}
});
}
For when the page is loaded, you use:
$( document ).ready(function() {
console.log( "ready!" );
});
Inside the document ready, you put your AJAX call. If the result you get is in JSON format, you need to include the dataType as well like this:
$.ajax({
method: "GET",
url: "/api/something",
dataType: "json"
})
.done(function( data ) {
$('.targeted').append(JSON.stringify(data));
});
If the result is not JSON, then you can just append the data.
Also note:
The jqXHR.success(), jqXHR.error() and jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail() and jqXHR.always() instead.
Please look at the jQuery documentation.
you can use jquery load like this:
$(".targeted").load('/api/something');
if you want to wait untill after the page is loaded, wrap it with window load like so:
$(window).load(function () {
$(".targeted").load('/api/something');
});
P.S. $(window).load(..) and $(".class").load(url) are two different functions
You can do:
$(function() {
$.ajax({
type: "GET",
url: "/api/something",
})
.done(function(data) {
$('.targeted').text(data);
});
});

Binding table in MVC 4 after Ajax call

I have an HTML able, which I bind by using the following Action in MVC controller:
public ActionResult BindTable(int ? page)
{
int pageSize = 4;
int pageNumber = 0;
List<Users> _users = query.ToList();
return View(_users.ToPagedList(pageNumber, pageSize));
}
Below the table I have the following HTML:
<textarea class="form-control" style="resize:none;" rows="9" placeholder="Enter value here..." id="txtValue"></textarea>
<br />
<button style="float:right; width:100px;" type="button" onclick="CallFunction()" class="btn btn-primary">Update specific record</button>
The Javascript function responsible for calling the action is as following:
function CallFunction() {
if ($('#txtValue').val() !== '') {
$.ajax({
url: '/User/UpdateUser',
type: 'POST',
data: { txt: $('#txtValue').val() },
success: function (data) {
$('#txtValue').val('');
alert('User updated!');
},
error: function (error) {
alert('Error: ' + error);
}
});
}
And here is the Action responsible for updating the user:
public ActionResult UpdateUser(string txtValue)
{
var obj = db.Odsutnost.Find(Convert.ToInt32(1));
if(obj!=null)
{
obj.Text= txtValue;
obj.Changed = true;
db.SaveChanges();
return RedirectToAction("BindTable");
}
return RedirectToAction("BindTable");
}
Everything works fine. But the table doesn't updates once the changes have been made ( it doesn't binds ?? )...
Can someone help me with this ???
P.S. It binds if I refresh the website.. But I want it to bind without refreshing the website...
I created a BIND function with Javascript, but it still doesn't binds:
function Bind() {
$(document).ready(function () {
var serviceURL = '/User/BindTable';
$.ajax({
type: "GET",
url: serviceURL,
contentType: "application/json; charset=utf-8",
});
});
}
You're not actually updating the page after receiving the AJAX response. This is your success function:
function (data) {
$('#txtValue').val('');
alert('User updated!');
}
So you empty an input and show an alert, but nowhere do you modify the table in any way.
Given that the ActionResult being returned is a redirect, JavaScript is likely to quietly ignore that. If you return data, you can write JavaScript to update the HTML with the new data. Or if you return a partial view (or even a page from which you can select specific content) then you can replace the table with the updated content from the server.
But basically you have to do something to update the content on the page.
In response to your edit:
You create a function:
function Bind() {
//...
}
But you don't call it anywhere. Maybe you mean to call it in the success callback?:
function (data) {
$('#txtValue').val('');
Bind();
alert('User updated!');
}
Additionally, however, that function doesn't actually do anything. For starters, all it does is set a document ready handler:
$(document).ready(function () {
//...
});
But the document is already loaded. That ready event isn't going to fire again. So perhaps you meant to just run the code immediately instead of at that event?:
function Bind() {
var serviceURL = '/User/BindTable';
$.ajax({
type: "GET",
url: serviceURL,
contentType: "application/json; charset=utf-8",
});
}
But even then, you're still back to the original problem... You don't do anything with the response. This AJAX call doesn't even have a success callback, so nothing happens when it finishes. I guess you meant to add one?:
function Bind() {
var serviceURL = '/User/BindTable';
$.ajax({
type: "GET",
url: serviceURL,
contentType: "application/json; charset=utf-8",
success: function (data) {
// do something with the response here
}
});
}
What you do with the response is up to you. For example, if the response is a completely new HTML table then you can replace the existing one with the new one:
$('#someParentElement').html(data);
Though since you're not passing any data or doing anything more than a simple GET request, you might as well simplify the whole thing to just a call to .load(). Something like this:
$('#someParentElement').load('/User/BindTable');
(Basically just use this inside of your first success callback, so you don't need that whole Bind() function at all.)
That encapsulates the entire GET request of the second AJAX call you're making, as well as replaces the target element with the response from that request. (With the added benefit that if the request contains more markup than you want to use in that element, you can add jQuery selectors directly to the call to .load() to filter down to just what you want.)

Why won't my javascript function called after ajax.success?

Why won't my function work after ajax has succeed?
I have a custom function named filter(), defined in the header as javascript file.
Then i have a series of jquery code to dynamically retrieve data from the server to populate the select box. I would like to call the filter() after the AJAX request has completed since the filter() will manage populated the select box's option.
$.ajax({
url: "checkersc2.php", //This is the page where you will handle your SQL insert
type: "GET",
data: values, //The data your sending to some-page.php
success: function (response) {
$('#loading-image').css('display', 'none');
$dropdownCondition.html(response);
filter();
},
error: function () {
console.log("AJAX request was a failure");
}
});
EDIT: my filter() code is a little long, # http://jsfiddle.net/tongky20/re5unf7p/11/
It looks like you have an invalid selector for dropdownCondition. It probably fails on that line and never calls filter. Unless you defined that variable else where try updating it to a valid element selector and see if it calls filter. Something like:
$('#dropdownCondition').html(response);
Assuming the element id is dropdownCondition.
Full function:
$.ajax({
url: "checkersc2.php", //This is the page where you will handle your SQL insert
type: "GET",
data: values, //The data your sending to some-page.php
success: function (response) {
$('#loading-image').css('display', 'none');
$('#dropdownCondition').html(response);
filter();
},
error: function () {
console.log("AJAX request was a failure");
}
});

Ajax Call inside JavaScripts using Yii Framework

I am trying to use ajax function inside javascript, but its not calling its goes to failure part,
JS code :
Yii::app()->clientScript->registerScript('my-event-listener',"
$('#dedup_id').change(function(data){
$.ajax({
type: 'POST',
url: '".$this->createUrl('CheckDedupField')."',
data: {crm_base_contact_id:1652},
success: function(msg){
alert('Sucess')
},
error: function(){
alert('failure');
}
});
});
");
My controller code :
public function actionCheckDedupField($id)
{
echo "Inside CheckDedup".var_dump($_POST);
}
Please anyone find out what mistake am doing here.
You have to call ajax url as
url: '".$this->createUrl('checkDedupField')."', // change C to c
In URL, controller function names will start with lower case.
as per the comment. you are calling controller function with wrong name.
Then For missing parameter, change as
data: {id:1652},

JQuery callback to previously defined function

I'm still learning JQuery (and as a result a little JavaScript) but I can't seem to find out how to use a previously defined function in a callback.
Say I have:
<script>
$(document).ready(function() {
function ajax_start() {
alert("starting...");
}
});
</script>
And I wish to use this in another function e.g:
<script>
$(document).ready(function() {
$.ajax({
beforeSend: ajax_start(),
url: "insert_part.php",
type:"POST",
data: "customer="+customer
});
});
</script>
Would this be correct? (I assume not as it doesn't...) what is the proper way of doing a callback?
Close.
$(document).ready(function() {
function ajax_start() {
alert("starting...");
}
$.ajax({
beforeSend: ajax_start, // <== remove the parens
url: "insert_part.php",
type:"POST",
data: "customer="+customer // <== as Skilldrick pointed out,
// remove the trailing comma as well
});
});
You need to do this because
ajax_start() evaluates to the value returned by executing the function named ajax_start, but
ajax_start evaluates to the function itself.
Edit re: OP comment
"how would I include a second function in the callback. Something like- beforesend: ajax_start,other_function (obv. not exactly like that)?"
There are a couple ways to do it. Combine them using an anonymous function:
$.ajax({
// if you need the arguments passed to the callback
beforeSend: function (xhr, settings) {
ajax_start();
other_function();
},
url: "insert_part.php",
type:"POST",
data: "customer="+customer
});
Or just declare a named function that does what you want, and then use it:
function combined_function(xhr, settings) {
ajax_start();
other_function();
}
$.ajax({
beforeSend: combined_function,
url: "insert_part.php",
type:"POST",
data: "customer="+customer
});
Change the value of beforeSend to ajax_start. In other words, remove the parentheses.
With the parentheses, you're calling ajax_start() and setting beforeSend to the return value of ajax_start() (in this case, I believe that would be undefined).
just remove the parentheses, then you are referencing the 'function'-object. The () calls the function, so you would pass the return value of ajax_start.
$.ajax({
beforeSend: ajax_start,
url: "insert_part.php",
type:"POST",
data: "customer="+customer,
});
});

Categories