This does not answer the question - jQuery Ajax return html AND json data
I can not use the wrap method because I do not have a single html string. I am not using Phery, I have tried the first option here and the second nested call runs before the first so that data is undefined- jquery Use two done callbacks in same function, one with datatype json one without and we are not using html5 only for this. Therefore the referenced answer does not address the question.
In my .done function I have (data) returning. This data is a mixture of php echo's and a single JSON_encode array. Sample data:
.....
//other divs and data above this point
<div id="test">text</div>
{"ids":["1","5","2","6"]}0
AJAX
.done(function(data) {
console.log(data);
func2(json_string)
})
I want to be able to extract and separately work with the array {"ids":["1","5","2","6"]}0. I am trying to pass it along to another function, but only that portion of the data
Here's a very simple content-negotiation example using a query string parameter...
In your PHP, break up your HTML and JSON parts like this
<?php
$format = $_GET["format"] ?? "html";
if ($format === "json") {
header("Content-type: application/json");
echo json_encode(["ids" => [1, 5, 2, 6]]);
exit;
}
?>
.....
//other divs and data above this point
<div id="test">text</div>
Then in your JavaScript code, fetch the two parts using
$.ajax(my_ajax.ajax_url, {
dataType: "html",
// etc
}).done(html => {
// html content here
})
and
$.ajax(`${my_ajax.ajax_url}?format=json`, {
dataType: "json",
// etc
}).done(json => {
// json content here
})
I have problem with send array in $.post to php.
var_dump result is "NULL"
JSON.stringify doesn't work..
JQUERY
var photobox = [];
photobox.push(e.target.result);
$.post("../modules/upload.php",{"images[]" : photobox, count : sum},
function(data)
{
$('.list').prepend(data);
}).done(function() {
$('#files').prop('disabled', false);
$('.file-search').html("Szukaj...");
$(".img-thumbnail").removeClass("first");
$(".img-thumbnail").first().addClass("first");
e.target.result is base64 code
PHP
$images = $_POST['images'];
var_dump($images);
You can send arrays like this:
$.post('/thepage.php', {'NameOfKey': variableName});
The above code will allow VariableName to be an Array.
You would need to encode to JSON on your client, but when on your server (PHP) convert it back to an array by using json_decode:
http://php.net/manual/en/function.json-decode.php
I have trouble with getting a value from an xmlhttp request after sending it with ajax to a php file and insert it into an mysql database. I get from the yahoo finance api the output you can see in the html snippet. After that the value of this html element should be sended to the file insertvolume.php.
After successful sending I save the data into an variable named $jsonString and decode it. Then I try to insert a specific value from the array into my mysql database but it wont work. I think the problem is that the value is into any other arrays but I dont know how to write that. I only need that array named results Any hints?
the html:
<div id="output">{"query{"count":1,"created":"20160215T09:15:04Z","lang":"deDE","results":{"quote":{"symbol":"ZN","Ask":"2.05","LastTradeRealtimeWithTime":null,"ChangePercentRealime":null,"ChangeFromYearHigh":"-0.45","LastTradeWithTime":"4:00pm<b>1.81</b>",astTradePriceOnly":"1.81", "Volume":"500","HighLimit":null,"LowLimit":null,"DaysRange":"1.781"}}}}</div>
javascript:
var outputt = $('#output').text();
$.ajax({
type: "POST",
dataType: "json",
url: "insertvolume.php",
data: {myData: outputt},
success: function(data){
//alert('Items added');
}
});
some pice of code from insertvolume php:
$jsonString = $_POST['mydata'];
$jsonArray = json_decode($jsonString, true);
$jsonArray1 = $jsonArray['query']['results']['quote'];
if ($stmt = $mysqli->prepare('INSERT INTO volume ( stocksymbol, volume, time) VALUES ( ?, ?, now())')) {
/* bind parameters for markers */
$stmt->bind_param($jsonArray1['symbol'], $jsonArray1['volume']);
/* execute query */
$stmt->execute();
/* close statement */
$stmt->close();
}
After decoding the data you cannot retrive the json data directly. We should create object for that. Here i am giving you the reference link of how to access values of json.
Get value from JSON array in PHP
In javascript code it is written as
var outputt = $( "#output" ).val();
But the div is not having the value. The content is present inside the div. So change the line code to
var outputt = document.getElementById('output').textContent and try.
Now you are able to access the array in javascript. But we are unable to access the data of output code from your line.
In ajax call remove the line
contentType: "application/json; charset=utf-8",
and then execute. It will work
The console.log on the first line returns a large array of values. And the Console.log(Data) at the end is displaying the plain text response from the server, but the $_POST variable on the server is empty.
The JS:
console.log(topost);
$.post(url,topost,function ( data ){
console.log(data);
});
The console.log(topost);
["DiscontentDisciple","illuminatedwax","S2S2S2S2S2","bechus","syncretic","davidreiss666","Skuld","soupyhands","AutoModerator","imluckytometyou","Lord_Arioc","IIdsandsII","Kylnas","alanpugh","langis_on","TheBigDickedBandit","long_wang_big_balls","arnoldlol","SBringer","ExoticCarMan","HaidiMontag","10FootPenis","SupriseRape","AManHasSpoken","ComedicCounterpart","Suddenly_Something","agenthex","GenerallySpecific","WelcomeToTarget","brainswho","Gooflactus","alcakd","Stingray88","TossTime","yolfer","biskits1","Evarg","phishroom","BuccoBruce","LookingForAlaska","getDense","lewisthemusician","tmotom","tha_ape","spankymuffin","Dashing_Pony","RuafaolGaiscioch","BeaverManiac","Careless_Con","Texas_","i_am_sad","The_helpful_idiot","Kon-chezz","bombdailer","frezik","Galifreyan2012","metalshadow","lightpollutionguy","b3mus3d","crazdave","merpes","naked_guy_says","GoodGuyAnusDestroyer","Bibliophobia","Internet_Lynch_Mob","photo","adkoe","ZeitTaicho","movie_man","iamkush","sired_tick","jyjjy","WhipIash","rred82","E_Diddyyy","CYBERPENISATTACK","MJYTR","TheBaconHasLanded","quarktheduck","heroic_trig","sleevieb","Burrow","myhousemateisabitch","promethephile","msm008","daskrip","jonnie123","Legendman3","Makes_Sad_Faces","anxiousalpaca","crankykong","IamDa5id","CocoSavege","iamsofuckedseriously","EvTheSmev","Briscotti","MarkieMarkl","CornishCucumber","BearsStillSuck","government_shill","Ihaveafatcat","gh5046","Sayum","henryponco","bolaxao","mrbriancomputer","PsychicNinja_","poopslooshed","REDDIT-","IVI4tt","spleendor","ngmcs8203","deadbeatbum","vegibowl","workingalot","Black_Apalachi","Incongruity7","rdeari1","ihahp","im_0n_toilet","Andynack","photokeith","Alpha17x","5NL70","AtticusFinch1962","clayvn","anonymau5","coplay","gnarbucketz","BukkRogerrs","teusz16","digital_evolution","theredcheck","empw","OrigamiRock","lumptoast","alphanovember","Nahtanos","som13","rstyknf","jmadden287","patchworkpavements","Computer-Blue","Miltage","bwaxxlo","aussiegolfer","coaltown","ThePickleMan","mpm96","Ilyanep","merreborn","Theemuts","wufoo2","thunderbar","blindado9","ntorotn","CatrickSwayze","HankSinatra","redditbots","Word_Inventor","catbeef","SoLongSidekick","Elefaze","Jinksywinksy","Mordy2011","thatusernameisal","Kanin","inthekeyofbflat","buckygrad","DeaD_bAU5","Toe_Fat","wsright987","Pachi2Sexy","woprdotmil","AmmoBradley","pokelord13","kroutonz","mattoftheD","WipeMyAssWith100s","ShuckBeam","dookyface","XLR8Sam","your_backpack"]
The response I get:
{"postyn":"YES"}
The PHP:
foreach ($_POST as $key => $value){
$data[$key] = $value;
}
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$data['postyn'] = 'YES';
}
I don't understand why the $_POST variable is empty?
$.post(url,{**NAMEME**: topost} ,function ( data ){
console.log(data);
});
You're trying to pass post data as an array it appears. It needs to either be a string or an object.
Description of data property for jQuery.post():
data A map or string that is sent to the server with the request.
From http://api.jquery.com/jQuery.post/
My guess here based on what you're trying to do is an object. Which brings up the next problem, both an object and your PHP script are expecting both keys and values, but you're only passing values.
You data object should look something like:
topost = {
somekey1: "DiscontentDisciple",
somekey2: "illuminatedwax",
somekey3: "S2S2S2S2S2",
// etc etc etc
};
I am using jQuery and PHP to write JSON data to my server. I'm processing a decent amount of repeating numeric data (~.75kb), so I want to pass the data to PHP in the form of a multidimensional array.
At the moment I cannot manage to get the data to PHP in a form that it can recognize. I've tried various combinations of sending/receiving as arrays and objects with no success.
The best case scenario would be one in which I pass a the array to the PHP and the PHP converts it to a readable form. I'd rather not use associative arrays or any serializing on the part of the Javascript.
Code... This is giving me a 500 internal server error, which no longer occurs if I omit the passed data variable. (I'm not yet using $data in the php file yet because I know it's not working.)
function generateData() {
// code here
return [ one[ sub_one[], sub_two[] ], two[], three[], four[] /* Etc... */ ]
}
function saveData() {
$.ajax({
url: "scripts/save.php",
data: {
"area":"testing",
"location":"testing",
"name":"testing",
"data":generateData()
}
});
}
<?php
$area = $_GET['area'];
$location = $_GET['location'];
$name = $_GET['name'];
$data = $_GET['data']);
# Performing operations with variables...
echo 1;
?>
Thanks for any help you can offer.
Found a solution:
"data": {
data: generateCellData()
}
The above code passes data as an object to PHP, whereby I can access the original array as $data("data"). I'm still somewhat baffled by why this works when I'm already passing the data and other parameters as an object.