如何使用jquery.post发送文本字段,php + mysql没有表单?
问题描述:
How to send textfield with jquery.post
(ajax) from php without form?
I need send text field using jquery.post
. I have this code:
HTML:
<div id="form1" class="enviar"> <p>
URL:
<input type="text" name="url" id="url" />
<p> JSON:
<textarea name="json" id="json" cols="45" rows="5"></textarea>
</p>
<p>
<input type="submit" name="send" value="send" />
</p>
</div>
JQUERY:
$(function(){
$("#send") .submit(function(){
var json = $("#json") .val();
var url = $("#url") .val();
var s = {
"json":json
}
var u = {
"url":url
}
$.ajax({
url:u,
type:'post',
data:s,
beforeSend: function (){
$(".status") .html(" alt=\"Loading ....\" />");
},
success:function(data){
$(".status").html(data);
}
});
});
})
PHP:
include ('conection.php');
$arr = json_decode($_POST['json'],true);
if ($_POST['json']>NULL){
mysql_query("INSERT INTO liciteiro.clientes(client_id,client_descricao,client_razaosocial,client_endereco,client_cidade,client_estado,client_telefone) VALUES ('".$arr[0]['client_id']."','".$arr[0]['client_descricao']."','".$arr[0]['client_razaosocial']."','".$arr[0]['client_endereco']."','".$arr[0]['client_cidade']."','".$arr[0]['client_estado']."','".$arr[0]['client_telefone']."')")or die(mysql_error());
}
else {
die(mysql_error());
}
But this code doesn't send anything.
答
Try this it will send data after click on send button Html
<div id="form1" class="enviar">
<p>URL:<input type="text" name="url" id="url" /></p>
<p> JSON:<textarea name="json" id="json" cols="45" rows="5"></textarea></p>
<p><input type="submit" name="send" value="send" id="send" /></p>
</div>
Jquery
$(function(){
$("#send").click(function(){
var json = $("#json") .val();
var url = $("#url") .val();
$.ajax({
url:url,
type:'post',
data:{json: json},
beforeSend: function (){
$(".status") .html(" alt=\"Loading ....\" />");
},
success:function(data){
$(".status").html(data);
}
});
});
});
答
You could add id to you button and use
$("#my-button-id").click
Or you can try this
$(function(){
$('#form1 input[type="submit"]').click(function(e){
e.preventDefault();
var json = $("#json") .val();
var url = $("#url") .val();
$.ajax({
url:url,
type:'post',
data:{json: json},
beforeSend: function (){
$(".status") .html(" alt=\"Loading ....\" />");
},
success:function(data){
$(".status").html(data);
}
});
});
});
But you must notice that you can't make ajax queries to other domains, without allow-origin headers.
答
jQuery:
$('#mybutton').on("click",function(){
var url = $('#url').val()
$.post(url,
{text:$('#json').val(), url:url },
function(data){
alert("it works");
})
})
HTML:
<textarea name="json" id="json" cols="45" rows="5"> </textarea>
<input type="button" id="mybutton" />