I seem to be struggling with sending POST data to my PHP script.
My AJAX sends data (an ID of a blog post) to my PHP script, which then finds the row that contains a matching ID from a database.
The script then sends back the title of the blog post and the content of the post in an array, which AJAX picks up and inserts into a form in the DOM.
I can successfully:
insert sample data (for example, if I simply store strings into the array I'm passing back to AJAX, it will successfully insert those strings into the form); and
insert the correct data from the database when a static ID is specified (for example, if I switch out $_POST['editpostid'] and specify the integer 5 instead, the query successfully finds the row with ID = 5 and AJAX inserts this data into the form).
Therefore, from my point of view, the problem is that the ID is never reaching the PHP script, or my script cannot see the ID inside the JSON object.
Please take a look at my code and let me know what you think. I'm new to all this, so I'd appreciate your feedback - if it fixes the problem or not.
Javascript/jQuery:
// When edit button is clicked
$('li.edit').click(function() {
// Get class (postid inserted with PHP) of edit button, excluding edit class
var oldpostid = $(this).attr('class').split(' ')[1];
alert(oldpostid); // Returns the correct postid, for example 5
var jsonObj = { 'postid': oldpostid };
alert(jsonObj); // Returns 'object Object'
// Send postid to PHP script
$.ajax({
type: 'POST',
url: '../scripts/fetchpost.php',
dataType: 'json',
data: { 'editpostid': jsonObj },
success: function() {
// Fetch post data back from script
$.getJSON('../scripts/fetchpost.php', function(data) {
alert(data.title); // Returns null
alert(data.content); // Returns null
// All of the below code works if the PHP script returns sample text,
// or if an ID is specified in the PHP script itself
var title = data.title;
var content = data.content;
// Insert data into editor
$('#titlehead').text(title);
$('#edittitle').val(title);
var editor = 'editpost-content';
tinymce.get(editor).setContent(content);
});
},
error: function( e ) {
console.log(e.message);
}
});
});
PHP:
<?php
// Specifies connection details
include('../scripts/config.php');
// Fetch data from AJAX
$postid = $_POST['editpostid']; // Where I think the problem lies. Returns null.
// Again, this works if I switch out $_POST with an integer, such as 5
// Find rows in database that match postid
$postedit_qry = mysqli_query( $dbconnect, "SELECT * FROM posts WHERE postid='$postid'" );
// Store results in an associative array
$row = mysqli_fetch_assoc( $postedit_qry );
// Split array into variables
$title = $row['title'];
$content = $row['content'];
// Organise data into an array for json
$postedit = array(
'title' => $title,
'content' => $content
);
// Return array as json object for ajax to pick up
echo json_encode( $postedit );
// Close connection
mysqli_close( $dbconnect );
?>
Update - Solution:
Fixed jQuery/Javascript:
// Snip
// Get class (postid inserted with PHP) of edit button, excluding edit class
var oldpostid = $(this).attr('class').split(' ')[1];
// Send postid to PHP script
$.ajax({
type: 'POST',
url: '../scripts/fetchpost.php',
dataType: 'json',
contentType: 'application/x-www-form-urlencoded',
data: { "editpostid": oldpostid },
success: function(data) {
var title = data.title;
var content = data.content;
// Snip
The PHP script remains the same.
Many thanks for your help!
MrPupper
I think you missed the index 'postid' and need to replace this
$postid = $_POST['editpostid'];
with this line :
$postid = $_POST['editpostid']['postid'];
Or instead of sending
data: { 'editpostid': jsonObj },
send this
data: { 'editpostid': oldpostid },
Looking over your code, it seems like you are getting null because you are requesting the fetchpost.php script twice. Once when you contact the script via $.ajax(...); and once more when you call $.getJSON(...);. When you contact via $.getJSON(...);, though, you are not POSTing data and it seems like your script does not have a properly defined way to handle GET requests, so the script doesn't know how to react and it returns null information.
I would change the JavaScript/jQuery to the following:
// When edit button is clicked
$('li.edit').click(function() {
// Get class (postid inserted with PHP) of edit button, excluding edit class
var oldpostid = $(this).attr('class').split(' ')[1];
alert(oldpostid); // Returns the correct postid, for example 5
var jsonObj = { 'postid': oldpostid };
alert(jsonObj); // Returns 'object Object'
// Send postid to PHP script
$.ajax({
type: 'POST',
url: '../scripts/fetchpost.php',
dataType: 'json',
data: {'editpostid': jsonObj },
success: function(sData) {
var data = JSON.parse(sData);
alert(data.title); // Returns null
alert(data.content); // Returns null
// All of the below code works if the PHP script returns sample text,
// or if an ID is specified in the PHP script itself
var title = data.title;
var content = data.content;
// Insert data into editor
$('#titlehead').text(title);
$('#edittitle').val(title);
var editor = 'editpost-content';
tinymce.get(editor).setContent(content);
},
error: function( e ) {
console.log(e.message);
}
});
});
Additionally, PHP is going to be expecting an application/x-www-form-urlencoded value to be able to interact with $_POST[...]. As such, if you want to feed it JSON, then in your PHP, you will need to implement a solution such as: $postedData = json_decode(file_get_contents('php://input')); (See more about that in this answer; for more about json_decode, see the official PHP documentation for json_decode.)
Note: While outside of the scope of your question, and you may know this already, I find it important to point out that your MySQL is insecure and vulnerable to SQL injection due to just blindly trusting that the postId has not been tampered with. You need to sanitize it by saying $postid = $dbconnect->real_escape_string($postid); after you initialize $dbconnect and connect to the database, but before you put the $postid into your SQL query string.
Related
I was wondering if you could help. I am attempting to pass a variable to a PHP file, then run a SQL query, using that variable, then pass back the result as a variable to the javascript. Currently, I have successfully received the PHP back to the javascript using Ajax, but not able to sending the ServiceName to the PHP File. It is essential that the files stay separate. Also just to clarify I have replaced certain sections for privacy, however, they are correct and working in the code. I have also used a $_GET method already, however, I could only get the javascript to access a new window and not return the PHP variable.
My current code is as follows:
// If the user changes the ServiceID field.
if (sender.getFieldName() == 'ServiceID')
// Declare the value of the new Service name and save it in the variable A.
a = sender.getValue();
{
// if it equals a new variable.
if (sender.getValue() == a) {
// Place it within the URL, in order for it to be processed in the php code.
window.location.href = "http://IP/development/Query01.php?service=" + a;
// Attempted code
// echo jason_encode(a);
// $.ajax({var service = a;
// $.post('http://IP/development/Query01.php', {variable: service});
// }
//use AJAX to retrieve the results, this does work if the service name is hard coded into the PHP.
$.ajax({
url: "http://IP/development/Query01.php",
dataType: "json", //the return type data is jsonn
success: function(data) { // <--- (data) is in json format
editors['Contact2'].setValue(data);
//alert(data);
//parse the json data
}
});
}
}
}
<?php
$serverName = "SeverIP"; //serverName\instanceName, portNumber (default is 1433)
$connectionInfo = array( "Database"=>"DatabaseName", "UID"=>"Username", "PWD"=>"Password
$conn = sqlsrv_connect( $serverName, $connectionInfo);
$service = $_GET['service'];
if ($conn)
{
//echo "Connection established.<br />";
}
else
{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
$sql = ("SELECT DefaultContact2 FROM tblServices WHERE ServiceName = '$service'");
$stmt = sqlsrv_query($conn, $sql);
if ($stmt === false)
{
die( print_r( sqlsrv_errors(), true));
}
while ($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC))
{
$dC2 = $row['DefaultContact2'];
}
echo json_encode ($dC2);
sqlsrv_free_stmt( $stmt);
?>
Any help would be greatly appreciated.
You could send data using your Ajax request like so.
$.ajax({
url: "http://IP/development/Query01.php",
method: "POST" // send as POST, you could also use GET or PUT,
data: { name: "John", location: "Boston" }
dataType: "json",
success: function(data) {
editors['Contact2'].setValue(data);
}
});
Then in PHP access the sent data:
<?php
print_r($_POST);
/*
[
"name" => "John",
"location" => "Boston"
]
*/
?>
You cannot pass the javascript's variable to php on same page.
You can do this with ajax call with POST or GET method, and then you can send the manipulated data back to you browser and store it in your javascript's object or variable.
You can do it in a single Ajax call.
Remove from your code this line:
window.location.href = "http://IP/development/Query01.php?service=" + a;
And modify a bit the Ajax call
$.ajax({
type: 'GET'
data : {
service: sender.getValue();
},
url: "http://IP/development/Query01.php",
dataType: "json", //the return type data is jsonn
success: function(data){ // <--- (data) is in json format
editors['Contact2'].setValue(data);
//alert(data);
//parse the json data
}
});
I put the same variable name for the Get in the Ajax call. But I don't know if your query01.php should accept to do now both actions in the same call.
Thank you guys for your help. Just thought it would be useful, if I posted of what I went with in the end, regardless of whether it is the right way, it certainly done the job.
// If the user changes the ServiceID field.
if (sender.getFieldName() == 'ServiceID')
{
// Variable Declaration
serviceName = sender.getValue();
{
// Use JQuery.Ajax to send a variable to the php file, and return the result.
$.ajax({
// Access the PHP file and save the serviceName variable in the URL, to allow the $_GET..
// method to access the javascript variable to apply it within the SQL Query.
url: "http://ServerName/development/DefaultContact1.php?service=" + serviceName,
// retrieve the result, using json.
dataType: "json", // the return type data is jsonn
success: function(data)// <--- (data) is in json format
{
// pre-fill the contact1 field with the result of the PHP file.
editors['Contact1'].setValue(data);
}
// End of Ajax Query
});
// End of function to prefill Contact1 field.
Thank again for your responses!
I don't how to ask this question but if their are duplicates send me that. Their are several .php files i have made
content.php, show.php and showFilteredResult.php .
content.php sends the start date and end date to the show.php and it returns the the orderIds which are of that date
$(document).ready(function () {
var srt = $("#cal1Date1").val();
var end = $("#cal1Date2").val();
$.ajax({
url: "http://localhost/show.php",
data: {
srt: srt,
end: end
},
type: "POST",
dataType: "json",
complete: function (response) {
$rtndata = response.responseText;
var dat1a = jQuery.parseJSON($rtndata);
var result = dat1a.OrderID;
console.log(result[0]); // send this result
}
});
});
now I want to send this $result with orderids to showFilteredResult.php where then i can make tables etc.
I'd skip the AJAX and just use request parameters (GET or POST).
cal1Date1 and cal1Date2 are input fields I assume. Wrap them in a form and post the values to a PHP form handler that could handle the lookup and display. No need for the AJAX middle-man here.
Just make a similar Ajax request to showFilteredResult.php I would have them in a separate function.
function showFilteredResult($result){
$.ajax({
url:"http://localhost/showFilteredResult.php",
data: {
result:$result
},
type:"POST",
dataType: "json",
complete:function(response){
$rtndata=response.responseText;
var dat1a=jQuery.parseJSON($rtndata);
var result=dat1a.OrderID;
console.log(result[0]);// do something with the data returned from showFilteredResult.php
}
});
}
and from the request that you have just call that funciton like
... $rtndata=response.responseText;
var dat1a=jQuery.parseJSON($rtndata);
var result=dat1a.OrderID;
console.log(result[0]);// send this result
showFilteredResult(result[0]);
}
});
Instead making another request to server , you have another option to do that. Let's say you get orderId from show.php before sending back , right ? Then you can use this orderId to do what u want such as query which u have written in showFilteredResult.php . then return back to client for final result . In that way you can eliminate the unnecessary http request.
my javascript won't go into my Database.php file.
Anyone knows what's wrong?
I know there is another thread with this question but it just doesn't work for me.
I have this in javascript
var Score = 5;
//Score insert
var postData =
{
"Score":Score
}
$.ajax({
type: "POST",
dataType: "json",
url: "Database.php",
data: {myData:postData},
success: function(data){
alert('Items added');
},
error: function(e){
console.log(e.message);
}
});
and this in php
function InsertScore(){
$table = "topscores";
if(isset($_POST['myData'])){
$obj = json_encode($_POST['myData']);
$stmt = $conn->prepare("INSERT INTO " + $table + " VALUES (?)");
$stmt->bind_param('s', $obj);
$stmt->execute();
}
else{
console.log("neen");
}
$result->close();
change this line
success: function InsertScore(data){
to this
success: function(data){
the success parameter of jquerys ajax method has to be a anonymous function (without a name) or one defined in javascript but definitely not a php function.
You should read up on variable scope, your $table variable is not defined in the scope of your function.
You also have an sql injection problem and should switch to prepared statements with bound variables.
You are trying to send an object to your PHP file instead of a JSON data type.
Try 2 use JSON2 to stringify your object like this :
var scoreINT = 9000;
var usernameSTRING = "testJSON"
var scoreOBJ = {score:scoreINT,username:usernameSTRING};
var jsonData = JSON.stringify(scoreOBJ);
this would give you the following result "{"score":9000,"username":"testJSON"}"
You would be able to send this with your AJAX if you change ( if you follow my variable names ofcourse )
data: {myData:postData}
to
data: {myData:jsonData}
This would already succesfully transfer your data to your PHP file.
regarding your error messages and undefined. the message "e.message" does not exist. so thats the "undefined" you are getting. no worries here.
I noticed the succes and error are called incorrectly. I've just deleted them because there is no need to.
Next. moving up to your PHP.
you would rather like to "DECODE" then to encode your encoded JSON.
you could use the following there :
$score = json_decode($_POST['json'],true);
the extra param true is so you are getting your data into an array ( link )
or you could leave the true so you are working with an object like you already are.
Greetings
ySomic
This question already has answers here:
Javascript array for AJAX POST send
(2 answers)
Closed 9 years ago.
I need help, I can't find the solution. I have a javascript array which I need to pass to a php script that will store all the array values (max 3) on Session variables. My javascript array comes from a string.split call:
var indentificators = id.split("_");
What I need is some help on how to do the Ajax call and then how to get every element of the array one by one.
My main problem is the format that this data has to be sent and how to retrieve it.
PD: I would post my current ajax call code but I think it would not help, it´s all messed up.
JSON is your answer here.. Are you using a javascript library like jQuery or MooTools?
jQuery:
How do I encode a javascript object as JSON?
url = 'target.php';
data = {identificators: JSON.stringify(identificators) };
jQuery.post( url, data, , function( response ) {
//response handling
});
MooTools:
url = 'target.php';
data = { identificators: JSON.encode(identificators) };
howto post (Async) in mootools:
http://mootools.net/docs/core/Request/Request
In php:
$phpArray = json_decode($_POST['identificators']/$_POST['identificators']);
You can format your answer to send as JSON String
For example:
Javascript array:
var indentificators = id.split("_"); // [0] => 'Stack', [1] => 'Overflow'
so you can do this:
var response_to_send = "{\"var1\":" + indentificators[0] + ", \"var2\": " + indentificators[1] + "}";
here you receive this string in your php script (supposing the ajax request is successful and the value of the string in POST is 'values'):
$values = json_decode($_POST['values'])
echo $values[0]; // This print 'Stack' echo $values[1]; // This print 'Overflow'
I hope this is what your searching
var array = id.split("_");
data = JSON.stringify(array);
var url = 'you/url'
$.ajax({
type: "POST",
url: url,
data: {array: data},
});
Finaly I solved it:
var identificadors = id.split("_");
$.ajax({
url: './phpScripts/comunicador.php?method=sessioList',
type: "POST",
data: ({data: identificadors}),
success: function(){
alert('cool');
}
});
Then at my php page:
function sessioList() {
$data = $_POST['data'];
$_SESSION['list_id_product'] = $data[0];
$_SESSION['list_id_tarifa'] = $data[1];
$_SESSION['list_index'] = $data[2];
}
As I said, my main problem was the format for the data to be sent and how to get it.
Thanks all, I really appreciate it.
How to access the serialized data in a PHP file in following situation?
The code and the serialized data is as follows:
$(document).ready(function() { $(document).on('click', '#delete_url', function (e) {
e.preventDefault();
var items = new Array();
$("input:checked:not(#ckbCheckAll)").each(function() {
items.push($(this).val());
});
var str = $("#user_filter").serialize();
$.ajax({
type: "POST",
url: "manage_users.php?op=delete_bulk_users&items="+items,
data: str,
dataType: 'json',
success: function(data) {
//var message = data.success_message;
var redirect_link = data.href;
alert(redirect_link);
window.location.href = redirect_link;
}
});
});
});
The data I'm getting in after serialize in str is as follows:
op=group_filter&page=1&from_date=11%2F10%2F2000&social_login=&to_date=11%2F10%2F2013&login_criteria=all&user_name=&user_state=&user_email_id=&user_city=
Now the PHP file(manage_users.php) is as follows:
/*The code is actually one of the switch casees*/
prepare_request();
$request = empty( $_GET ) ? $_POST : $_GET ;
$op = $request['op'];
switch( $op ) {
case "delete_bulk_users":
print_r($request);/*For printing the received array of values after form submission
Here I'm not getting serialized data */
}
Thanks in advance.
The serialize function is intended to be used to create a query string for a URL from a collection of inputs (or an entire form), and will out of necessity encode characters such as / (which denotes a directory in a URL). There's no way to tell .serialize() to convert to the "proper" format because it already is.
If you're using the result of .serialize() as part of an AJAX request it's fine to do that like so:
$.ajax({
url: 'yourpage.php',
data: str, // the string returned by calling .serialize()
... // other options go here
}).done(function(response) {
// do something with the response
});
Your server should handle decoding those characters when it receives the request and provide the correct values to you.
If you're using it for something else you could try using the native JavaScript decodeURIComponent function to convert those encoded characters back, like so:
str = decodeURIComponent(str);
Note that calling decodeURIComponent and then trying to use it for an AJAX request won't work.
For more information on URI encoding take a read through the MDN entry for encodeURIComponent.