I have a simple script that gets the value of a textarea and posts this via AJAX. If I post "??" I get strange values. If I log out the value it retrieves before posting it all is correct. But the POST data my script receives includes the jQuery version number. My code and results are are below. Should I be escaping this somehow ?
var value = $("#textarea").val();
$.ajax({
url:'index.php',
type:'POST',
data:'text='+value,
dataType:'JSON',
success:function(data){}
});
My post data comes through as "jQuery17106460378167700797_1345234676316" for the value of text.
It's a POST request, not GET, and should be:
var value = $("#textarea").val();
$.ajax({
url:'index.php',
type:'POST',
data: {text : value}, //object
dataType:'JSON',
success:function(data){
}
});
PHP
$value = $_POST['text'];
Also, setting the dataType to JSON evaluates the response as JSON and returns a JavaScript object. The JSON data is parsed in a strict manner, any malformed JSON is rejected and a parse error is thrown. This means any malformed JSON, and your ajax call will fail.
I am not sure when you are executing the script, is it on button press?
If not, you will need to wrap it so that it runs only after DOM had completed loading:
$(document).ready(function()
{
var value = $("#textarea").val();
$.ajax({
url:'index.php',
type:'POST',
data:'text='+value,
dataType:'JSON',
success:function(data){}
});
});
Related
I have searched through the amazing answers offered on similar subjects, but I just can't seem to find one that answers my question.
I am trying to POST data to a separate PHP page via AJAX to send an email without the page reloading. However, I can either get the data to POST and have the page reloaded, or the form POSTs nothing and the page remains exactly as it was. The following example is of the latter scenario.
I'm not sure if this is relevant, but the form is contained within a modal. I can post it if necessary.
jQuery:
$("#submit").click(function(e) {
e.preventDefault();
$.ajax({
method: "POST",
url: "email.php",
data: {
name: $("#name").val(),
email: $("#returnEmail").val(),
subject: $("#subject").val(),
body: $("#body").val(),
},
dataType: "html",
success: function() {
$("#errorSuccess").html('<div class="alert alert-success" role="alert">Email Sent!</div>');
}
});
});
Thanks in advance!
you're appending data in a wrong way.
When you post something in ajax to a php (And then you read it there with $_POST["name"]) PHP recieves it as url encoded data (?name=value&name=value).
So, here are a few solutions:
Identify your form element with some id (id="myform") and then retrieve the values you're needing with serialize() method. Like this:
method: "POST",
url: "email.php",
data: $("#myform").serialize(),
You can append it to a Javascript Array like this:
var form_data = {};
form_data["name"] = $("#name").val();
form_data["email"] = $("#email").val();
And then you can send it as regular data in Ajax parameters,
data:form_data,
Use the FormData object. And append data from your form - FormData is recommended when you're appending data and files in the same form .
var form_data = new FormData();
form_data.append("name", $("#name").val());
form_data.append("email", $("#email").val());
Or even easier, again with an ID in the form:
var form = document.getElementById('myform');
var form_data = new FormData(form);
and for sending, you use this in your ajax parameters:
data: form_data,
processData: false,
contentType: false
*processData and contentType are very important, if they're not present, it will throw an error (Illegal invocation if I remember right)
Add it manually to a string (ugly and not recommended way). But it shows you how does it work (you know, just for curiosity)...
data: '?name='+$("#name").val()+'&email='+$("#email").val()
Success and error in your ajax would be great. Don't forget to set a response in your PHP, seeing that PHP would be great for helping you.
Hope it helps :)
I have a draggable div-container and whenever I drop it, its location is to be send to a local php script.
$(function() {
$( "#fenster" ).draggable({
stack: "#fenster", stop: function(event, ui){
var pos_x = ui.offset.left;
var pos_y = ui.offset.top;
$.ajax({
type: "POST",
contentType: "application/json",
data: {'x': pos_x},
url: "index.php",
}).done(function(msg){
alert("data Saved: " + msg);
});
}
});
});
In the php file (index.php) I check whether $_POST['x'] is set. Unfortunately, no matter what I do, the condition is never met.
if((isset($_POST['x']))){
$_SESSION['xLoc'] = $_POST['x'];
echo "Test";
}
Upon dropping the window, I get a response (alert of the msg shows output) and according to FireBug, the request DOES contain x.
The PHP superglobal $_POST, is only available when you use these content types
application/x-www-form-urlencoded (standard content type for simple form-posts) or
multipart/form-data-encoded (mostly used for file uploads)
You are using application/json which means you need to get the stream with...
$rawData = file_get_contents("php://input");
$d = json_decode($rawData);
if((isset($d['x']))){
$_SESSION['xLoc'] = $d['x'];
echo "Test";
}
Or if you dont actually need to be submitting JSON, just remove the contentType from your jquery, and you should be able to retrieve the $_POST on the php side, using the code you already had.
$.ajax({
type: "POST",
data: {'x': pos_x},
url: "index.php",
}).done(function(msg){
alert("data Saved: " + msg);
});
Or change your php to the code above, to retrieve the raw stream, if you need to be sending json data to the server
I had two redirects that killed the POST request. After making adjustments to the if-conditions, this no longer happens and the data sent by the Ajax request is now also being successfully processed by PHP.
Thank you all that took the time to help me, it's greatly appreciated.
i am sending data through ajax call to the php code my ajax code is this
var values = JSON.stringify({ dstring: dataString, ukey:ukey });
var page_path = server_url+"save_data.php";
$.ajax({
type: "POST",
url: page_path,
cache: false,
data: values,
dataType: "json",
success: function(msg){
},
error:function(xhr, status, error) {
}
});
and in the ajax it send data like this
{"dstring":{"q2":"11","q3":"22","q4":"33","q5":"44","q6":"55"},"ukey":"1"}
and in the php when i try to get it through REQUEST it dont show me data , i am bit confuse on how to handle this data in php
Don't stringify data on your ajax call. You should then be able to $_POST['dstring']on the PHP script. Also, you should add in some debug code at least into that error handler to know what's up. Last but not least, inspect the network calls.
You have to get file_get_contents("php://input") and run that through json_decode.
I'm trying to update a div with id=OCRID, which is a div on my page that contains some data. I used the code at the following URL first, however we switched to a jQuery approach. <-Ugly ajax->. Switched to this. Using alert, I saw that the message being returned on success was the correct message, but the document.getElementById(OCRID).innerHTML=msg doesn't change the value. I have some other javascript that does some similar things but not with data from the server. Please help?
$.ajax({
type: "GET",
url: url,
data: "q="+OCRID+"&newstatus="+document.getElementById(OCRID).value,
success: function(msg, OCRID){
document.getElementById(OCRID).innerHTML=msg;
}
});
First of all you mentioned OCRID is an id of div and you've used
document.getElementById(OCRID).value // a div doesn't have a value attribute
which returns value of an HTML element but a div doesn't contain any value attribute and in the success callback you have used
success: function(msg, OCRID){
document.getElementById(OCRID).innerHTML=msg; // innerHTML is right for a div
}
From the jQuery Documentation:
success(data, textStatus, jqXHR)
A function to be called if the
request succeeds. The function gets passed three arguments: The data
returned from the server, formatted according to the dataType
parameter; a string describing the status; and the jqXHR (in jQuery
1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the success setting can accept an array of functions. Each function will be called in
turn. This is an Ajax Event.
in this case you shouldn't use OCRID as the second parameter because jQuery uses 3 parameters in the success callback and these are basically data, textStatus, jqXHR and in this case data is your msg, OCRID in this case become textStatus and it is the response's status message and the third parameter is the xhr object. So it should be
$.ajax({
type: "GET",
url: url,
data: "q="+OCRID+"&newstatus="+$('#'+OCRID).html(), // or text()
success: function(msg){
$('#'+OCRID).html(msg); // or text()
}
});
Also remember that you OCRID looks like a variable and this should be available in the scope of your ajax call and if this is not a variable then it should be $('#OCRID') in both places as given below
$('#OCRID').html();
and in the success callback
$('#OCRID').html(msg);
Replace this line:
document.getElementById(OCRID).innerHTML=msg;
With:
document.getElementById("OCRID").innerHTML=msg; // notice the quotes
If your success callback has OCRID as a parameter(which is incorrect) it will be used instead of the one you used in your data parameter, so remove it.
$.ajax({
type: "GET",
url: url,
data: "q="+OCRID+"&newstatus="+document.getElementById(OCRID).innerHTML,
success: function(msg){
document.getElementById(OCRID).innerHTML=msg;
}
});
Why not use the jQuery version for the interface to the element? To me it looks like OCRID is a variable, right?
$.ajax({
type: "GET",
url: url,
data: "q="+OCRID+"&newstatus=" + $('#' + OCRID).text(),
success: function(msg, OCRID){
$('#' + OCRID).html(msg);
}
});
I'm going crazy over this script, i'm trying to het this working by when some one click on a button then with ajax fetch data from another URL then fill form inputs with the fetched data can any one help please
my code look like this:
$(document).ready(function()
{
$("#getmetaData").click(function(){
var element = $(this);
var url = $("#url").val();
var dataString = 'url='+ url ;
//alert(dataString);
if(url=='http://')
{
alert("Please Enter URL to fetch Meta Data");
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="images/loader.gif" >');
$.ajax({
type: "POST",
url: "fetch-metadata.php",
data: dataString,
cache: false,
success: function(data){
$("#title").val(data);
$("#description").val(data);
$("#keywords").val(data);
$("#flash").hide();
}
});
}
return false;});});
If you see no error, which I am guessing is the case, it means your request is failing. Since you have no error function, when your request fails, your jQuery code will do nothing.
Add something like this to your $.ajax object argument:
error: function(jqXHR, textStatus, errorThrown) {
// now you can set a breakpoint or log textstatus/errorThrown
},
As per HackedByChinese's answer I would add an error callback function.
Also, in your success callback function you are simply using the 'data' variable without doing anything with it. Depending on the format of the response from 'fetch-metadata.php' I think you'll need to do something first. It's either XML in which case you'll need to parse it. If its json you can use object dot notation to reference it's properties.
Lastly, I'd use something like Firebug to look at the request and response for this Ajax request to make sure it's being processed and not returning a 404 or 500. Assuming its returning a valid response, using Firebug you can look at the response to see the raw data that is being returned to your js.
Hope this helps