I want to send data through an array
This transmitter code:
<script type="text/javascript">
$(function() {
$(".cat_button").click(function() {
var element = $(this);
var test = $("#cou").val();
var test2 = $("#category2").val();
var data = [
{data:test},
{data:test2}
];
if(test=='' || test2=='.....')
{
alert("fill data");
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="http://tiggin.com/ajax-loader.gif" align="absmiddle"> <span class="loading">Loading...</span>');
$.ajax({
type: "POST",
url: "insert2.php",
data: {data: data},
cache: false,
success: function(response){
console.log(response);
}
});
}
return false;
});
});
</script>
This code reception:
print_r($_POST['data']); // dumps an array
$course = $_POST['data'][0]['data'];
$category = $_POST['data'][1]['data'];
$insert_new_cou = mysql_query("insert into course (name,cat_id) values ('$course','$category')") or die($insert_new_cou."<br/><br/>".mysql_error());
But show me the following error:
Cannot use string offset as an array
I think the solution using Jtgson but I do not know how to use it
It can be done by JSON encoding your array of objects. In the $.ajax call:
...
url: "insert2.php",
data: {data: JSON.stringify(data)},
...
On the PHP side use json_decode() to get an array of objects from the JSON string:
$data = json_decode($_POST['data']);
$course = $data[0]->data;
$category = $data[1]->data;
Related
I would search for the solution, but I don't know what exactly do I have to search.
The task is to grab texts with ID's (#ftext_1,..._2,..._3,..._4) in html file and send them to php file. After some manipulation with texts in php file I have to insert them back into their ID's in html file.
Here is the code:
var text_1_Replace = $('#ftext_1').text();
var text_2_Replace = $('#ftext_2').text();
var text_3_Replace = $('#ftext_3').text();
var text_4_Replace = $('#ftext_4').text();
$('#ID').on('click', function(){
var text= {
ftext_1: text_1_Replace,
ftext_2: text_2_Replace,
ftext_3: text_3_Replace,
ftext_4: text_4_Replace
}
var targetFile = 'ajax/file.php';
$.ajax({
method: 'post',
url: targetFile ,
data: JSON.stringify(text),
contentType: 'application/JSON'
}).done(function(data) {
console.log(data);
});
});
How do I edit .done function to place new texts in their old ID's(#ftext_1,..._2,..._3,..._4)? The variable with texts array is $result.
so the answer is :
}).done(function(data) {
var text = JSON.parse(data);
var text1 = text.ftext_1;
var text2 = text.ftext_2;
var text3 = text.ftext_3;
var text4 = text.ftext_4;
$('#ftext_1').text(text1);
$('#ftext_2').text(text2);
$('#ftext_3').text(text3);
$('#ftext_4').text(text4);
So, the last update for the topic: The real and nice answer is:
.done(function(data) {
var text = JSON.parse(data);
$.each(text, function(i, val){
$("#" + i).text(val);
});
This code is the solution to my question in this topic. Thank you all, who responded!
The best for you would be send named property that looks like this
$.ajax({
method: 'post',
url: targetFile ,
data: {data: text},
dataType: "json",
success: function(response){
$.each(response, function(element){
$("#"+element.name).text(element.text);
});
}
});
Then in your php you could easily iterate data from post
<?php
$data = $_POST['data'];
$response = [
];
foreach($data as $elementName => $text){
// some text management
$response[] = ['name' => $elementName, 'text' => $text];
}
return json_encode($response);
When you change your received values in php you put them in an array so that you
can call it later easily
PHP
$values = array("one"=>5,
"two"=>"something",
"three"=>$something);
echo json_encode($values);
You need to add
dataType:'json'
in Jquery since you're returning json
JQuery
$.ajax({
method: 'post',
url: targetFile ,
data: JSON.stringify(text), # or data: {"value1":value,"value2":value2},
contentType: 'application/JSON',
dataType:'json',
success: function(response){
console.log(response.one); #Will console 5
console.log(response.two); #Will console "something"
console.log(response.three); #Will console whatever $something holds in php
}
});
You can call it however you want it (response) or (mydata)...
And then you just type response.yourdata (that you declared in php)
I'm using chart.js to generate charts on my page.
However I want these charts to be populated by my SQL database.
I'm able to get my data out of my database, but I won't draw the chart
I got a canvas on my main page called "OmzetChart" , this is where the chart should come.
<script>
$.ajax({
type: 'POST',
url: 'templates/getdata.php',
success: function (data) {
lineChartData = data;
//alert(JSON.stringify(data));
var ctx = document.getElementById("OmzetChart").getContext("2d");
var myLineChart = new Chart(ctx, {
type: 'line',
data: lineChartData
});
}
});
</script>
The page of GetData.php results in the following (This is what I need, just want it into my chart):
[{"dag":"23","0":"23","uur":"13","1":"13","SomOmzet":"23.00","2":"23.00"},{"dag":"23","0":"23","uur":"18","1":"18","SomOmzet":"2.50","2":"2.50"}]
Getdata.php:
<?php
include ("../PDO.php");
$conn = DatabasePDO::getInstance();
$sql = "SELECT DATEPART(DD, receiptdatetime) as dag ,DATEPART(hh, receiptdatetime) as uur, ISNULL(abs(cast(sum(NetAmount) as decimal (10,2))),0) as SomOmzet FROM ReceiptLine a , Receipt b, ReceiptLineDetail c
where a.LineType = 200 and a.receiptID = b.receiptid and a.receiptlineID = c.receiptlineID
group by DATEPART(DD, receiptdatetime), DATEPART(hh, receiptdatetime)";
$st = $conn->prepare($sql);
$st->execute();
$list = array();
while ( $row = $st->fetch() ) {
$list[] = $row;
}
$conn = null;
echo json_encode( $list );
?>
json_encode() produces a JSON string. You need to parse this with JSON.parse() before you can use it.
$.ajax({
type: 'POST',
url: 'templates/getdata.php',
success: function (data) {
lineChartData = JSON.parse(data); //parse the data into JSON
var ctx = document.getElementById("OmzetChart").getContext("2d");
var myLineChart = new Chart(ctx, {
type: 'line',
data: lineChartData
});
}
});
Also, using $.ajax() method's dataType parameter, you can leave this parsing to jQuery.
$.ajax({
type: 'POST',
url: 'templates/getdata.php',
dataType: 'json', //tell jQuery to parse received data as JSON before passing it onto successCallback
success: function (data) {
var ctx = document.getElementById("OmzetChart").getContext("2d");
var myLineChart = new Chart(ctx, {
type: 'line',
data: data //jQuery will parse this since dataType is set to json
});
}
});
There are many threads on the subject, but I cannot find any that use PHP. I want to pass the json object to the view, where I will later update an element with the returned json object.
Here is my code:
View:
<input type="submit" class="button" name="insert" value="load"/>
<script>
jQuery(document).ready(function() {
var $ = jQuery;
var baseUrl = [location.protocol, '//', location.host, location.pathname].join('');
$('.button').click(function(){
var clickBtnValue = $(this).val();
var ajaxurl = baseUrl+"?action=load";
data = {'action': clickBtnValue};
$.post(ajaxurl, {}, function (result) {
alert(result);
});
});
});
</script>
And Controller is:
<?php
set_include_path(get_include_path().':../');
require_once('_inc/common.php');
$action = req('action');
if ($action == 'load') {
$result = parse_ini_file('test.ini');
$json = json_encode($result);
}
[UPDATE]
After the code to the answers provided, I now get an Json.parse error. So I edited my code again but the error still persists, I checked online to see if my Json is a valid json and no error on the validator.
$result = parse_ini_file($config_file);
$json = json_encode(array($result),JSON_HEX_QUOT);
var_dump($json);
header('Content-Type: application/json');
View
var request = $.ajax({
url: ajaxurl,
method: "POST",
data: {},
dataType: "json"
});
request.done(function( msg ) {console.log("d");});
request.fail(function( jqXHR, textStatus ) {console.log( "Request failed: " + textStatus );});
});
Like said above, you aren't outputting the JSON, and also you are not setting the content type. But I noticed something else, you did not assign the return type of the post request (JSON).
$.post(url, {}, function (data) {
alert(data);
}, 'JSON');
Be also sure that you encode an array and not a false value, parse_ini_file returns false when it fails.
Try this
<script>
jQuery(document).ready(function() {
var $ = jQuery;
var baseUrl = [location.protocol, '//', location.host, location.pathname].join('');
$('.button').click(function(){
var clickBtnValue = $(this).val();
var ajaxurl = baseUrl+"?action=load";
data = {'action': clickBtnValue};
$.post(ajaxurl, {}, function (result) {
var json =JSON.parse(result);
console.log(json); //see in browser console
});
});
});
</script>
And Controller is:
<?php
set_include_path(get_include_path().':../');
require_once('_inc/common.php');
$action = req('action');
if ($action == 'load') {
$result = parse_ini_file('test.ini');
echo json_encode($result);
}
I'm trying to pass array from ajax to php (controller).
What is wrong with second code as var_dump($data) of first code returns appropriate content and second returns NULL?
FIRST. GOOD.
function myFunction() {
var elementy = document.getElementsByClassName('inputISBN');
var data = elementy[0].value;
$.ajax({
url: "{{ path('test') }}",
type: "POST",
data: { "data": data }
});
}
SECOND. BAD
function myFunction() {
var elementy = document.getElementsByClassName('inputISBN');
var data = [];
data[elementy[0].name] = elementy[0].value;
$.ajax({
url: "{{ path('test') }}",
type: "POST",
data: { "data": data }
});
}
THIRD. UGLY
var elementy = document.getElementsByClassName('inputISBN');
undefined
var data = [];
undefined
data[elementy[0].name] = elementy[0].value;
"667"
Third one is line by line from the socond code written in browser console. And it's return what it should.
edit
and data is pulled out from here:
<input type="number" class="inputISBN" size="2" name="exampleName"
value="666" onchange="myFunction()">
When passing an array to PHP, you want to include the array indicator: []. I thi8nk you need an Object: {}.
function myFunction() {
var elementy = $('.inputISBN');
var data = {};
$.each(elementy, function(){
data[$(this).attr('name')] = $(this).val();
})
$.ajax({
url: "{{ path('test') }}",
type: "POST",
data: { "data": data }
});
}
At this point, you may also want to serialize the data (as was mentioned in the other answer by #Adelphia):
'data': JSON.stringify(data)
jsFiddle: https://jsfiddle.net/Twisty/cw77ann7/
You can call it in PHP: print_r($_POST['data']);
You want to pass your data variable to PHP, which is an array, right? Why not data = JSON.stringify(data); and then on PHP's side, $data = json_decode($_POST['data'], true);
function myFunction() {
var elementy = document.getElementsByClassName('inputISBN');
i = elementy.length;
data = [];
while(i--) data[elementy[i].name] = elementy[i].value;
data = JSON.stringify(data);
$.ajax({
url: "{{ path('test') }}",
type: "POST",
data: { "data": data }
});
}
I have a list of options (categories) of projects that the user can see. By selecting the categories, the div below should update with the lists of projects matching said categories.
Despite using the following answer, almost verbatim, Send array with Ajax to PHP script, I am still unable to retrieve any results, and yet no errors show up either.
The jquery:
// filter for projects
var $checkboxes = $("input:checkbox");
function getProjectFilterOptions(){
var opts = [];
$checkboxes.each(function(){
if(this.checked){
opts.push(this.name);
}
});
return opts;
}
$checkboxes.on("change", function(){
var opts = getProjectFilterOptions();
//alert(opts);
var categories = JSON.stringify(opts);
$.ajax({
url: "/web/plugins/projcat.php",
type: "POST",
dataType: "json",
data: {data : categories},
cache: false,
success: function(data) {
$('#projects').html(data);
//alert(data);
}
});
});
the php (still in testing, so not filled out):
<?php
if(isset($_POST['categories'])) {
//echo "testing";
$data = json_decode(stripslashes($_POST['categories']));
print_r($data);
}
?>
Where is the error?
Try this:
JS
...
// dataType: "json", // remove that; you're not sending back JSON string
data: {categories : categories},
cache: false,
...
PHP
<?php
if($_SERVER['REQUEST_METHOD']=='POST' && isset($_POST['categories'])) {
//echo "testing";
$data = json_decode(stripslashes($_POST['categories']));
// .. process the $data
print_r($data);
return;
}
?>
Your desired array is in $_POST['data'] and not in $_POST['projcats']. Change data: {data : categories}, to data: { projcats: categories }, to use $_POST['projcats'].