Ajax function to PHP - javascript

I have two problems here, 1st the code below won't work, anybody could tell me what am i missing? 2nd, i want to return the value from php to success function and then that value also will be returned to the parent function...
function myFunc(e){
$.ajax({
type: "post",
url: "path/myPhp.php",
data: "val="+e,
dataType: "php",
success: function(result){
return result; //i want this result to be returned to parent function myFunc(e)
},
error: function(e){
alert('Error: ' + e);
}
});
}

There is no data type named php for jquery ajax.
legal data type is as below:
xml
html
script
json
jsonp
text
Do you mean "json" data type?

If you want your response to return as function return value, then you need to make it ajax synchronize and later ajax unsynchronize after ajax finish
If your return response is not array ,then I think this will work.
function myFunc(e){
var returnValue = '';
$.ajaxSetup({async:false}); // synchronize
$.ajax({
type: "post",
url: "path/myPhp.php",
data: "val="+e,
success: function(result){
returnValue = result;
},
error: function(e){
alert('Error: ' + e);
}
});
$.ajaxSetup({async:true});// Unsynchronize
return returnValue;
}

1) You have an invalid value in 'dataType'. Valid values are: xml, json, script, or html.
2) As I see it, you want the ajax call to behave in a synchronous way.
Use 'async: false' to accomplish that. Try:
function myFunc(e){
var value = "";
$.ajax({
type: "post",
url: "path/myPhp.php",
data: "val="+e,
dataType: "json",
success: function(result){
value = result;
},
error: function(e){
alert('Error: ' + e);
},
async: false // set synchronous
});
alert(value); // use value
}
Or
$.ajaxSetup({async:false});
before issuing $.ajax() call.
A discussion about using synchronous ajax can be found here How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?

Related

A part of AJAX response storing in PHP variable

I need to store a piece of data, into PHP variable, which is received through AJAX response in an input box. How can I do this?
<script type="text/javascript">
$(document).ready(function() {
$("#user_id").change(function() {
var id = $(this).val();
var dataString = 'user_id='+ id;
$.ajax({
type: "POST",
url: "wmat_details.php",
data: dataString,
cache: false,
success: function(result) {
var data = result.split(",");
$('#name').val(data[0]);
$('#email').val(data[1]);
$('#ref_id').val(data[2]);
$('#candidature_start').val(data[3]);
$('#candidature_end').val(data[4]);
$('#default_attempts').val(data[5]);
$('#existing_complimentary').val(data[6]);
$('#wmat_start').val(data[9]);
$('#wmat_end').val(data[10]);
$('#attempts_taken').val(data[11]);
}
});
});
});
</script>
As shown in above code, I want to store $('#attempts_taken').val(data[11]); this value to a PHP variable. Any insight is appreciated.
Unfortunately you can't.
PHP is server side while jQuery (JS) is client side. They are two separate layers of abstraction that interact only when the client call the server.
I don't have enough informations about what you need to do with data[11] but it seems that you have only one option: make a consecutive AJAX call to the php file that will manipulate data[11].
The consecutive AJAX call must be executed from inside the first call success callback; something like this:
success: function(result){
// Your on success logic
// ...
// Prepare the object to send to the server
var objData = {};
objData.attemptsTaken = data[11];
// Execute the second AJAX call to the server
$.ajax({
type: "POST",
url: "second_call_destination_file.php",
data: objData,
success: function(result){
// Do something on success
},
error: function(){
// Do something on error
},
complete: function(){
// Do something on complete (executed after success and error)
}
}
You cannot store ajax response into a php variable.
way 1 :
You can make another ajax call.
way 2 :
you can set session.

Callback with javascript and jquery

I am more of a java developer and am having difficulty with javascript callback. I am wondering if any experts here would help me out of my struggle with this code.
I am trying to pull our locations from db and populating in an array. On first load i am trying to refresh all locations and I am having trouble to control the flow of execution and loading values. Below is the code and I have put in the output at the end.
JQUERY CODE:
// load all locations on first load.
refreshLocations();
$("#locInput").autocomplete({source: locationData});
}); // end of document.ready
// function to refresh all locations.
function refreshLocations() {
getLocationArray(function(){
console.log("firing after getting location array");
});
}
// function to get the required array of locations.
function getLocationArray() {
getJsonValues("GET", "getLocalityData.php", "", getLocalityFromJson);
}
// function to pick up localities from json.
function getLocalityFromJson(json){
if (!json) {
console.log("====> JSON IS NOT DEFINED !! <====");
return;
} else {
console.log("json is defined so processing...");
var i = 0;
$.each(json.listinginfo, function() {
var loc = json.listinginfo[i].locality;
locationArray[i] = loc;
console.log("added location ->" + locationArray[i]);
i++;
});
}
//return locationArray;
}
// function to get raw json from db.
function getJsonValues(type, url, query, getLocalityFromJson) {
var json;
// if the previous request is still pending abort.
if (req !== null)
req.abort();
var searchString = "";
if (query !== "") {
searchString = "searchStr" + query;
}
console.log("searchString : (" + query + ")");
req = $.ajax({
type: type,
url: url,
data: searchString,
contentType: "application/json; charset=utf-8",
dataType: "text",
success: function(result) {
json = JSON.parse(result);
console.log("========start of json
return============");
console.log(JSON.stringify(json));
console.log("========end of json
return============");
//return json;
}
});
getLocalityFromJson(json);
return json;
}
the output from above code is as follows:
searchString : () (18:25:36:473)
at locality1.php:74
====> JSON IS NOT DEFINED !! <==== (18:25:36:518)
at locality1.php:48
========start of json return============ (18:25:37:606)
at locality1.php:83
{"listinginfo":[{"listing":"1","locality":"birmingham"},
{"listing":"2","locality":"oxford"}]} (18:25:37:624)
at locality1.php:84
========end of json return============ (18:25:37:642)
at locality1.php:85
>
Help will be greatly appreciated.
call getLocalityFromJson(json); inside your success callback
function getJsonValues(type, url, query, getLocalityFromJson) {
var json;
// if the previous request is still pending abort.
if (req !== null)
req.abort();
var searchString = "";
if (query !== "") {
searchString = "searchStr" + query;
}
console.log("searchString : (" + query + ")");
req = $.ajax({
type: type,
url: url,
data: searchString,
contentType: "application/json; charset=utf-8",
dataType: "text",
success: function(result) {
json = JSON.parse(result);
console.log("========start of json return============");
console.log(JSON.stringify(json));
console.log("========end of json return============");
//return json;
getLocalityFromJson(json);
}
});
}
You need to call getLocalityFromJson(json) and return json inside your ajax success function. Ajax requests are asynchronous, there's no guarantee that the request will be finished by the time you get to the lines getLocalityFromJson(json); return(json); where they are currently.
The call back functions from a jquery ajax call is complete, failure, success, etc..
Success is called after a request is successful,
Failure is called if theres something like an error 500, or a 404, or w/e.
Complete is Always called after a ajax call.
If you want your code to just follow sequence like in java, throw async: false into your ajax call.. but I wouldnt' recommend this as it defeats the purpose of using this method, and also locks up your browser.
You should make sure you are waiting for the request to finish before moving on - so put code in the success function that you want to run AFTER the request has finished fetching your data.
I think you need to remember Ajax is running async, so you need to follow this thread to execute your refresh.

What are the differences between Ajax & getJSON when calling an action method that return JSON

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
});
}

javascript waiting for return before proceeding

I have an issue with my javascript not waiting for the return of the call. I already now that javascript is asynchronous so I would like to know how to make this method call wait for the result. I do not have control over the first two snipper since they are uploaded by the user. I can use jquery or pure javascript. Advance thanks!
I have this javascript call
var value = somemethod("cmi.location");
/ /This is not getting set since it does not wait. alerts 'undefined'
alert(value);
and somemethod looks something like the code below,
function somemethod(element){
var result;
result = API1.GetValue(element);
return result;
}
API is a window object instantiated by doing the code below. I have access to the code snippets from this point on.
var API1 = new API();
API is an object in javascript which looks like this:
function API(){
};
API.prototype.GetValue=API_GetValue;
function API_GetValue(parameter){
$.ajax({
type:"POST",
async:false,
url:"method.do",
dataType:"xml",
data: {action: 'getValue', parameter: parameter, value: ''},
success:function(data){
//I am getting 0 here
return $(data).find('search').text();
}
});
}
function API_GetValue(parameter){
var newdata;
$.ajax({
type:"POST",
async:false,
url:"method.do",
dataType:"xml",
data: {action: 'getValue', parameter: parameter, value: ''},
success:function(data){
//I am getting 0 here
newdata = $(data).find('search').text();
}
});
return newdata;
}
you can also do something like this:
function API_GetValue(parameter){
var newdata = $.ajax({
type:"POST",
async:false,
url:"method.do",
dataType:"xml",
data: {action: 'getValue', parameter: parameter, value: ''}
}).responseText;
return $(newdata).find('search').text();
}

Modifying jQuery $.ajax() success method during request

In the web app I am working on there is potential for very long running ajax queries.
I'm using jQuery's $.ajax method to do something like:
this._xhr = jQuery.ajax({
type: "GET",
url: "/path/to/service",
data: "name=value",
success: function(data, message){
// handle a success
},
dataType: "json"
});
Is there a way to modify the success callback after this._xhr.readyState = 2 (loaded) and before this._xhr.readyState = 4 (completed)
I tried modifying this._xhr.onreadystatechange but found that jQuery does not define onreadystatechange.
The abort method sounds like the best option to me.
I don't know much about the ajax method internals, but I can think of a few ways to do what you want. Both involve global state and would break if it's possible for your user to send a second request before the first has finished, so I'm not sure I recommend them.
First, you could keep a reference to the method that does your success work, and change it:
MySuccessMethod = function(d, m) { /* handle a success */ };
this._xhr = jQuery.ajax({
type: "GET",
url: "/path/to/service",
data: "name=value",
success: function(data, message){ MySuccessMethod(data, message); },
dataType: "json"
});
// later...
// user cancels request, so change the success method
MySuccessMethod = function(d, m) { /*print a simple message*/ }
Alternatively, you could just put all the logic in the one success method, and use a global flag to determine what to do:
success: function(data, message){
if (RequestHasBeenCancelled) {
//display a simple message
}
else {
// handle a success
}
},

Categories