nothing is being sent with $.post
function clicked()
{
var $contact_title=$("#contact_title");
var $contact_summary=$("#bbcode");
alert($contact_title.val());// How do I get the contents of the title
alert($contact_summary.val());// How do I get the contents of the textarea
$.post('jquery_send_admin.php',{ title:$contact_title, content:$contact_summary }, function(data){ alert("Message was sent") }, 'html');
}
I get exceptions in my console error..like the following:
UPDATE:
no data is inserted on the next page..why?!?
if( isset($_POST["title"]) && isset($_POST["content"]) )
{
$title=mysql_escape_string($_POST["title"]);
$content=mysql_escape_string($_POST["content"]);
$result=mysql_query("INSERT INTO users (query_title,query_message) VALUES(''$title', '$content')") or die(mysql_error());
}
The following error happens:
Error: uncaught exception: [Exception... "Could not convert JavaScript argument" nsresult: "0x80570009 (NS_ERROR_XPC_BAD_CONVERT_JS)" location: "JS frame :: http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js :: <TOP_LEVEL> :: line 16" data: no]
UPDATE:
Thats what I request from the page, which is triggered by jquery:
<?php
echo 'outside';
if( isset($_POST["title"]) && isset($_POST["content"]) )
{
echo 'inside';
$title=mysql_escape_string($_POST["title"]);
$content=mysql_escape_string($_POST["content"]);
$result=mysql_query("INSERT INTO users (query_title,query_message) VALUES(''$title', '$content')") or die(mysql_error());
}
?>
You need to extract the values using the .val() method:
var $contact_title = $('#contact_title').val();
var $contact_summary = $('#bbcode').val();
var dataToPost = { title: $contact_title, content: $contact_summary };
$.post('jquery_send_admin.php', dataToPost, function(data) {
alert('Message was sent');
}, 'html');
var $contact_title=$("#contact_title").text();
var $contact_summary=$("#bbcode").text();
try to get the value/text instead of just the control.
var $contact_title=$("#contact_title").text();
or
var $contact_title=$("#contact_title").val();
Edit:
Not sure how it works in PHP but I use it with vb.net and there I need to give my controller name(aka file) and function so it becomes
$.post('myFile/myJSONFunction', {all-your-parameters});
So maybe thats why it wont post your data.
Something else you might want to look at is that your php might return different data than you are actually expecting him to return.
function clicked() {
var $contact_title = $("#contact_title");
var $contact_summary = $("#bbcode");
alert($contact_title.val()); // with the val
alert($contact_summary.val()); // with the val
$.post('jquery_send_admin.php', { title: $contact_title.val(), content: $contact_summary.val() }, function (data) { alert("Message was sent") }, 'html');
}
Instead of this posted by #Darin
$.post('jquery_send_admin.php', dataToPost, function(data) {
alert('Message was sent');
}, 'html');
use this
$.post('jquery_send_admin.php', dataToPost, function(data) {
alert(data);
});
That will show the result of the echo statements in the alert box which could possibly help you debug the issue.
Oh my. jQuery bugs, PHP debugging bugs. I'll probably get down-rates for this answer... but sometimes, it helps to simply read the manuals if you're that lost that people have to help you cross the street: http://api.jquery.com/ & http://php.net/manual/
Related
For some reason Im getting a <br/> tag from nowhere in my response from the PHP function...
Here is the ajax:
var paid_value = 'Paid';
$.ajax({
url: 'http://localhost/myshop/owe_money/add_paid.php',
type: 'post',
data: { paid_value:paid_value } ,
beforeSend: function() {
$("#ajax-result").html('Before');
},
success: function(data) {
$("#ajax-result").html(data);
$('input[name="mark_as_paid"]').val(data);
},
error: function(xhr, ajaxOptions, thrownError) {
$("#ajax-result").html('Error');
}
});
And the PHP:
function add_paid() {
include('../db_connect.php');
$paid_value = $_POST['paid_value'];
if (is_numeric($paid_value)) {
$sql = "UPDATE paid SET first_item = $paid_value";
} else {
$sql = "UPDATE paid SET first_item = '".$paid_value."'";
}
if (mysqli_query($connect, $sql)) {
echo $paid_value;
} else {
echo "Unsuccesful".mysqli_error($connect);
}
die;
}
add_paid();
My response should simply be saying "Paid", but instead is saying "<br /> Paid".
on the face of it, it looks sound. You'll probably find that the br is going in somewhere else. Maybe it's even already in the file?
If it is finding it's way into the $_POST variable, you could temporarily hack the issue to use
$paid_value = strip_tags($_POST['paid_value]);
This answer comes with no warranty whatsoever!
In your jQuery code, change the success block to:
success: function(data) {
$("#ajax-result").html(data);
$('input[name="mark_as_paid"]').val(data);
console.log(data)
},
Open your debugger in the browser and view the console. This will write the value of data as sent from your PHP script, and may or may not have the line break in it. I suspect that the line break may be coming from the fist page but this will allow you to see this.
I cannot see any problem with the code so I think it has to do with the form/input where you are displaying the result - you have not included this.
you can use replace tag in success ajax
data.replace("but the br tag","");
but it will still exist in the database
i cannot seem to get a callback to work from this but it gets a response its a simple test. anyone know why it dosnt do as i want
<script type="text/javascript">
$(document).ready(function(e) {
$("button").click(function() {
var msg = $("#txt").val();
$.post(
"http://localhost/bot.php",
{msg: msg},
function(data,status) {
$("p").text(data);
}
);
});
});
</script>
The PHP, and could anyone suggest a good JavaScript tool to help me find errors?
<?php
class ai
{
private $msg;
public function __construct($msg)
{
$this->msg = $msg;
}
public function respond()
{
switch($this->msg)
{
case "hi":
echo "Hello Mr Brown How are You";
break;
case "fine":
echo "Good to hear Did you know Zanda hard Coded me?";
break;
case "im fine":
echo "Good to hear Did you know Zanda hard Coded me?";
break;
default:
echo "??????????????????????????????" .
"That means i was extra rush prototype.......i cant answer that";
}
}
}
$talk = new ai($_POST['msg']);
$talk->respond();
?>
<div class="box">
<p>text</p>
<textarea id="txt"></textarea>
<button>click</button>
</div>
there is the html made it as short as can be
Something to try here too is to change your $.post for $.ajax so you can specify an error callback. $.get, $.post etc are just shorthands for $.ajax anyhow. Try something like this:
("button").click(function() {
var msg = $("#txt").val();
$.ajax(
url: "http://localhost/bot.php",
data: {msg: msg},
dataType: 'jsonp',
success: function(data,status) {
console.log(data, "returned with status:", status);
},
error: function(obj, status, error){
console.log("Error!", obj, status, error);
}
);
});
Just because you're getting a 200 response doesn't mean everything's working correctly. All that's saying is that the POST was successful. You need to check the response text to see if any errors are being returned.
EDIT: added in dataType: 'jsonp' to request.
It seems like it is due to the Same Origin Policy and from the MDN documentation
The port number is kept separately by the browser. Any call to the setter, including document.domain = document.domain causes the port number to be overwritten with null. Therefore one can not make company.com:8080 talk to company.com by only setting document.domain = "company.com" in the first. It has to be set in both so that port numbers are both null.
So that is the reason you are getting null as you said in your responses
Try adding datatype:"jsonp". It shoudl work like this.
$(document).ready(function(e) {
$("button").click(function() {
var msg = $("#txt").val();
$.post(
"http://localhost/bot.php",
{msg: msg},
function(data,status) {
$("p").text(data);
},
dataType:"jsonp"
);
});
});
Further reading here.
Hope that helps.
In my footer.php I have this code which i needed for my api references
<script type="text/javascript">
/** Override ajaxSend so we can add the api key for every call **/
$(document).ajaxSend(function(e, xhr, options)
{
xhr.setRequestHeader("<?php echo $this->config->item('rest_key_name');?>", "<?php echo $this->session->userdata('api_key')?>");
});
</script>
It works fine in my project without any error but when I started working on file upload and I'm using ajaxfileupload to upload file, I got this error whenever i upload the file.
TypeError: xhr.setRequestHeader is not a function
xhr.setRequestHeader("KEY", "123456POIUMSSD");
Here is my ajaxfileuplod program code:
<script type="text/javascript">
$(document).ready(function() {
var DocsMasterView = Backbone.View.extend({
el: $("#documents-info"),
initialize: function () {
},
events: {
'submit' : 'test'
},
test: function (e) {
e.preventDefault();
var request = $.ajaxFileUpload({
url :'./crew-upload-file',
secureuri :false,
fileElementId :'userfile',
dataType : 'json',
data : {
'title' : $('#title').val()
},
success : function (data, status)
{
if(data.status != 'error')
{
$('#files').html('<p>Reloading files...</p>');
refresh_files();
$('#title').val('');
}
alert(data.msg);
}
});
request.abort();
return false;
}
});
var x = new DocsMasterView();
});
</script>
Can anyone here fix my problem. Any suggestion/advice in order to solve my problem.
As I understand from your comments, setRequestHeaders works fine with regular ajax calls. At the same time it is not available when ajaxFileUpload is used. Most likely that is because transport method does not allow to set headers (for instance, in case when iframe is used to emulate upload of files in ajax style) . So, possible solution is to place a key into your form data:
$(document).ajaxSend(function(e, xhr, options)
{
if(xhr.setRequestHeader) {
xhr.setRequestHeader("<?php echo $this->config->item('rest_key_name');?>", "<?php echo $this->session->userdata('api_key')?>");
else
options.data["<?php echo $this->config->item('rest_key_name');?>"] = "<?php echo $this->session->userdata('api_key')?>";
});
Note: I'm not sure if options.data is a correct statement, just do not remember structure of options object. If proposed code does not work - try to do console.log(options) and how
to get an object with data that should be posted (it might be something like options.formData, I just do not remember exactly)
And on server side you will just need to check for key in headers or form data.
I'm using $.post to deliver data to my main page from droppable elements. Yet when I echo out the the data I'm getting my toolbar echoed out to me as well as the data I fetched.
if (isset($_POST['data'])){
$data = $_POST['data'];
echo $data;
The javascript containing the $.post is below
if(dropbox && dropbox1 !== ''){
$.post("account_main.php",
{data: $(this).text()},
function(data) {
$('#demo').html(data);
});
}
And a visual for the script using the droppable elements is HERE, but the problem is not shown here, can't duplicate it. I am open to any suggestions.
if (isset($_POST['data'])) {
echo $_POST['data'];
# Other stuff
exit; # Kill the script
}
If I understand your problem correctly, that should sort it :)
Just try :
if (dropbox && dropbox1 !== "") {
var url, params, callback;
url = "account_main.php";
params = {
"data": $(this).text()
};
callback = function(data) {
$("#demo").html(data);
}
$.post(url, params, callback, "html");
}
Please note that I would strongly advise you to use JSON for your response instead of HTML.
header("Content-type: application/json");
echo json_encode($my_result);
data: $(this).text()
$(this) refers to the $.post, I think that's not the data you want.
I submit a form using jQuery to a php file on my server.
Everything works... (the php file gets the right post variables, makes a database entry etc.)
But on the response, sometimes 'data' goes wacky.
$('#form_submit').click( function() {
$.post("path/to/script.php", $('#form').serialize(), function(data) {
if ( data.status == 1 ) {
alert('awesome sauce');
} else {
alert('crap');
}
}, "json");
});
php script returns (on success)
$response['status'] = 1;
$response['message'] = 'worked';
echo json_encode($response);
exit();
I'm getting a whole lot of crap, and not enough awesome sauce.
Does anyone have an idea why sometimes 'data.status' is undefined, and sometimes it isn't?
Try it like this>
$('#form_submit').click( function() {
$.post("path/to/script.php", $('#form').serialize(), function(data) {
var obj = jQuery.parseJSON(data);
if ( obj.status == 1 ) {
alert('awesome sauce');
} else {
alert('crap');
}
});
});
How does exit() behave with regards to output buffering? Does it flush the output buffer?
try this one:
$('#form_submit').click( function() {
$.post("path/to/script.php", $('#form').serialize())
.success(function(){
alert('awesome sauce');
}).error(function(){
alert('crap');
});
});