Call JSON inside AJAX success - javascript

I want to call a json data inside my AJAX success. I'm still new on manipulating json and AJAX. Can somebody help me on how to access my json data which is from another URL? And I want to compare the id to the JSON data. Here's my code so far:
function getCard(id){
$.ajax({
type: "GET",
data: "id=" + id,
success: function(data){
#call JSON data here from another URL
# Is it possible to call another AJAX here?
}
});
}

This code will work for you
$.ajax({
url: "url",
method: "post",
data: "id=" + id,
success:function(data) {
// success goes here
$.ajax({
url: "url",
async:false,
method: "post",
data: "id=" + id,
success:function(json) {
JSON.parse(json);
// compare data and json here
},
error: function(){
// error code goes here
}
});
},
error: function(){
// error code goes here
}
});

yes Zuma you can call another Ajax inside Success function of Ajax call. Below is the example:
$.ajax({
type: "post",
url: url1,
data: data1,
success: function(data){
$.ajax({
type: "post",
url: url2,
data: data2,
success: function(data){
});
});
});

function getCard(id){
$.ajax({
type: "Get",
url: "发送请求的地址",
data: "id=" + id,
success: function(data){
#call JSON data here from another URL
# if success,you can call another AJAX.
# Is it possible to call another AJAX here?
# yes!
}
});
}

Related

Send Request In Laravel Using AJAX GET Method

Want to Access Show function data through AJAX, but it returns error when i passed id variable in route
Contoller
public function show($id)
{
$features['UnitFeatures'] = UnitFeatures::find($id);
return $features;
}
View Blade File
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var feature_id = $('#unitFeatures').val();
$.ajax({
url: '{{ route('unitfeatures.show',feature_id) }}', // error in this line when i pass feature_id value to route
type: 'GET',
dataType: 'json',
success: function(response){
console.log(response);
}
});
});
Please give me a solution
The problem is that you cannot access a JS variable in your {{}} PHP code.
You will have to get the route uri and replace the placeholder manually in your JS code.
You can get the URI of your Route with this piece of code:
\Route::getRoutes()->getByName('unitfeatures.show ')->uri
This returns the uri as a string like that: /sometext/{id}
Now you can simply replace the {id} with the feature_id by using str.replace() or whatever function you like.
var feature_id = $('#unitFeatures').val();
var origUrl = '{{ \Route::getRoutes()->getByName('unitfeatures.show ')->uri}}';
$.ajax({
url: origUrl.replace('{id}', feature_id),
type: 'GET',
dataType: 'json',
success: function(response){
console.log(response);
}
});
});
Problem With You are using Javascript Variable in PHP Code You can use Javascript Variable After Execution of PHP Code treated as a String.
$.ajax({
url: "{{ route('unitfeatures.show') }}"+'/'+feature_id,
type: 'GET',
dataType: 'json',
success: function(response){
console.log(response);
}
});
});

Issue with nested ajax call in jQuery

I have a situation where I make an ajax call, on returning from which (successfully), I make an another ajax call with the returned data and submit the page. The pseudo code looks something like this:
$.ajax({
url: 'first_page.jsp',
type: 'POST',
dataType: 'JSON',
data: {...}
}).done(function(response) {
$.ajax({
url: '2nd_page.jsp',
type: 'POST',
dataType: 'JSON',
data: {...}
});
thisPage.submit();
});
The inner ajax call is not executed if I do not comment out the 'submit' line. I do not understand the behaviour. Can someone please help me with this.
Thanks
You need to execute submit on second ajax sucess.
For example
$.ajax({
url: '',
type: 'GET',
data: {
},
success: function (data) {
$.ajax({
url: '',
type: 'GET',
data: {
},
success: function (data) {
//do your stuff
}
$("input[type='submit']").click(function(event){
event.preventDefault();
$.ajax({
url:'abcd.php',
method:'post',
type:'json',
async:false,
success:function(response){
$.ajax({
url:'abcde.php',
method:'post',
type:'json',
data:{res:response},
success:function(response){
console.log(response);
}
});
$("form").submit();
}
});
});
Try this one.Its working correctly.

multiple ajax call to single function javascript

I have 3 ajax call. Data from each ajax call is passed to john_doe();
Call 1
$.ajax({
url: url1,
dataType: "JSON",
type: "GET",
}).success(function(data1){
john_doe(data1);
});
Call 2
$.ajax({
url: url2,
dataType: "JSON",
type: "GET",
}).success(function(data2){
john_doe(data2);
});
Call 3
$.ajax({
url: url3,
dataType: "JSON",
type: "GET",
}).success(function(data3){
john_doe(data3);
});
Main function
function john_doe(param){
console.log(param); //Print data from all three ajax call.
}
How to separate data1, data2 and data3 in john_doe function? because I need to carry out arithmetic operation.
Currently,
Input
data1 = one,two,three
data2 = four
data3 = five
Output
console.log(param) would give output as
one
four
five
I want output as
console.log(param[0])
console.log(param[1])
console.log(param[2])
param[0] containing one,two,three
param[1] containing four
param[2] containing five
I dont have control over the data. How to access data1, data2 and data3 separately?
Using promises you can access all the data in Promise.all() callback and do whatever you need with it all at once. Assumes using jQuery 3+. Can use $.when in older versions
var urls =['data-1.json','data-2.json','data-3.json'];
// array of ajax promises
var reqPromises = urls.map(function(url){
return $.ajax({
url: url,
dataType: "JSON",
type: "GET"
});
});
Promise.all(reqPromises).then(function(res){
// res is array of all the objects sent to each `$.ajax` from server
// in same order that urls are in
var param = res.map(function(item){
return item.val
});
console.log(param)
})
DEMO
Quick and dirty solution is simply pass in an identifier, why is this dirty because it isn't really extensible with respect to adding say 4th or 5th call each time you do this you need to add more identifiers and your if statement in the main method will end up pretty ugly at one point. But that said sometimes "Keeping It Simple" is ok.
Main function:
function john_doe(identifier, param) {
// best to use something more readable then numbers
if(identifier == 1) {
console.log(param); //Print data from all ajax call 1.
} else if(identifier == 2) {
console.log(param); //Print data from all ajax call 2.
} else if(identifier == 23) {
console.log(param); //Print data from all ajax call 3.
} else {
// handle bad id
}
}
In your ajax calls, pass in the right identifier, for example Call 2:
$.ajax({
url: url2,
dataType: "JSON",
type: "GET",
}).success(function(data2){
// numeric 2 in in the first param is your identifier
john_doe(2,data2); });
Adding a param to let you know where it is being called from
Call 1
$.ajax({
url: url1,
dataType: "JSON",
type: "GET",
}).success(function(data){
john_doe('call1',data);
});
Call 2
$.ajax({
url: url2,
dataType: "JSON",
type: "GET",
}).success(function(data){
john_doe('call2',data);
});
Call 3
$.ajax({
url: url3,
dataType: "JSON",
type: "GET",
}).success(function(data){
john_doe('call3',data);
});
Main function
function john_doe(call,data){
console.log('Called from : ' + call);
console.log(data); //Print data from all three ajax call.
}
How about this?
Declare an object container to hold your response data values and your arithmetic operation function.
var myParams = {
all_params: [],
getParams: function(){
return this.all_params;
},
setParam: function(index, data){
this.all_params[index] = data;
},
yourArithmeticOperation: function(){
console.log(this.all_params); // your actual logic using all 3 ajax response data
}
}
Then, in your ajax calls:
// call 1
$.ajax({
url: url1,
dataType: "JSON",
type: "GET",
}).success(function(data){
myParams.setParam(0, data); // add ajax 1 response data
});
// call 2
$.ajax({
url: url1,
dataType: "JSON",
type: "GET",
}).success(function(data){
myParams.setParam(1, data); // add ajax 2 response data
});
// call 3
$.ajax({
url: url1,
dataType: "JSON",
type: "GET",
}).success(function(data){
myParams.setParam(2, data); // add ajax 3 response data
});
In case you need all your response data,
// after all three ajax calls
params = myParams.getParams();
console.log(params);
And finally, your arithmetic operation,
myParams.yourArithmeticOperation();
try adding async: false to your ajax calls
$.ajax({
url: url1,
dataType: "JSON",
type: "GET",
async: false,
}).success(function(data){
john_doe('call1',data);
});

My ajax code is not send value to other php page?

My ajax code is not send value to other php page??
I want to delete value coming from database ajax code get id that come from database but not sent to other php page where delete code.
<script type="text/javascript">
function deleteBox(id){
if (confirm("Are you sure you want to delete this record?")){
var dataString = id;
$.ajax({
type: "POST",
url: "del.php",
data: dataString,
cache: false,
success: function(){
}
});
}
}
</script>
try below code:
var dataString = id;
$.ajax({
type: "POST",
url: "del.php?datastring="+id,
//data: dataString,
cache: false,
success: function(){
}
});
or
var dataString = id;
$.ajax({
type: "POST",
url: "del.php",
data: {datastring:id},
cache: false,
success: function(){
}
});
send data with parameter name and value not only value, like this
data: {'id':dataString},
please correct this in ajax call. you can pass the data from one page to another page using data. like data : {var1:value1,var2:value2,var3:value3}
$.ajax({
type: "POST",
url: "del.php",
data: {dataString: dataString},
cache: false,
success: function(){
}
});

Jquery set HTML via ajax

I have the following span:
<span class='username'> </span>
to populate this i have to get a value from PHP therefor i use Ajax:
$('.username').html(getUsername());
function getUsername(){
$.ajax({
type: 'POST',
url: myBaseUrl + 'Profiles/ajax_getUsername',
dataType: 'json',
data: {
},
success: function(data){
document.write(data);
}
})
}
Now when i debug i see that the returned data (data) is the correct value but the html between the span tags stay the same.
What am i doing wrong?
Little update
I have tried the following:
function getUsername(){
$.ajax({
type: 'POST',
url: myBaseUrl + 'Profiles/ajax_getUsername',
dataType: 'json',
data: {
},
success: function(data){
$('.username').html('RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRr');
}
})
}
getUsername();
Still there is no html between the tags (no text) but when i look at the console the method is completed and has been executed.
Answer to the little update
The error was in my Ajax function i forgot to print the actual response! Thank you for all of your answers, for those of you who are searching for this question here is my Ajax function:
public function ajax_getUsername(){
if ($this->RequestHandler->isAjax())
{
$this->autoLayout = false;
$this->autoRender = false;
$this->layout = 'ajax';
}
print json_encode($this->currentClient['username']);
}
Do note that i am using CakePHP which is why there are some buildin methods. All in all just remember print json_encode($this->currentClient['username']);
The logic flow of your code is not quite correct. An asynchronous function cannot return anything as execution will have moved to the next statement by the time the response is received. Instead, all processing required on the response must be done in the success handler. Try this:
function getUsername() {
$.ajax({
type: 'POST',
url: myBaseUrl + 'Profiles/ajax_getUsername',
dataType: 'json',
data: { },
success: function(data){
$('.username').html(data); // update the HTML here
}
})
}
getUsername();
Replace with this
success: function(data){
$('.username').text(data);
}
In success method you should use something like this:
$(".username").text(data);
You should set the html in callback
function getUsername() {
$.ajax({
type: 'POST',
url: myBaseUrl + 'Profiles/ajax_getUsername',
dataType: 'json',
data: {
},
success: function(data){
$('.username').html(data);
}
})
}
Add a return statement for the function getUsername
var result = "";
$('.username').html(getUsername());
function getUsername(){
$.ajax({
type: 'POST',
url: myBaseUrl + 'Profiles/ajax_getUsername',
dataType: 'json',
data: {
},
success: function(data){
document.write(data);
result = data;
}
})
return result;
}
You can use .load()
Api docs: http://api.jquery.com/load/
In your case:
$('.username').load(myBaseUrl + 'Profiles/ajax_getUsername',
{param1: value1, param2: value2});

Categories