-2

I have a function where I submit data to another php page that inputs it into the database.

$(document).on('click', '.addNumber', function() {
    var newNum = $('input#newNumber').val();

        $.ajax({
            type: 'POST',
            url:  '/addNewPhoneNumber.ajax',
            data: {
                'bid' : bid,
                'nbr' : newNum
            },
            dataType : 'json'
        });

});

I need to expand the functionality and add a check on my other php page for submitted number. If it is already in my db I need to return some flag and display a message on the first page. I know how to do that on my second page, but how do I return response back to my initial page?

santa
  • 12,234
  • 49
  • 155
  • 255
  • possible duplicate of [jQuery: Return data after ajax call success](http://stackoverflow.com/questions/5316697/jquery-return-data-after-ajax-call-success) – ElefantPhace Dec 07 '14 at 22:06

2 Answers2

3

Add a success callback like this

$.ajax({
        type: 'POST',
        url:  '/addNewPhoneNumber.ajax',
        data: {
            'bid' : bid,
            'nbr' : newNum
        },
        dataType : 'json',
        success: function (response) {
        if(response.status === "success") {
            // do something with response.message or whatever other data on success
        } else if(response.status === "error") {
            // do something with response.message or whatever other data on error
        }
    }
    });
santa
  • 12,234
  • 49
  • 155
  • 255
JOSEFtw
  • 9,781
  • 9
  • 49
  • 67
  • Whether the number is in my db or not, I will not get an error. Currently it will return success. How to I make it return another response if I find a match? Do I just output echo 'error'? Sorry, a bit confused with the process. – santa Dec 07 '14 at 22:10
  • Just do the check on your php page and return a different message. Success only means that the call was successful. Look in my example, Im checking a status variable... PSUEDO `if(numberIsInDb) echo 'error' else echo 'success'` Then you just need to check the response variable that will be a string, not a object like this in your javascript: `if(response === 'success')`... – JOSEFtw Dec 07 '14 at 22:12
0

You can success and error callback function

$.ajax({
    type: 'POST',
    url:  '/addNewPhoneNumber.ajax',
    data: {
        'bid' : bid,
        'nbr' : newNum
    },
    dataType : 'json',
    success: function(response, status, x) {
        console.log(response) //response is the output of your page.. you can write it somewhere

    },
    error: function(h, s, x) {
        console.log("error: " + h.statusText)
    }
  }
});