What i want to do: copy all selected rows from FIRST table and insert them into SECOND table. In json im sending event type ( insert or delete) and array of IDs rows to copy.
How i can acces to this JSON data in PHP file?
JS:
var data_to_send = {
event : "accept",
ids : ids_to_accept,
}
console.log(ids_to_accept);
$.ajax({
type: "POST",
url: "request.php",
contentType: "application/json; charset=utf-8",
data: data_to_send,
success: function(response){
console.log("Dodałem rekord!");
},
});
PHP:
<?php
//include db configuration file
include_once("connect.php");
if(isset($_POST["data"])){
$data = $_POST["data"];
$ids_to_insert = array();
$ids_to_insert = $data["ids"];
$row_to_insert = $mysqli->query("SELECT * FROM oczekujace WHERE ID='".$ids_to_insert[0]."'");
$inser_row = $mysqli->query("INSERT INTO zaakceptowane(nazwa) VALUES('".$row_to_insert['nazwa']."')");
}
?>
EDIT
Ok, i fixed this. Just deleted contentType...
$.ajax({
type: "POST",
url: "request.php",
//dataType : "json",
//contentType: "application/json; charset=utf-8",
data: {data : data_to_send},
success: function(response){
console.log(response);
console.log("Dodałem rekord!");
},
});
You can use json_decode() function. Its return php array which you can use to insert data in mysql. To read more about json_decode() visit this link.
http://php.net/manual/en/function.json-decode.php
In AJAX use dataType: 'json',
var data_to_send = {
event : "accept",
ids : ids_to_accept,
}
console.log(ids_to_accept);
$.ajax({
type: "POST",
url: "request.php",
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: data_to_send,
success: function(response){
console.log("Dodałem rekord!");
},
});
And in your PHP File use json_decode()
include_once("connect.php");
if($_POST){
$data = json_decode($_POST);
//manipulate $data
$ids_to_insert = array();
$ids_to_insert = $data["ids"];
$row_to_insert = $mysqli->query("SELECT * FROM oczekujace WHERE ID='".$ids_to_insert[0]."'");
$inser_row = $mysqli->query("INSERT INTO zaakceptowane(nazwa) VALUES('".$row_to_insert['nazwa']."')");
}
It will work as you desire.
$_POST['data'] is undefined, because its not present in data_to_send.
You have to either access the posted elements directly in $_POST:
$event = $_POST["event"]);
$ids_to_insert = $_POST["ids"];
or you can change the JS part and provide the data element:
$.ajax({
type: "POST",
url: "request.php",
data: {
"data": data_to_send,
},
success: function(response){
console.log("Dodałem rekord!");
}
});
no need for json_decode, jQuery already converts the data object into a urlencoded parameter string, which PHP in turn converts into an array.
Related
In the first document I added a JSON string filled with numbers to localstorage like this:
$.ajax({
url: "oyvind_liste.php",
data: {aktuelle_verdier: aktuelle_verdier},
dataType: "json",
success: function(result){
var dataToStore = JSON.stringify(result);
localStorage.setItem('key', dataToStore);
}});
Then in another document I am trying to post the JSON string retrieved from local storage like this:
<script>
var data = JSON.parse(localStorage.getItem('key'));
var localData = data.join(", ");
$.ajax({
type: 'post',
data: {localData: localData},
url: '',
dataType: "json",
success: function(result){
console.log(result)
}});
</script>
The PHP on the same page as the post tries to fetch the data like this:
<?php
$user_id = isset($_POST['localData'])?$_POST['localData']:"";
$values = json_decode($user_id);
var_dump($values);
?>
When I run var_dump I get Array(), so in essence it doesn't post anything. Anyone know whats going wrong?
You don't need to use JSON when sending an array in an object argument to $.ajax. Just put the array there, and jQuery will URL-encode it.
var data = JSON.parse(localStorage.getItem('key'));
$.ajax({
type: "post",
data: { localData: data },
...
});
Then in PHP you can do:
$values = isset($_POST['localData']) ? $_POST['localData'] : array();
var_dump($values);
You can also send JSON this way:
var json_string = localStorage.getItem('key');
$.ajax({
type: "post",
data: { localData: json_string},
...
});
then in PHP do:
$values = json_decode(isset($_POST['localData']) ? $_POST['localData'] : '[]');
var_dump($values);
I have the following code:
var arr = {City:'Moscow', Age:25};
$.ajax({
url: "<? echo $this->createUrl('cities/index');?>",
type: "POST",
data: JSON.stringify(arr),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(data){
alert(data);
}
});
The result is null. In the PHP side I have:
echo json_encode($_POST);
and
print_r($_POST);
But both are giving empty results (checked Firebug also).
You can also set the dataType in Ajax to specify the content type as follows.
var city='city name';
var age=10;
$.ajax({
url: "<? echo $this->createUrl('cities/index');?>",
type: "POST",
data:"City="+city+"&Age="+age,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(data){
alert(data);
}
});
and in cities/index.php you can get this data by follows
if($_POST){
$city=$_POST['City'];
$age=$_POST['Age'];
// and do with $city and $age what you want.
//for return anything thing to `json` use follows we pass $age back to ajax
echo json_encode($age);
}
I guess you don't need to stringyfy the data because data should be PlainObject or String but in your case you can simply write like below
var arr = {City:'Moscow', Age:25};
$.ajax({
url: "<? echo $this->createUrl('cities/index');?>",
type: "POST",
data: arr,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(data){
alert(data);
}
});
as documented in jquery official site https://api.jquery.com/jQuery.ajax/
data
Type: PlainObject or String
Data to be sent to the server. It is converted to a query string, if
not already a string. It's appended to the url for GET-requests. See
processData option to prevent this automatic processing. Object must
be Key/Value pairs. If value is an Array, jQuery serializes multiple
values with same key based on the value of the traditional setting
(described below).
The data option passed to $.ajax() must be either a simple object, that jQuery will transform into a string of the formatkey1=value1&key2=value2.. OR it should be a string of the form key1=value1&key2=value2...
In your case, it can be solved by passing the object itself and letting jQuery do the query string formatting:
$.ajax({
...
data: arr,
...
});
try this
var arr = {City:'Moscow', Age:25};
$.ajax({
url: "<? echo $this->createUrl('cities/index');?>",
type: "POST",
data: arr,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(data){
alert(data);
}
});
Here is a partial example of what I am trying to achieve.
I am trying to retrieve a value from ajax but the javascript result.success variable is undefined. I have the following:
PHP:
$result = array ("success" => null, "html" => "");
$result['success'] = true;
$result['html'] = "test";
echo json_encode($result);
Javascript/jQuery:
var ID = 1
$.ajax({
type: 'POST',
url: '/ajax/load.php',
contentType: "application/json; charset=utf-8",
datatype: 'json',
data: {ID: ID},
beforeSend: function(xhrObj) {
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Accept","application/json");
},
success: function(result) {
if (result.success) {
// do something
}
});
The response I am getting from ajax (retrieved from chrome dev tools) is {"success":true,"html":"Test"}
This looks fine to me however in the JavaScript result.success is undefined. I believe this will be simple I just can't see where the issue lies..
Your error is here:
datatype: 'json',
Javascript is case sensitive and the property is dataType:
dataType: 'json',
Because of that, jQuery is not being told to automatically parse the JSON, so the result is just treated as html or plain text.
You also need to remove the content-type header because that specifies the content type for the request not response. You are sending form/url encoded in the request, not JSON.
$.ajax({
type: 'POST',
url: '/ajax/load.php',
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: {ID: ID},
beforeSend: function(xhrObj) {
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Accept","application/json");
},
success: function(result) {
if (result.success) {
// do something
}
} // Maybe your forgot this
});
in other words - Basic Debugging
in your PHP page put this on top of the page (you are accepting only json response but probably your response headers content type is text/html
header('Content-type: application/json');
My jQuery ajax posting is not working. Here is the javascript
function SocialButtons() {
var $buttonWrapper = jQuery('.WrapperDiv');
if ($buttonWrapper.length){
var postData = $buttonWrapper.html();
jQuery.ajax({
type: 'POST',
url: 'http://www.wordpress-site.com/wp-contents/themes/theme-name/post.php',
data: postData,
cache: false,
success: function(data) {
console.log(data);
},
contentType: "application/json",
dataType: 'json'
});
}
}
I am saving the data to be posted inside a hidden div like
<div class='WrapperDiv hidden'>{"post_id":392,"url":"http:\/\/www.wordpress-site\/post\/post-title\/","title":"SEO Friendly title"}</div>
All I am getting in return from the post.php page is an empty array. Here is my code for post.php
<?php
if(isset($_POST)){
print_r($_POST);
} else {
echo "0";
}
?>
Any Idea whats wrong?
EDIT : Its working after I removed
contentType: "application/json",
dataType: 'json'
What about something like this:
var postData = "data=" + encodeURCIComponent($buttonWrapper.html());
Than in PHP:
echo $_POST["data"];
Than parse it or something....
Couple of things to try,
Try to pass the data directly in to the data object first. If it
works then you can debug and see why it's not ready your hidden div.
instead of $buttonWrapper.html try $buttonWrapper.text();
function SocialButtons() {
var $buttonWrapper = jQuery('.WrapperDiv');
if ($buttonWrapper.length){
var postData = $buttonWrapper.**text**();
jQuery.ajax({
type: 'POST',
url: 'http://www.wordpress-site.com/wp-contents/themes/theme-name/post.php',
data: **{'id':1}**,
cache: false,
success: function(data) {
console.log(data);
},
contentType: "application/json",
dataType: 'json'
});
}
}
Inside your jQuery ajax call, your data is not set to $_POST variable names. Hence why nothing is showing
Try changing your function to this:
function SocialButtons() {
var buttonWrapper = jQuery('.WrapperDiv');
if (buttonWrapper.length){
var postData = buttonWrapper.html();
jQuery.ajax({
type: 'POST',
url: 'http://www.wordpress-site.com/wp-contents/themes/theme-name/post.php',
data: {postData: postData},
cache: false,
success: function(data) {
console.log(data);
},
contentType: "application/json",
dataType: 'json'
});
}
}
Then you should have a $_POST['postData'] variable on your print_r or var_dump of $_POST.
Its working after I removed
contentType: "application/json",
dataType: 'json'
What is the best way to send data and receive a response dependent on that data?
Consider the PHP file used for the request:
$test = $_POST['test'];
echo json_encode($test);
I have tried unsucessfully to achieve this with:
$.ajax({
type: "POST",
dataType: "json",
data: '{test : worked}',
url: 'ajax/getDude.php',
success: function(response) {
alert(response);
}
});
Lose the quotes to pass the object:
$.ajax({
type: "POST",
dataType: "json",
data: {test : worked},
url: 'ajax/getDude.php',
success: function(data) {
alert(data);
}
});
Instead of this
data: '{test : worked}'
try
data: {"test" : worked} // Worked being your data you want to pass..
data: {"test" : "worked"} // Else enclose worked in quotes
The problem appears to be that you're submitting a string rather than a json object - change data: '{test : worked}' to data: {test : 'worked'}