简体   繁体   中英

$.ajax( type: “POST” POST method to php

I'm trying to use the POST method in jQuery to make a data request. So this is the code in the html page:

<form>
Title : <input type="text" size="40" name="title"/>
<input type="button" onclick="headingSearch(this.form)" value="Submit"/><br /><br />
</form>
<script type="text/javascript">
function headingSearch(f)
{
    var title=f.title.value;
    $.ajax({
      type: "POST",
      url: "edit.php",
      data: {title:title} ,
      success: function(data) {
        $('.center').html(data); 
      }
    });
}
</script>

And this is the php code on the server :

<?php

$title = $_POST['title'];
if($title != "")
{
    echo $title;
}

?>

The POST request is not made at all and I have no idea why. The files are in the same folder in the wamp www folder so at least the url isn't wrong.

You need to use data: {title: title} to POST it correctly.

In the PHP code you need to echo the value instead of return ing it.

Check whether title has any value or not. If not, then retrive the value using Id.

<form>
Title : <input type="text" id="title" size="40" name="title" value = ''/>
<input type="button" onclick="headingSearch(this.form)" value="Submit"/><br /><br />
</form>
<script type="text/javascript">
function headingSearch(f)
{
    var title=jQuery('#title').val();
    $.ajax({
      type: "POST",
      url: "edit.php",
      data: {title:title} ,
      success: function(data) {
    $('.center').html(data); 
}
});
}
</script>

Try this code.

In php code, use echo instead of return . Only then, javascript data will have its value.

try this

$(document).on("submit", "#form-data", function(e){
    e.preventDefault()
    $.ajax({
        url: "edit.php",
        method: "POST",
        data: new FormData(this),
        contentType: false,
        processData: false,
        success: function(data){
            $('.center').html(data); 
        }
    })
})

in the form the button needs to be type="submit"

Id advice you to use a bit simplier method -

$.post('edit.php', {title: $('input[name="title"]').val() }, function(resp){
    alert(resp);
});

try this one, I just feels its syntax is simplier than the $.ajax's one...

function signIn()
{
    var Username = document.getElementById("Username").value;
    var Password = document.getElementById("Password").value;

    $.ajax({
        type: 'POST',
        url: "auth_loginCode.jsp",
        data: {Username: Username, Password: Password},
        success: function (data) {
            alert(data.trim());
            window.location.reload();
        }
    });
}
contentType: 'application/x-www-form-urlencoded'

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