user2753924
user2753924

Reputation: 465

Toggle between ajax data objects

I'd like to toggle between 2 ajax data objects on click of a link. Its not possible to do this with the method below, can anyone suggest a way I can do this? Thanks!

jQuery.ajax({
  url: "/somefile.php",
  dataType: 'JSON',
  type: 'POST',
  jQuery(".togglesearch").toggle(
    function () {
      data: JSON.stringify({
        "Name": jQuery("#searchfield").val(),
        "Number": ""
      }),
    },
    function () {
      data: JSON.stringify({
        "Name": "",
        "Number": jQuery("#searchfield").val()
      }),
    } 
  );

Upvotes: 1

Views: 396

Answers (3)

guest271314
guest271314

Reputation: 1

var data = ["Name", "Number"];

var obj = {"Name":"", "Number":""};

var val = jQuery("#searchfield").val();

var n = 0;

var res;

$("button").click(function() {
  obj[data[n]] = val;
  obj[data[n === 0 ? n + 1 : n- 1]] = "";
  res = JSON.stringify(obj);
  $("label").text(JSON.stringify(res));
  // do ajax stuff
  /*
  jQuery.ajax({
     url: "/somefile.php",
     dataType: "JSON",
     type: "POST",
     data: res
  })
  */
  n = n === 0 ? 1 : 0
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<button>click</button>
<input type="text" id="searchfield" value="123" /><label></label>

Upvotes: 1

erikscandola
erikscandola

Reputation: 2936

Try this:

jQuery(".togglesearch").toggle(function() {
    var data = { "Name": "", "Number": jQuery("#searchfield").val() };
    callAjax(data);
}, function(){
    var data = { "Name": jQuery("#searchfield").val(), "Number": "" };
    callAjax(data);
});

function callAjax(data) {
    jQuery.ajax({
        url: "/somefile.php",
        dataType: 'JSON',
        type: 'POST',
        data: JSON.stringify(data),
        success: function(response) { }
    )};
}

In toggle finally call a function with ajax call. Let me know if it works for you.

Upvotes: 0

David Johnson
David Johnson

Reputation: 58

I think you'll have to put each different ajax call inside the toggles:

 jQuery(".togglesearch").toggle(
    function () {
       jQuery.ajax({
           url: "/somefile.php",
           dataType: 'JSON',
           type: 'POST',
           data: JSON.stringify({
               "Name": jQuery("#searchfield").val(),
               "Number": ""
           })
       });
     },
    function () {
        jQuery.ajax({
           url: "/somefile.php",
           dataType: 'JSON',
           type: 'POST',
           data: JSON.stringify({
               "Name": "",
               "Number": jQuery("#searchfield").val()
           })
        });
     }
  });

Upvotes: 0

Related Questions