简体   繁体   中英

Trying to pass values from jquery to php file using XMLHttpRequest()

I am trying to pass values in an HTML textarea to a PHP file using jQuery. This is what I have so far:

JQuery

var jq = $.noConflict();
jq("#addUsers").click(function () {
    jq("#addModal").modal("show");
});

jq("#addUser").click(function () {
    var text = jq("textarea#emails").val();
    if (text.length == 0)
    {
        alert("Please enter new user e-mails line by line.");
    }
    else
    {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200)
            {
                jq("textarea#emails").innerHTML = xmlhttp.responseText;
            }
        };
        xmlhttp.open("GET", "add_users.php?emails=" + text + "&list=1", true);
        xmlhttp.send(null);
    }
});

add_users.php

<?php
//error_reporting(E_ALL);
ini_set('display_errors', '1');

$list = $_REQUEST["list"];
$emails = trim($_REQUEST["emails"]);

// This is where I will parse out the text line-by-line
// .....
?>

So, this is all activated by the click function on line 6. When I do this however, nothing happens . I tried putting an echo statement pretty much everywhere inside the function and it echoes out fine. Additionally:

  • The php file is in the same directory as the file I'm working with.
  • I've tried echoing out in the php file; the php file is never accessed.
  • I've tried echoing out the response text using alert(); nothing happens.

Not sure what I'm doing wrong. Help please!!

For one, jq("textarea#emails").innerHTML is not going to work because you're dealing with a jQuery wrapped element now, and not a raw HTML element. If you use jQuery you want to set the contents with val() or html() (depending on the element).

So it's possible you are calling your script successfully, and just not outputting the results on your page.

You can simplify your ajax tremendously by using jQuery. I'd use load() specifically, since your intent is to stick the results into an element.

I would start with this:

jq("#addUser").click(function () {
    var text = jq("textarea#emails").val();
    if (text.length == 0)
    {
        alert("Please enter new user e-mails line by line.");
    }
    else
    {
        jq("textarea#emails").load("add_users.php?emails=" + text + "&list=1");
    }
});

Reference: http://api.jquery.com/load/

Once you have your ajax query working successfully, check your Dev Tools Network tab (assuming Chrome here) to watch the ajax call and see how your server is responding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM