skip to Main Content

here ajax call is not happening inside function, outside function it is working,
anyone can help in spotting the error

$('#submit').on("click", function(){

    var B = $('#search').val();
    
    alert (B);
  
    $.ajax({
        url:"hi.php",
        type:"POST",
        data:{A :10},
        success: function(data){
            console.log (data);
        },

    });
})

2

Answers


  1. May be default submit event is firing before this function. You can prevent this by e.preventDefault().

    $('#submit').on("click", function (e) {
    e.preventDefault()
    var B = $('#search').val();
    
    alert(B);
    
    $.ajax({
        url: "hi.php",
        type: "POST",
        data: {A: 10},
        success: function (data) {
            console.log(data);
        },
    
    });
    })
    
    Login or Signup to reply.
  2. If button type is submit it will refresh your page and you will not get a desired behavior. So you need to use either a normal button or event.PreventDefault(); to make sure it will not refresh your page.

    <input type="submit" value="Submit" />
    
    $('#submit').on("click", function(e){
        e.preventDefault();
        var B = $('#search').val();
        
        alert (B);
      
        $.ajax({
            url:"hi.php",
            type:"POST",
            data:{A :10},
            success: function(data){
                console.log (data);
            },
    
        });
    })
    

    for more you can visit here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search