Jquery Post Empty Even though Sent Variable has data - javascript
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
};
Related
Posting Data to PHP with Axios
I am creating a Vue app where I am posting to PHP using Axios. So what I have is: methods: { onSubmit () { axios.post('/wp-content/themes/bones/library/jobsResponse.php',{region: Chicago, jobType: Direct Hire}, {headers: {'X-Requested-With': 'XMLHttpRequest', 'Content-type': 'application/x-www-form-urlencoded'}}) .then(function(response){ console.log(response) }) .catch(function(error){console.log(error)}) }, } What that method is doing is when the onSubmit function is ran it will use Axios to POST to a PHP file I created named jobsResponse.php. The data it is posting is 'region: Chicago Region, jobType: Direct Hire'. Then in that jobsResponse.php PHP file I have: <?php $_POST = json_decode(file_get_contents('php://input'), true); $region = $_POST['region']; $jobType = $_POST['jobType']; echo $region; echo $jobType; echo ' this is the posted data content'; ?> So that is getting the posted data from Vue using Axios. In Axios I am running a console.log of the response and when I check the console log it shows me the data I posted to the jobsResponse.php As you can see in the image above the data from my Vue app was posted to the jobsResponse.php file. So that's all fine and well. What I need to do now is take that data I posted to the jobsResponse.php file and use it in my Vue app. So currently in my Vue app I am recieving a JSON object using PHP like so: <?php echo getBhQuery('search','JobOrder','isOpen:true','id,title,categories,dateAdded,externalCategoryID,employmentType,customText12', null, 200, '-dateAdded');?> What I want to do is use the posted data from Axios in that PHP query. So I would need to take that posted data and insert into that PHP in some fashion like: <?php echo getBhQuery('search','JobOrder','isOpen:true AND customText12:"'.$region.'"','id,title,categories,dateAdded,externalCategoryID,employmentType,customText12'); ?> Adding the $region variable to the PHP query would filter the JSON object to only pull back job posts that have the region of whatever that variable is set to. So I have the needed data posting, which is good. I'm just not sure how to take that data and use it to generate a new JSON object on the fly, like ajaxing it.
Well, $_POST is a superglobal, so I wouldn't be overwriting it as they are handled by PHP automatically and best left alone. Like a comment mentioned, $post = file_get_contents('php://input') ?? $_POST; will take the incoming POST request and assign it to the variable $post. Then once you've parsed it: $post = json_decode($post, true); this will parse the JSON string into an associated array. Then get the variables like you mention, $region and $jobType. You'd then plug these into your database query, or if you are not making this production and can have fixed data: have a static text file or save a list of jobs to a variable. // get the incoming POST data $post = file_get_contents('php://input') ?? $_POST; // decode the JSON data $post = json_decode($post, true); // assign the needed data from the POST object $region = $post['region']; $jobType = $post['jobType']; // define how you want to filter the data function $sortJobs($job) use ($region, $jobType) { return ($job['region'] == $region) && ($job['type'] == $jobType); } // get your jobs data $jobs = [[ 'type' => 'x', 'region' => 'minneapolis', 'name' => 'developer'], ['type' => 'y', 'region' => 'chicago', 'name' => 'secretary']]; // filter the jobs data $filteredJobs = array_filter($jobs, "sortJobs"); // return the filtered data http_response_code(200); echo json_encode($filteredJobs);
Printing JavaScript Objects from Associatve Array
What if I want to console.log only one 1(ANY) javaScript object. Currenly it displays all 1000. Please Look at Php and JS files: Server.php if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $data = array("coordinates" => array()); $sql = "SELECT Lng, Lat, URL FROM results LIMIT 1000"; $result = $conn->query($sql); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { $data["coordinates"][] = $row; } } echo json_encode($data); Index.js { $.ajax({ dataType: "json", url: 'server.php', //data: [], data: {param: ""}, success: function(data) { //JSON.parse(data); console.log(data); addMarkers(data,map); } }); }
It helps to understand the json data structure you are outputting, and how you access certain elements from an object made by that json. In your case, you end up with a single object named data (as defined by the .ajax success callback). That object then contains just one keyname with an array of objects. The keyname is coordinates. Inside each array value, is an object from your database row return. If you simply wish to show one object from your array of objects, this is all you need: console.log( data.coordinates[0] ); That would show the first object in the array (arrays start with [0]). console.log( data.coordinates[999] ); That would show the last object in the array of 1000. console.log( data.coordinates[ data.coordinates.length-1 ] ); That would show the last object in an array of a variable size, using itself as the determiner.
It's displaying all because you're logging all. You're returning 1000 objects from your db call, which is why it's logging all. You could find a single object by a key using something like: data.filter(x => x.myPropValue == "myString"); And log that.
If you want your JavaScript AJAX call to not log all 1000 items, you might want to change your php code ($sql = "SELECT Lng, Lat, URL FROM results LIMIT 1000";) to only send one item per call (e.g. replace 1000 with 1), and then adjust the Server Logic to get the respective next item on a following AJAX call. This would also make your Server & Client faster, since it's reducing the total data amount, but would still allow 1000 or more items. You could also try and add a parameter, so that you can tell your php code how many items your JS code needs to get.
Passing php array to javascript then accessing values by key
I'm using $.post to return an array from a separate php file, and trying to access the values of the array in javascript by the keys, but am having trouble doing so. Here's the post code: $(document).ready(function(){ var limRefresh = setInterval(refreshLIM, 10000); var dbAction = "feedRefresh"; var newestRow = <?php echo $newestRow ?>; $.post("jsDb.php",{ action: dbAction,lastRow: newestRow },function(status){ console.log(status); console.log(newArr['status']); console.log(newArr.status); console.log(newArr[0]); }); }); Here's the excerpt of how the response is being formatted in the external php file: echo json_encode(array("status" => "success","actId" => $newActId)); And here's the respective console logs (just trying different options): {"status":"success","actId":"585924418"} undefined undefined { Any ideas where I'm going wrong?
The response you get as status from $.post is a string. You need to parse it order to use it as you intend. Moreover, newArr is undefined because you have not defined it anywhere. This is probably because you have reused someone else's code and missed this part: newArr = JSON.parse(status)
The response is coming as string, so you need to parse it before you can access it as JSON: $.post("jsDb.php",{ action: dbAction,lastRow: newestRow },function(status){ var data = JSON.parse(status); console.log(data['status']) console.log(data['actId']) }
How is dynamically created array in jquery is accessed in PHP
I have created a script that adds items on click into an array. $(document).ready(function() { var array_ids = []; $('.add').click(function() { array_ids.push($(this).parent().siblings('.row_id').html().trim()); alert(array_ids); }); }); Items are coming from mysql database so I am storing primary keys of items. keys are stored in array like this manner 1,2,3,4,5 Now I want to access this array in php so that I could store in database one by one. I thought to doing some ajax and this is my code $('.show').click(function(e) { //e.preventDefault(); $.ajax( { method: 'POST', url: 'createsale.php', data: {items: array_ids}, success: function() { alert('done'); } }); }); I get the done alert but couldn't manage to get it stored in database. Can anyone tell how do I insert those items in mysql?
Send the value from Javascript by using Json {"key":value} or array [1,2,3]. While getting them to use them in PHP, you can use json_decode() to convert the Json or array from Javascript to PHP. If you want your information from PHP to Javascript, Just use the funtion json_encode() that will send a json string. Ref: json_encode, json_decode
your createsale.php file should has something like this below code to receive array Data & dont forget to escape your data using mysql_real_escape_string before doing any mysql query <?php if(isset($_POST["items"]) && $_POST["items"] !=""){ $arr = $_POST["items"]; //convert JS array to PHP array $arr = json_decode($arr,true); //then you have your PHP array => new array(1,2,3,...); /* use for/forEach loop for($i=0;$i<count($arr);$i++){ do the task } */ } ?>
Strange behaviour sending data with PHP JSON encode to jQuery getJSON
I am sending data from PHP to jQuery. Everything works fine except I want to sent the total rows from the DB. I have stripped a lot of other things to put onlu the essential problem. PHP code: header('Content-type: text/json'); header('Content-type: application/json'); $rows = array with the data; That is working fine $total=mysql_num_rows($RSList); $total_data=array("total"=>$total); array_push($data,$total_data,$rows); echo json_encode($data); jQuery code: $.getJSON("..url..", function( data ) { var data_array = eval(data); $.each(data_array[0], function(i, item ) { console.log(item) }); }); The result showing in the browser is: [{"total":532},[{"product_id":"1",.... }]] 532 is the correct value from the mysql_num_rows() Console: An empty string I tried the following: If I set the value manually of total in PHP: $total=100; The result showing in the browser is: [{"total":100},[{"product_id":"1",.... }]] Console of java: 100 If I convert the value in string in PHP: $total="(".$totalRows_RSList.")"; The result showing in the browser is: [{"total":"(532)"},[{"product_id":"1",.... }]] Console: () I have also tried intval, number_format and strval with no success. Very, very strange or ? Update: I have modified as suggested the code and still the same problem: PHP: echo json_encode(array('total' => $total, 'rows' => $rows)); javscript: $.getJSON( "..url..", function( data ) { console.log( data ) $.each( data.rows, function(i, item ) {...} }) Browser: {"total":532,"rows":[{"product_id":"567",...}]} Console: Object { rows=[99], total=""}
You don't need to pass the total rows, just get the length of the parsed JSON object. jQuery code: $.getJSON('...url...', function(data){ console.log(data.length); } PHP Code: header('Content-type: text/json'); header('Content-type: application/json'); $rows = array_with_the_data; //That is working fine echo json_encode($rows);
Note: This answer explains what is wrong with your code. Learn from it, then look at #ojovirtual's answer which shows what I think is the best way for you to accomplish what you were intending to do in the first place. End Note Remove the eval statement from your code. jQuery will have already parsed the incoming JSON (if it is valid) and your success function will receive your array as the data param. Just use that data param instead of data_array. $.getJSON('..url..', function (data) { // if your PHP is sending proper JSON in the format you describe, `data` is now // an array containing two items. The first (`data[0]`) is an object which has // one property, `total`. The second (`data[1]`) is your array of row data, each // of which is an object. // your code in modified form, though I don't understand why you would use `each` $.each(data[0], function (i, item) { console.log(item); }); // just use: console.log(data[0].total); }); Be sure to read the comments in the above code.