最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JQuery Ajax post html data to php and get a reply - Stack Overflow

programmeradmin0浏览0评论

I want to post data from a span like the following, but on click nothing happens. i'm posting '4' in the following span. I don't how to post this or the syntax. Span.

<span style="color:#B00" id="PidClick">4</span>

Using this.

$('#PidClick').click(function() {
console.log('PidClick event:')
   $.ajax({
    dataType:'json',
    data: {data:Pid},
    type:"POST",
    url:"test.php"
    }).done(function(reply){
    console.log('reply is' + reply) 
        alert (reply.name)

})
});

and the php being. //// also is my '.$Pid.' variable right? i'm not sure if this is right.

<?php
require_once 'db_conx.php';
if(isset($_POST["Pid"])) {
$id = preg_replace ('#[^0-9 ]#i', '', $_POST['Pid']);
$Result = mysql_query("SELECT * FROM profiles WHERE Pid = '.$Pid.' ") or die (mysql_error());
while($row = mysql_fetch_array($Result)){
$result = array();
$result['pemail'] = $row['pemail'];
$result['name'] = $row['name'];
echo json_encode($result);
}
}
mysql_close($con);
?>

Console Errors:- 
PidClick event: 'Type error: Type error'

I want to post data from a span like the following, but on click nothing happens. i'm posting '4' in the following span. I don't how to post this or the syntax. Span.

<span style="color:#B00" id="PidClick">4</span>

Using this.

$('#PidClick').click(function() {
console.log('PidClick event:')
   $.ajax({
    dataType:'json',
    data: {data:Pid},
    type:"POST",
    url:"test.php"
    }).done(function(reply){
    console.log('reply is' + reply) 
        alert (reply.name)

})
});

and the php being. //// also is my '.$Pid.' variable right? i'm not sure if this is right.

<?php
require_once 'db_conx.php';
if(isset($_POST["Pid"])) {
$id = preg_replace ('#[^0-9 ]#i', '', $_POST['Pid']);
$Result = mysql_query("SELECT * FROM profiles WHERE Pid = '.$Pid.' ") or die (mysql_error());
while($row = mysql_fetch_array($Result)){
$result = array();
$result['pemail'] = $row['pemail'];
$result['name'] = $row['name'];
echo json_encode($result);
}
}
mysql_close($con);
?>

Console Errors:- 
PidClick event: 'Type error: Type error'
Share Improve this question edited Nov 4, 2013 at 6:42 Relm asked Nov 4, 2013 at 6:11 RelmRelm 8,28520 gold badges69 silver badges114 bronze badges 1
  • firstly you have to take the inner text of the span. – Jenz Commented Nov 4, 2013 at 6:15
Add a ment  | 

5 Answers 5

Reset to default 1

First you'll need to assign Pid a value like the others are saying, once we have a value assigned to Pid. Since in the PHP file you're trying to grab a variable named Pid, we'll want to pass it as such.

Here's the updated JQuery:

jQuery(document).ready(function($) {
    $('#PidClick').click(function() {
        var Pid = $(this).text();
        $.ajax({
            type: 'POST',
            url: 'test.php',
            dataType: 'json',
            data: {
                Pid: Pid
            },
            success : function(data){
                console.log('reply is' + data.reply);
                alert(data.reply);
            },
            error : function(XMLHttpRequest, textStatus, errorThrown) {
                alert('There was an error.');
            }
        });
    });
});

Secondly, I wrote a little test case PHP file. Just to make sure everything works. Once again you'll want to make sure to keep your variables the same when passing them back and forth; in the jquery example above you'll notice that I used "data.reply" retrieve the information, in the PHP file below I assigned the data to a variable also named "reply". I also included some safeguard to make sure that the file is only accessible through an ajax request.

<?php

// only work if requested with ajax
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
        strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {

    if(isset($_POST['Pid'])) {
        $return['reply'] = 'The input was '.$_POST['Pid'];
    }
    else {
        $return['reply'] = 'No input detected';
    }

    echo json_encode($return);

} else {
    die('direct access is forbidden');
}
?>

Here's the html file that I used:

<!DOCTYPE html>
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title>pid example</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width">

        <script src="jquery.js"></script>
        <script src="ajax.js"></script>
    </head>
    <body>
        <span style="color:#B00" id="PidClick">4</span>
    </body>
</html>

Also, make sure all your file permissions and paths are correct when trying to execute this example. In this case all files should be located within the same directory.

Use $('#PidClick').text() or $('#PidClick').html() for getting the inner text of the span.

$('#PidClick').click(function() {
  var Pid = $('#PidClick').html();
  ..............
});

Can you assign the Pid value,

var Pid = $(this).html();

User .html() to get the inner html

So add $('#PidClick').html();

$('#PidClick').click(function() {
  var Pid = $('#PidClick').html();
  Pid = parseInt(Pid);
   $.ajax({
data: 'Pid='+Pid,
type:"POST",
url:"test.php"
}).done(function(reply){
console.log('reply is' + reply) 
    alert (reply.name)

})
});
$('#PidClick').click(function() {
   var Pid = $('#PidClick').text();
    $.ajax({
       dataType:'json',
       data: 'Pid='+Pid,
       type:"POST",
       url:"test.php"
  }).done(function(reply){
    console.log('reply is' + reply) 
    alert (reply.name)
  })
});

js fiddler example

发布评论

评论列表(0)

  1. 暂无评论