I wanted to make a button when I clicked it called that ajax function to send data to a function then the function returns the data back to the ajax so that it can execute the success call which makes the button become disabled.
Here's the function notify()
public function notify()
{
$id = $this->user['id'];
$agent = AffiliateAgents::get($id);
if (empty($agent)) redirect('affiliate/sales/browse');
$_POST = array_map('trim', $_POST);
$agent = [
'commission_claim' => 1
];
AffiliateAgents::update($id, $agent);
$status = AffiliateAgents::get($id ,'commission_claim');
return $status;
}
Here's the ajax
$("#notify").click(function() {
$.ajax({
url: 'affiliate/sales/notify',
success: function() {
showNotification("success", "Berjaya!", "Anda berjaya membuat tuntutan komisyen");
}
});
})
just pass parameter into success function in this line:
...
success: function(yourData) {
...
As you wanted to disable the buttons after the success of Ajax.
You have to write the following code
in ajax part
success : function(data){
// disable button
if(data="success"){
$("#buttonId").attr("disabled","disabled");
} else{
alert("Status not success");
}
}
You can get the returned data (from PHP) like this:
//In the ajax...
success: function(data) {
console.log(data)
}
success Type: Function( Anything data, String textStatus, jqXHR jqXHR
) A function to be called if the request succeeds. The function gets
passed three arguments: The data returned from the server, formatted
according to the dataType parameter or the dataFilter callback
function, if specified; a string describing the status; and the jqXHR
(in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the
success setting can accept an array of functions. Each function will
be called in turn. This is an Ajax Event.
http://api.jquery.com/jquery.ajax/
Related
I had a question;
How would one call multiple PHP functions and output them onto the page?
Now i have found a way, could anyway let me know how i could improve my answer.
It works perfectly, I just want to see what could be a better way.
AJAX CALL;
$.ajax({
url: 'functioncalls.php', //URL TO PHP FUNCTION CONTROL
data: {call: 'Login', parameters: {Username, Password}}, //CALL the function name with an array of parameters
type: 'post'
}).done( function( Output ){
try{
Output = JSON.parse(Output); // see if out put is json as that is what we will pass back to the ajax call
} catch (e){
alert('Error calling function.');
}
});
PHP "functioncalls.php" page
if(isset($_POST['call']) && !empty($_POST['call'])){ //check if function is pasted through ajax
print call_user_func_array($_POST['call'], $_POST['parameters']);//dynamically get function and parameters that we passed in an array
}
PHP FUNCTION - make sure your function is either on the page or included
function Login($Username, $Password){
// function control
return json_encode($return);// return your json encoded response in value or array as needed
}
And that's that, Nothing else needed you can call any function and use it in your done ajax promise.
Note: Your parameters have to be passed as an array.
Thank you
change your ajax request like this
$.ajax({
url: 'functioncalls.php', //URL TO PHP FUNCTION CONTROL
data: {call: 'Login', parameters: JSON.stringify([Username, Password])}, //CALL the function name with an array of parameters
type: 'post'
}).done( function( Output ){
try{
Output = JSON.parse(Output); // see if out put is json as that is what we will pass back to the ajax call
} catch (e){
alert('Error calling function.');
}
});
in php you have to do something like this:
$params = json_decode($_POST['parameters']);
login($params[0], $params[1]);
I have written a simple page which have a form input. While a user prints text at the form a script gets request on server and take JSON data. I need to pass a value from the input to a function which reprocess the value.
var search = document.querySelector('#search');
function iReceived(msg) {
var mass = msg.data;
mass.map(function(e) {
var city = document.querySelector('#city');
var newLi = document.createElement('li');
newLi.innerHTML = e.Description;
city.appendChild(newLi);
});
};
function Foo(e) {
$.ajax({
type: "POST",
dataType: 'jsonp',
url: "https://api.novaposhta.ua/v2.0/json/",
data: {
"modelName": "Address",
"calledMethod": "getCities",
"methodProperties": {},
"apiKey": "6f94a6391cb5134ee68ddb7924de2a3d"
},
success: iReceived, /* this function I would like to pass value input
but I can write just a reference on this
function without () and arguments */
});
console.log(e.target.value);
};
search.oninput = Foo;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<form>
<input type="text" id="search" onchange="Foo()">
</form>
<div id="content"></div>
<div id="city"></div>
May have I built this program a bad way?
Have you read the jQuery docs?
success Type: Function( Anything data, String textStatus, jqXHR jqXHR
)
A function to be called if the request succeeds. The function gets
passed three arguments: The data returned from the server, formatted
according to the dataType parameter or the dataFilter callback
function, if specified; a string describing the status; and the jqXHR
(in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the
success setting can accept an array of functions. Each function will
be called in turn. This is an Ajax Event. timeout
So in your case you would modify your Foo() functions success method like below
function Foo(e) {
$.ajax({
type: "POST",
dataType: 'jsonp',
url: "https://api.novaposhta.ua/v2.0/json/",
data: {
"modelName": "Address",
"calledMethod": "getCities",
"methodProperties": {},
"apiKey": "6f94a6391cb5134ee68ddb7924de2a3d"
},
success: function(data) {
// the data is the data returned from the server
// do whatever you want with the data here
// get the value you need for iReceived here.
iReceived(value); /* this function I would like to pass value input
but I can write just a reference on this
function without () and arguments */
}
});
console.log(e.target.value);
};
I can't comment yet but here is a good starting point:
You should start by having the user submitting their data with a button before it runs the function. As soon as you input any text into that box the json request fires off with one character, then two, and so on.
Currently what ever you put into that box returns 2070 results that are all objects, I'm not sure of the formatting of the api but you should try to call just the part of the objects/array that you need.
I have a quiz type application. Each question has two answers with a value of 1 or 2. When the quiz is complete, if they have a score lower than 10, they get redirected to a page.
This is my code for this part.
while (n < numResults) {
increment = minScore + (interval * n);
if (totalScore <= increment) {
if(totalScore <= 10) {
$.ajax({
method: "POST",
url: "handleData.php",
dataType: "json",
data: { answers: ansArray, page: window.location.href }
})
.done(function( msg ) {
window.location.href("www.page2.html");
});
}
return;
} else {
n++;
}
}
I have a few things I am trying to solve. Firstly, before the redirect, some data (answers and url) is posted to PHP so I can process it. One thing I pass is the current window url. The reason I do this is because the
url has a format like
www.page1.com?a=1&b=2&c=3
In PHP, I parse this url and grab the values.
My first problem is that although the data is successfuly sent to PHP and handled, and returns a response of Success, the done function never seems to fire, therefore no redirect occurs (I put an alert in this function
to ensure it is not firing). In PHP, after I process the data, I do this
var_dump($response); //Outputs Success
return json_encode($response);
The second thing I am trying to work out is the redirect url (page2.html). Within this page, I have a button. This button has a standard link, and then I need to give it some params from the initial url.
So this pages button might be something like
www.externallink.com?a=1&c=2
How can I get the original URLs params into a button on the redirected url?
Thanks
USE below function insted of done:
$.ajax({
method: "POST",
url: "handleData.php",
dataType: "json",
data: { answers: ansArray, page: window.location.href }
success:function(data){
window.location.href("www.page2.html");
});
})
For your 1st part:
Try putting the error function of jQuery ajax call. Sometimes when the return type of result does not match with the expected datatype of ajax call, then result comes in the response of error.
error: function (data, status, e) {
}
For your 2nd part:
Attach click event for the button in the handler and read the current URL query string using window.location.search and then redirect using
window.location = newURL + "extra query params";
// Assign handlers immediately after making the request,
// and remember the jqXHR object for this request
var jqxhr = $.ajax( "example.php" )
.done(function(data, textStatus, jqXHR) {
alert( "success" );
})
.fail(function(jqXHR, textStatus, errorThrown) {
alert( "error" );
})
.always(function(data|jqXHR, textStatus, jqXHR|errorThrown) {
alert( "complete" );
});
If you .done() callback never invoked, try to set debuggers or alerts inside .fail() or .complete() callback functions. Check if you have an error during ajax call and at all if the call has complete statement.
Here more information: http://api.jquery.com/jquery.ajax/
I have no idea how I can achieve this.
I am using jQuery 1.9 for ajax call back.
I have a function, let's say:
function a (param){
//calling a function this will perform ajax
data = performAjax(param, url, etc);
// render response
renderResponse(data);
}
We are executing our ajax in perform ajax function.
Issue is when ajax fails then it perform ajaxError function.
I put a message in div that please refresh this again.
But how can I get function a and all the parameter of that in ajaxError function? So that I can put a link to refresh again.
Not sure if I understand correctly, but here it goes:
function performAjax() {
return $.ajax({
....
});
}
var lastFailedFunction;
function a (param){
var args = arguments;
//calling a function this will perform ajax
performAjax().then(function(data) { // on success
// render reponse
renderResponse(data);
}, function() { // on failure
lastFailedFunction = function() {
a.apply(a, args);
};
// now you can call lastFailedFunction() to try again
});
}
When the ajax-call fails, it will store the failed function call to lastFailedFunction. So somewhere else you might show this message:
<div>Function A failed, click here to try again</div>
Using error callback of ajax, you can get the error message
function a(param) {
var performAjax = $.ajax({
type: "",
url: "",
data: "",
success: function(msg){
//success msg
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
//can access param of fun a and the error message
//append it to the body
$('body').append('<div>'+param+' error: '+errorThrown+'</div>');
}
});
}
I am reading a book about asp.net MVC and I found different methods for calling Action methods that return JSON:, either using Ajax OR getJSOn, so are these two methods equivalent to:-
$.ajax({
type: "GET",
url: "http://localhost:11279/test/testcall",
dataType: "json",
success: function (result) {
var message = result.Title + ": $" + result.CurrentPrice;
$('#Result').html(message);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Error: " + errorThrown);
}
});
And the getJSON is:-
<script type="text/javascript">
$(function () {
$.getJSON("http://localhost:11279/test/testcall",
function (data) {
$.each(data, function (key, val) {
var str = val.Description;
$('<li/>', { html: str }).appendTo($('#auctions'));
});
});
});
</script>
Second question
if I want to call the above action method or an external web service from a controller class instead of using javaScript, so which c-sharp methods I should use ?, and how I am going to pass the returned JSON from the controller class to the view.
BR
getJson-
Method allow get json data by making ajax call to page. This method allows only to pass the parameter by get method posting parameter is not allowed.
Ajax ()- This method provide more control than all other methods we seen. you can figure out the difference by checking the list of parameter
Provide more control on the data sending and on response data.
Allow to handle error occur during call.
Allow to handle data if the call to ajax page is successfull.
Answer to 2
You can make use of jquery + Ajax() function to consume it in your html page..
here is article for you : Steps to Call WCF Service using jQuery.
something like this
function WCFJSON() {
var userid = "1";
Type = "POST";
Url = "Service.svc/GetUser";
Data = '{"Id": "' + userid + '"}';
ContentType = "application/json; charset=utf-8";
DataType = "json"; varProcessData = true;
CallService();
}
//function to call WCF Service
function CallService() {
$.ajax({
type: Type, //GET or POST or PUT or DELETE verb
url: Url, // Location of the service
data: Data, //Data sent to server
contentType: ContentType, // content type sent to server
dataType: DataType, //Expected data format from server
processdata: ProcessData, //True or False
success: function(msg) {//On Successfull service call
ServiceSucceeded(msg);
},
error: ServiceFailed// When Service call fails
});
}