my Ajax post data is not arriving - any clues please.
The data is a serilaized form that "alerts" correctly with all the data using this
$(document).ready(function() {
var serial = $('#frm_basket').serialize();
alert(serial);
$.ajax({
url: "basket-calc.php",
type: "post",
data: serial,
success: function(){
("#basketTotal").load('basket-calc.php');
}
});
});
The alert gives me a string like product=p1&qty=1&product=p2&qty=2
But when I try to php echo out the results on basket-calc.php I get an "empty" array
basket-calc.php:
$test = $_POST;
print_r($test);
You can debug your request with firebug to make sure what is happening.
Also try setting the post type to GET:
type: "GET",
to see if it makes any difference.
try:
$(document).ready(function() {
var serial = $('#frm_basket').serialize();
alert(serial);
$.ajax({
url: "basket-calc.php",
type: "post",
data: serial,
success: function(result){
("#basketTotal").html(result);
}
});
});
Also note following points:
make sure basket-calc.php is not returning 404
try sending blank data and echo your response
once you get sample string from server, just attach the real data
hope this helps
If your htaccess is stripping the .php from the , the POST gets converted to GET. I think.
Try and remove .php from your url.
Related
When I sent the variable data through ajax loading_add.php page an error
is displayed:
Uncaught ReferenceError: profit is not defined.
What I tried so far is attached below.
var profit = (
Number($("#pro_price").val() - retail_price)
);
$.ajax({
type: "POST",
url: '../php/product/loading_add.php',
dataType: 'JSON',
data: {
profit: profit
};
In you php page just define variable as:
#$_POST['profit'];
you will not get undefined error again, hope this trick will help you :)
Your question is not clear.
But I share the valid way to send data via AJAX and retrieve the data in PHP Server Side..
var profit = (
Number($("#pro_price").val() - retail_price)
);
console.log(profit); // see in console log if `profit` is a valid variable or not
$.ajax({
type: "POST",
url: '../php/product/loading_add.php',
dataType: 'JSON',
data: {
profit: profit
}
}).done(function(result){
//do something after done AJAX
});
In server side, you must call variable $_POST['profit'] to retrieve the profit value.
I'm trying to send data via POST to PHP file..
$.get() - works fine, hovewer I couldn't tell the same about $.post() or $.ajax() with method post..
Here my code I wrote:
$('[name="update"]').click(function(){
tr = $(this).parents('tr');
u = [];
u["username"] = tr.find('[name="u[username]"]').val();
u["display_name"] = tr.find('[name="u[display_name]"]').val();
u["type"] = tr.find('[name="u[type]"]').val();
$.ajax({
type: "POST",
url: "../ajax-queries/update-user.php",
data: {update:u},
cache: false,
success: function(data){
alert(data);
}
});
});
And PHP file looks like:
<?php
print_r($_POST);
?>
Response I get:
Array(
)
Using latest jQuery lib... no ideas why not working.. any solutions you can offer?
Is that could be posible because of port:2014?
in case i tried and in :80 (same results)..
Because you aren't setting anything.
Try changing u to {}, like: u = {};
Array with key index is not an array, it's an object, try alert(typeof u).
sending an array with key index will fail in IE8.
This may sound strange but I have a JQ/AJAX/PHP post problem.
My "code" is all there and works in most situations except 1 - when I try to pass a tag through the process.
I grab the html like this
var ed = $('#fraRTE').contents().find('body #editarea').html();
#fraRTE is an iframe width an editable div #editarea hence .contents().find('body #editarea').html()
So if var ed is just "hello world etc...." there is no problem and the data is processed BUT if var ed is something like "hello world etc.... <img src="image.png">" the data is not processed - stangely if var ed is "hello world etc....<img src="image.png">" - no gap between text and the image the data is actually processed.
If I alert(ed) before the post then I see the "correct" string - whatever it's contents, post like this:
var data = 'content='+ed;
$.ajax({
type: 'post',
url: 'script.php',
data: data,
success: function(msg) {
alert(msg);
}
});
I create the data string before "data:data" as there are a few more items in the string.
my alert(msg) is set by echo $_POST['content']; on script.php
the alert(msg) tells me what has (or has not) been posted to the DB. this is where I see the problem mentioned above. i.e. the inclusion (or not) of <img...>
Suggestions please
jQuery is smart enough to handle turning your request data into a query string for you.
$.ajax({
type: 'post',
url: 'script.php',
data: { content: ed },
success: function(msg) {
alert(msg);
}
});
This issue you are having is the data not being properly escaped.
In order to stringify it yourself, you would have to use encodeURIComponent()
"content=" + encodeURIComponent(ed);
But it's far simpler to just let jQuery do it for you.
Don't use string concatenations when constructing request parameters or they won't be properly url encoded and if the parameter contains some special characters it won't be properly received. Here's the correct way:
var data = { content: ed };
$.ajax({
type: 'post',
url: 'script.php',
data: data,
success: function(msg) {
alert(msg);
}
});
I'm trying to take values from a dropdown two boxes and send them to a PHP file which will draw an appropriate field from a mySQL database depending on the combination chosen and display it in a div without refreshing the page using AJAX. I have the second part sorted, but I'm stuck on the first part.
Here is the HTML: http://jsfiddle.net/SYrpC/
Here is my Javascript code in the head of the main document:
var mode = $('#mode');
function get() {$.post ('data.php', {name: form.him.value, the_key: #mode.val()},
function(output) {$('#dare').html(output).show();
});
}
My PHP (for testing purposes) is:
$the_key = $_POST['the_key'];
echo $the_key;
After I have it in PHP as a variable I can manipulate it, but I'm having trouble getting it there. Where am I going wrong? Thanks for your replies!
You need a callback function as well to have the server response to the POST.
$.post('ajax/test.html', function(data) {
$('.result').html(data);
});
This snippet will post to ajax/test.html and the anonymous function will be called upon its reply with the parameter data having the response. It then in this anonymous function sets the class with result to have the value of the server response.
Help ? Let me know and we can work through this if you need more information.
Additionally, $.post in jQuery is a short form of
$.ajax({
type: 'POST',
url: url,
data: data,
success: success
dataType: dataType
});
your jquery selectors are wrong:
html:
<select id="mode">
jquery selector:
$("#mode").val();
html:
<select name="player">
jquery selector:
$("select[name=player]").val();
You want to add a callback to your ajax request, its not too hard to do, here ill even give you an example:
$.ajax({
url: "http://stackoverflow.com/users/flair/353790.json", //Location of file
dataType: "josn",//Type of data file holds, text,html,xml,json,jsonp
success : function(json_data) //What to do when the request is complete
{
//use json_data how you wish to.;
},
error : function(_XMLHttpRequest,textStatus, errorThrown)
{
//You fail
},
beforeSend : function(_XMLHttpRequest)
{
//Real custom options here.
}
});
Most of the above callbacks are optional, and in your case i would do the following:
$.ajax({
url: "data.php",
dataType: "text",
data : {name: ('#myform .myinput').val(),the_key: $('#mode').val()},
success : function(value)
{
alert('data.php sent back: ' + value);
}
});
the ones you should always set are url,success and data if needed, please read The Documentation for more information.
how to sanitize user inputs that you gather by jquery .val() so you can write it in a dataString... in the example you see below when user writes
if some text that contains & the rest
of the comment doesn't seem to work
fine because it counts the rest as an
other variable to POST..
is there a sanitaziation or
serialization code? jQuery's
sanitize() function works on forms but
i want something that i can use
directly use on strings...
var id = $("some_id_value_holder_hidden_field").val();
var comment = $("#sometextarea").val();
var dataString = "id=" + id + "&comment=" + comment;
$.ajax({
type: "POST",
url: "write_comment.php",
data: dataString,
dataType: "json",
success: function(res) {
// Success
},
error: function(xhr, textStatus, errorThrown) {
// Error
}
});
Any suggestion will be much appreciated
Regards
Since you're using jquery, you can use the included Form plugin to serialize the array.
serialize() - Creates a url string from form fields (eg, someEle=someVal&anotherEle=anotherVal)
serializeArray() - Returns a key/value array of all the form elements (useful to know)
$.ajax({
url : 'write_comment.php',
type : 'post',
data : $('#form-element').serialize(),
success : function(data)
{
alert('yay!');
}
});
Edit: Edited to remove incorrect escape() part.
there is a built-in encodeUriComponent that does exactly what you're looking for. Besides that, you can provide an object in "data" field, in which case url encoding will be handled by jquery. In your example:
$.ajax({
type: "POST",
url: "write_comment.php",
data: { id: id, comment: comment},
etc...