In my program i have written the jquery like below:
$(document).ready(function() {
$("#toggle").click(function() {
$.post("/project/addhighlight", {
name: "Donald Duck",
city: "Duckburg"
},
function(data, status){
var dataconverted = jQuery.parseJSON(data);
$("#mytext").text(dataconverted);
if (status == "success") { }
});
});
})
What i want to do is to change the $.post url(/project/addhighlight) to the one returned by the backend method once the post is success.
Can any one please advice on how to do it?
You can store the url in a variable which you can update in the callback:
var postUrl = '/project/addhighlight';
$("#toggle").click(function() {
$.post(postUrl, {
name: "Donald Duck",
city: "Duckburg"
},
function(data, status) {
$("#mytext").text(data);
if (status == "success") {
postUrl = data.updatedPostUrl; // your property here...
}
});
});
Note that jQuery.parseJSON(data) is not needed, as jQuery will automatically parse a JSON response when it detects one.
Related
I have this $.Post
function getEmail() {
var dateobj = new Date();
var B = dateobj.toISOString();
var Method = "getSurveysByEmail";
var hash = SHA1(Method + getCookie("userEmail") + B + getCookie("APIKey"));
var requestBody = {
'method': Method,
'email': getCookie("SelectedEntryEmail"),
'authentication': {
'accountID': getCookie("userID"),
'username': getCookie("userEmail"),
'hash': hash,
'datetime': B
},
'take': 1,
'skip': 0
};
$.post('https://surveymechanics.com/api/invitees', JSON.stringify(requestBody),
function (data, status) {
if (status == "success") {
setCookie("SurveyByEmail", JSON.stringify(data["data"]["surveys"]), 1);
} else {
sessionStorage.setItem('SurveyByEmail', JSON.stringify(data['data']['surveys']));
}
});
}
Basicaly checking the network debug, i can see the results for this POST and is a success (as you can see here https://prnt.sc/skddut);
However the code just pass through the
function (data, status) {
if (status == "success") {
alert('hahahahaha');
} else {
sessionStorage.setItem('SurveyByEmail', JSON.stringify(data['data']['surveys']));
}
});
and doesnt save any cookies or save on storage was trying to setup a cookie.
So, I have my JSON file, but I need to send a certain URL to my JSON aswell with a loop.
this is where I set everything:
function setMainObjectArray() {
var exercises = [];
var eBlocks = $('.eBlock');
eBlocks.each(function(i, eBlock) {
var exObject = {
word: $(eBlock).find('input.ExerciseGetWordInput').val(),
syllables: []
};
$(eBlock).find('input.syllable').each(function(j, syll) {
exObject.syllables.push($(syll).val());
});
exercises.push(exObject);
});
return exercises;
}
this is my ajax save function:
function saveExerciseAjaxCall() {
console.log(setMainObjectArray());
$.ajax({
url: 'saveJson.php',
type: 'POST',
data: {
id: getUrlParameter('id'),
getExerciseTitle: $('#getExerciseTitle').val(),
language: $('#languageSelector').val(),
application: 'lettergrepen',
'main_object': {
title: $('#getExerciseTitle').val(),
language: $('#languageSelector').val(),
exercises: setMainObjectArray()
},
dataType: 'json'
}
}).done(function(response) {
}).fail(function(jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
console.log(errorThrown);
console.log(textStatus);
});
}
and I think I need to loop something like this through my function setMainObjectArray()
var audioId = MEDIAARRAY.audio.lowercase.indexOf(exObject['exerciseGetWordInput'].toLowerCase() + '.mp3');
var audio_link = '';
if (audioId > -1) {
exObject['audio'] = 'https://TheUrlServer' + MEDIAARRAY.audio.path + MEDIAARRAY.audio.files[audioId];
}
But I have no idea how to implement this into my function setMainObjectArray. I am not entirely sure if the loop is even written the correct way, i'm quite new to javascript and from there on to put it in my ajax call (since it's a link).
Sorry for title I really didn't know how to describe it.
I have data returned by JavaScript but my data has other data ORM related which i need those as well.
this is my data that returned on selected option:
Object { id: 1, address: "hrktgui erhoutruei9utgy", postalcode: "154785", user_id: 1, city_id: 1, state_id: 10, country_id: 102, created_at: "2018-02-09 13:28:22", updated_at: "2018-02-09 13:28:22" }
I need this data:
address
postalcode
city name (provided under city_id)
state name (provided under state_id)
My issue is to retrieving that city and state name
later i want add this 4 data as hidden input to my view so I can use it for my other function.
here is my js code:
<script type="text/javascript">
$(document).ready(function() {
$('select[name="address_id"]').on('change', function() {
var addressID = $(this).val();
if(addressID) {
$.ajax({
url: '{{ url('addressdetails') }}/'+encodeURI(addressID),
type: "GET",
dataType: "json",
success:function(data) {
$('div#details').empty();
console.log(data['address']);
console.log(data);
// $.each(data, function(key, value) {
// $('div#details').append('<input type="hidden" name="shipment_price" value="'+...+'"><input type="hidden" name="shipment_price" value="'+...+'">');
// });
}
});
}else{
$('div#details').empty();
}
});
});
</script>
my html:
<div id="details"></div>
my function:
public function getAddressDetails($id)
{
$address = Address::findOrFail($id);
return response()->json($address);
}
my route:
Route::get('addressdetails/{id}', 'CartController#getAddressDetails');
its an object. try this.
success:function(data) {
var statename = data.state.name;
var cityname = data.city.name;
}
Edit:
"my issue is to retrieving that city and state names"
your query need to use eager loading
example:
return response()->json(Address::with(['city','state'])->find($id));
in Address Model
class Address {
...
...
public function city(){
return $this->belongsTo(City::class);
}
public function state(){
return $this->belongsTo(State::class);
}
}
Basically I'm creating my own callback and passing it into my method called _ajaxCall().
_ajaxCall() takes the following parameters:
data = an object containing the user submitted data to be POSTed to my server
postURL = the url to post to
callback = a function expression to be called upon successful return of data from the server.
Here is the _ajaxCall() method:
_ajaxCall: function (data, postURL, callback) {
$.post(postURL, {
data : data
}, 'json').done(function (returned) {
switch(returned.success) {
case true:
typeof callback === 'function' && callback(returned);
break;
}
}).fail(function (xhr, textStatus, errorThrown) {
if (status !== 200) {
window.location = document.URL;
}
});
}
commentUpdate : function(self) {
var postURL = '/submission/comment/' + self.attributes.commentId;
var data = {
action: self.attributes.action,
commentId : self.attributes.commentId,
comment: self.attributes.comment
};
var callback = function(returned) {
if (returned.success === true) {
// do something in here
} else {
// do other crap here
}
};
this._ajaxCall(data, postURL, callback);
}
But it's not passing returned to my custom callback() method. Why?
im trying to send values in a form via POST in ajax, how do i capture them in send them, this is wat i have now while in GET
function test(ans_field_uuid){
var result = "";
var url="ajax_pages/remove_answer_field_ajax.php"
url += '?uuid=' + ans_field_uuid;
$.get(
url,
function (data) {
result = data;
}
)
.success(function () {
if (result != "") {
addTableRow('tb_add_field', result);
$('#ajaaxDiv').html(result);
}
})
.complete(function () {
$('#img_create_subcat').hide();
$('#dialog').dialog('close');
})
.error(function () {
alert('An error has occurred.');
});
return false;
}
since you already use jQuery
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
data: name and location are your POST variable.
You can fetch the POST variable in this example in some.php with
$_POST["name"]
which equals "John"
If you want to receive something then like "Hello".
Inside your some.php
echo "Hello";
and it will be send to your ajax function as response in your done function as variable msg
Documentation for jQuery post
// ...
var url = "ajax_pages/remove_answer_field_ajax.php";
$.post( url, "uuid=" + ans_field_uuid, function (data) {
result = data;
}
// ...