Mireille28 Mireille28 - 5 months ago 9
Ajax Question

Sending data via ajax post using if statement

Actually I'm pretty new in

jquery
but I try to found if there is a way to achieve what I am looking for

actually here is my code:

saveData = function(){
$.post('server/admin.php', {
data: 1,
user: userName
}, function(response) {
if(response == 1){
location.reload();
}
else {
return false;
}
});


}

what I try to achieve is to have multiple different data set with the same function example

saveData = function(source){
$.post('server/admin.php', {
if(source == 1){
data: 1,
user: userName
}
if(source == 2){
data: = 2,
date: newDate
}
}, function(response) {
if(response == 1){
location.reload();
}
else {
return false;
}
});


}

as you can see in what I try to do is to send different data via post not always using the same
$_POST
value in
case == 1
I send user in
case == 2
I send date

Is it possible to achieve something like that without having to write a new function in
jquery
for every form I write if they go to the same processing file?

Answer

Try the following

  saveData = function(source){
    var sendData  ={};

    if(source == 1){// do the if outside of the ajax function
            sendData = {  data: 1,
              user: userName };
           }
           if(source == 2){
            sendData = { data: 2,
             date: newDate};
           }

    $.post('server/admin.php', sendData , function(response) {
            if(response == 1){
                location.reload();
            }
            else {
                return false;
            }
    }); 
    }