Benjamin G
Benjamin G

Reputation: 115

Call file using AJAX from a file called from JQuery

I am trying to call the server side from a file called trough JQuery. This is so hard to explain but what I am really doing is, I call a file that will pop up like a window using JQuery. Then in that pop up window I am going to call the server side file using an AJAX.

This is how I called the first file:

JQUERY

function AddBill(id) {
    $("#displayDIV").show();
    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("displayDIV").innerHTML = this.responseText;
        }
    };
    xmlhttp.open("GET","file1.php?",true);
    xmlhttp.send();
}

Now I want to call another file inside the file1.php

AJAX

$(function() { 
    $("#formAdd").submit(function(e) {
        e.preventDefault();
        alert();
        $.ajax({  
            url: $(this).attr('action'),
            type: "post",  
            data: $(this).serialize(),
            error:function(){
                alert("ERROR : CANNOT CONNECT TO SERVER");
            },
            success: function(data) {
                alert(data);
            }
        });
        return false; 
    });
});

By the way. This is where I call the AddBill()

<input type="button" class="updateButton" value="ADD BILLED TO" onclick="AddBill()"/>

And this is the content of my file1.php

<form id="formAdd" action="server.php" method="POST">
    <input type="text" name="text1">
    <input type="submit" value="ADD">
</form>

The AJAX is not being read by the program. Where did I go wrong or what is the better way to do this?

THANKS

Upvotes: 2

Views: 70

Answers (2)

filype
filype

Reputation: 8380

Looking at the updated question, perhaps your ajax code is running before the contents are added on the page:

Try this in your ajax:

$(document).on('submit', "#formAdd", function(e) {

instead of

$("#formAdd").submit(function(e) {

Upvotes: 1

filype
filype

Reputation: 8380

The browser will not execute scripts that are inserted in the DOM. You should consider other ways of achieving this.

You can include a script, adn then inject the contents of file1.php as an exmaple:

if (this.readyState == 4 && this.status == 200) {
    var g = document.createElement('script');
    var s = document.getElementsByTagName('script')[0];
    g.text = this.responseText;
    s.parentNode.insertBefore(g, s);
}

There are some other useful solutions on this question: Can scripts be inserted with innerHTML?

Upvotes: 0

Related Questions