AJAX data is sent empty to PHP Function - javascript

I need to send the id of an element and a value (1,2,3) through ajax to a PHP document that checks if the data is empty (which is always). The two values I'm trying to send are correctly logged on the console though.
$(document).ready(function() {
$('.status-menu-option-1').click(function(){
changeLabelStatus(1);
});
$('.status-menu-option-2').click(function(){
changeLabelStatus(2);
});
$('.status-menu-option-3').click(function(){
changeLabelStatus(3);
});
function changeLabelStatus(status){
var parent = $(event.target).parent().parent().parent().attr('id');
console.log(status);
console.log(parent);
$.ajax({
url: 'team/canva_change_label',
type: "GET",
data: {
status : status,
row : parent
},
success: function(msg) {
if(msg.error) {
alert(msg.error_msg);
return;
}
}
});
}
}
I know I'm doing something wrong but I can't point what.

$(document).ready(function() {
$('.status-menu-option-1').click(function(e){
changeLabelStatus(e.target, 1);
});
$('.status-menu-option-2').click(function(e){
changeLabelStatus(e.target, 2);
});
$('.status-menu-option-3').click(function(e){
changeLabelStatus(e.target, 3);
});
function changeLabelStatus(element, status){
var parent = $(element).parent().parent().parent().attr('id');
console.log(status);
console.log(parent);
$.ajax({
url: 'team/canva_change_label',
type: "GET",
data: {
status : status,
row : parent
},
success: function(msg) {
if(msg.error) {
alert(msg.error_msg);
return;
}
}
});
}
}
You need to pass in the element that the event resulted from, rather than relying on the event being a global variable, which is not standard behavior for all browsers.
Also, you should be able to use a form of closest(selector) instead of all those chained parent calls, but without seeing the markup I can't suggest a proper selector.

Related

Calling ajax request continually until a certain search request is found

I am trying to keep sending AJAX GET requests to a certain page that inputs from a cgi script until a specific set of keystrokes shows up.
However, my requests aren't coming up continuously, in fact they aren't even taking place when I am using a function and trying to call the function. I had to use the complete with the success, because for whatever reason, with the success I could not properly store the value retrieved.
Here is what I have:
function posts() {
$.ajax({
type: "GET",
url: 'http://checkvaluestatus.sh',
success: function(data) {
alert(data_response.responseText);
},
complete: function(data_response) {
alert(data_response.responseText);
var viewport = data_response.responseText;
var version = viewport.match(/Release:[^=]*/);
if (version != null) {
console.log(version);
} else {
posts();
}
},
error: function() {
console.log('failed');
posts(); //calling the ajax again.
}
});
Is there not a way to keep sending requests based on a condition being met and having the value still stored?
This is my AJAX call that worked to print the value:
$.ajax({
url: 'http://checkvaluestatus.sh',
type: "GET",
dataType: "json",
success: function(data) {
alert(data_response.responseText);
},
complete: function(data_response) {
alert(data_response.responseText);
var viewport = data_response.responseText;
var version = viewport.match(/Release:[^=]*/);
document.write(version);
},
});
salam,
the value you are looking for in success function is the 'data' ,not "data_response.responseText" because in "success" function data is your response text ,but in the "complete" function "data_response" is a jqXHR object contain more information.
to print your text in success function replace
alert(data_response.responseText);
by
alert(data);
for more details "jquery.ajax"

Determine ajax call finished to run another ajax call

In my project I have some select option group which load ajax data depending on previous value. Now I am having problem when I am trying to copy them to another select option group.
here is the scenario
parmanet address Present Address
Division Division
District District
Upzilla Upzilla
Union Union
All of them are select field and after select each field next select option loaded by ajax. I put a checkbox and when user click the checkbox, parmanent address data should copy to present address with all the ajax call.
Now The problem is, the jquery "val" function not working because it runs before the data loaded from ajax. If I put delay to 100 ms, it working, but It's not a proper way. Is there any better way to solve this problem??
This is my code when i change division to load ajax data to division, and other option is same as like this.
$('#divisions').change(function() {
$("#villtable").hide();
$("#villaddform").hide();
$.ajax({
type: 'post',
url: 'GetDistricts',
data: {
get_option:this.value
},
success: function(response) {
document.getElementById("districts").innerHTML=response;
}
});
});
And this is what i tried to copy data to present address group...
$.when( $('.division-prese').val(divi).trigger('change').delay( 100 ) ).then(function() {
$.when( $('.district-prese').val(dist).trigger('change').delay( 100 ) ).then(function() {
$.when( $('.upazilla-prese').val(upaz).trigger('change').delay( 100 ) ).then(function() {
$('.union-prese').val(unio).trigger('change');
});
});
});
i also tried 'done', but still not working.
General idea of extracting the logic and using it in two places, one of which performing the promise chaining.
function loadDistricts ($divisions) {
return $.ajax({
type: 'post',
url: 'GetDistricts',
data: {
get_option: $divisions.val()
},
success: function(response) {
$('#districts').html(response);
}
});
}
//... other methods
var $divisions = $('#divisions');
var $districts = $('#districts');
var $upazillas = $('#upazillas');
$divisions.change(function() {
$("#villtable").hide();
$("#villaddform").hide();
loadDistricts($divisions);
});
//... other change methods
$('.division-prese').val(divi);
loadDistricts($divisions).then(function(){
$('.district-prese').val(dist);
loadUpazillas($upazillas).then(function(){
$('.upazilla-prese').val(upaz);
//call next thing
});
});
try adding return before your call
$('#divisions').change(function() {
$("#villtable").hide();
$("#villaddform").hide();
return $.ajax({
type: 'post',
url: 'GetDistricts',
data: {
get_option:this.value
},
success: function(response) {
document.getElementById("districts").innerHTML=response;
}
});
});

Passing "this" inside a promise?

I am trying to learn about promises.
My URL will contain three ID parameters, e.g.
#org=123&num=145&denom=467
and I want to use these to select the values of three select elements on my page (each one with an Ajax source), e.g.
<select id="org"><option selected val="123">Birmingham University</option></select>
<select id="num"><option selected val="145">Maths</option></select>
<select id="denom"><option selected val="467">English</option></select>
The complicated bit is that I need to do an Ajax request for each ID, so that I can pre-fill the name part of the option as well as the ID.
Then once all three requests are complete, I want to continue to render the rest of the page.
I've got most of the way there, but I'm stuck on how to get the value of this inside the getNumerators function. Can anyone help?
setUp: function() {
// use hash to set this.globalOptions
var _this = this;
_this.setFormValues().then(function() {
this.setUpRestOfForm ...
};
},
setFormValues: function() {
return _this.getOrgs()
.then(_this.getNumerators)
.then(_this.getDenominators)
.then(function() {
return true;
}
});
},
getOrgs: function() {
return $.ajax({
type: 'GET',
url:'/api/orgs/?q=' + this.globalOptions.orgId,
dataType: 'json'
});
},
getNumerators: function(orgIds) {
// FAILS: Cannot set property 'orgIds' of undefined
this.globalOptions.orgIds = orgIds;
var url = '/api/subjects/?q=' + this.globalOptions.numId;
return $.ajax({
type: 'GET',
url: url,
dataType: 'json'
});
}
Any other advice on the way I'm doing this would also be gratefully received.
You can use Funtion.bind()/$.proxy() to pass a custom execution context
setFormValues: function() {
return _this.getOrgs()
.then(_this.getNumerators.bind(_this)) //using bind() - supported in IE9+
.then($.proxy(_this.getDenominators, _this)) //using $.proxy()
.then(function() {
return true;
}
});
}
or you can pass a custom context using context option in ajax
getOrgs: function() {
return $.ajax({
type: 'GET',
url:'/api/orgs/?q=' + this.globalOptions.orgId,
dataType: 'json',
context: this
});
},

I need to get a variable between jQuery function and AJAX

I have two buttons on the form I'm getting, this first piece of coce allow me to know which was the button clicked by getting the id of it.
var button;
var form = $('.register_ajax');
$('#vote_up, #vote_down').on("click",function(e) {
e.preventDefault();
button = $(this).attr("id");
});
and this other send the form data through AJAX using the info already obtained from the button using the script above.
form.bind('submit',function () {
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
cache: false,
dataType: 'json',
data: form.serialize() + '&' + encodeURI(button.attr('name')) + '=' + encodeURI(button.attr('value')) ,
beforeSend: function() {
//$("#validation-errors").hide().empty();
},
success: function(data) {
if(data.message == 0){
$("#fave").attr('src','interactions/favorite.png');
$("#favorite").attr('value',1);
console.log(data.errors);
}
if(data.message == 1)
{
$("#fave").attr('src','interactions/favorite_active.png');
$("#favorite").attr('value',0);
}
if(data.message == "plus")
{
$("#vote_up").attr('class','options options-hover');
$("#vote_down").attr('class','options');
console.log(data.message);
}
if(data.message == "sub")
{
$("#vote_down").attr('class','options options-hover');
$("#vote_up").attr('class','options');
console.log("sub");
}
},
error: function(xhr, textStatus, thrownError) {
console.log(data.message);
}
});
return false;
});
The problem is that the data is not being passed to the ajax function, the button info is being saved on the button var, but it's not being obtained at time on the ajax call to work with it (or at least that is what I think). I'd like to know what can I do to make this work, any help appreciated.
1st edit: If I get the button data directly like button = $('#vote_up'); it doesn't work either, it only works if I get the button directly like this but without using the function.
2nd edit: I found the solution, I posted below.
var button is in the scope of the .on('event', function(){})
You need to declare the variable in the shared scope, then you can modify the value inside the event callback, i.e.
var button,
form = $('.register_ajax');
$('#vote_up, #vote_down').on("click",function(e) {
e.preventDefault();
button = $(this).attr("id");
});
You are being victim of a clousure. Just as adam_bear said you need to declare the variable outside of the function where you are setting it, but you are going to keep hitting these kind of walls constantly unless you dedicate some hours to learn the Good Parts :D, javascript is full of these type of things, here is a good book for you and you can also learn more from the author at http://www.crockford.com/.
I Found the solution, I just changed a little bit the click function like this:
var button;
var form = $('.register_ajax');
var data = form.serializeArray();
$('#vote_up, #vote_down').on("click",function(e) {
e.preventDefault();
button = $(this).attr("id");
data.push({name: encodeURI($(this).attr('name')), value: encodeURI($(this).attr('value'))});
form.submit();
});
using e.preventDefault(); and form.submit(); to send the form. also I changed the data.serialize to serializeArray(); because it's more effective to push data into the serializeArray(). in the second script I just changed the data.serialize() and used the data variable that I already filled with the serializeArray() and the data.push():
form.bind('submit',function () {
alert(button);
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
cache: false,
dataType: 'json',
data: data,
//here goes the rest of the code
//...
});
return false;
});
it worked for me, it solved the problem between the click and submit event that wasn't allowing me to send the function through ajax.

jquery ajax data is not printing in parent element

my problem is when i try to show a value by ajax calling,it shows the value to "generic" class but when i try to show it on the parent row it is not showing anything.
here is my ajax code
$.ajax({
type: 'POST',
url: 'http://localhost/medical/index.php/purchase/test',
data: 'data=' + pid,
success: function() {
$.get('http://localhost/medical/index.php/purchase/test', function(data) {
$(this).parents('tr').find('.generic').html(data); // doesn't show the value
$( ".generic" ).html(); // this show the value but in all table row
});
}});
Thanks in Advance
The problem is called scope. this in context of the anonymous function means something else than it means outside. You can do it like this
var that = this;
$.ajax({
...
success: function() {
$.get(..., function(data) {
$(that).parents('tr').find('.generic').html(data);
});
}
});

Categories

Resources