Passing data from javascript to PHP via POST not working - javascript

Im trying to send an array, populated using javascript on client-side, to a php file in the backend.
MAIN.JS
var list = iterateItems();
_ajax("https://127.0.0.1/prog1/final/class/ticket.php", list)
.done(function(list){});
});
function _ajax(url,data) {
var ajax = $.ajax({
type : "POST",
datatype : "string",
url : url,
data : data
})
return ajax;
}
function iterateItems() {
// array is an array populated in this function, returned to be sent to ticket.php
return JSON.stringify( array );
};
TICKET.PHP
<?php
var_dump(json_decode($_POST['list']));
?>
And executing this, I'm getting this result:
Notice: Undefined index: list in D:\127.0.0.1/prog1/final/class/ticket.php on line 2
NULL
Im not understanding why im getting an undefined index.
I tried googling this, but most responses seem to point in the direction of using some kind of HTTPS method, which is what I'm trying to achieve via POST.
Any help will be greatly appreciated. Thank you.

The 'list' undefined issue might be due to the structure of the JSON array you pass.
Try the below code and check if it works. If not let's check further :)
var list = {'list': iterateItems()};
_ajax("https://127.0.0.1/prog1/final/class/ticket.php", list)
.done(function(list){});
});
function _ajax(url,data) {
var ajax = $.ajax({
type : "POST",
datatype : "json",
url : url,
data : data
})
return ajax;
}
function iterateItems() {
// array is an array populated in this function, returned to be sent to ticket.php
return JSON.stringify( array );
};
Your PHP Code:
<?php
var_dump(json_decode($_POST['list']));

PHP can't parse JSON parameters automatically. $_POST will only be filled in from a URL-encoded string or a FormData object.
$.ajax will URL-encode an array automatically for you.
_ajax("https://127.0.0.1/prog1/final/class/ticket.php", array)
.done(function(list) {});
function _ajax(url, data) {
var ajax = $.ajax({
type: "POST",
dataType: "string",
url: url,
data: {list: data}
})
return ajax;
}
In PHP you then don't need to call json_decode(). The value of $_POST['list'] will be the array.

Related

Print JSON string from URL

I'm using ajax to parse JSON data from a URL. I need to capture the parsed array into a variable. How would I go about this? Thanks
function rvOffices() {
$.ajax({
url:'https://api.greenhouse.io/v1/boards/roivantsciences/offices',
type:'GET',
data: JSON.stringify(data),
dataType: 'text',
success: function( data) {
// get string
}
});
}
rvOffices();
var rvOfficesString = // resultant string
You can use JSON.parse(data) to convert the desired output to JSON, and then access the objects and array indexes from within that with .object and [array_index] respectively:
function rvOffices() {
$.ajax({
url: 'https://api.greenhouse.io/v1/boards/roivantsciences/offices',
type: 'GET',
dataType: 'text',
success: function(data) {
var json_result = JSON.parse(data);
//console.log(json_result); // The whole JSON
console.log(json_result.offices[0].name);
}
});
}
rvOffices();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You also don't need to pass any data, as you're performing a GET request.
Hope this helps! :)
So I guess you are not sure about the ajax call, so lets break it..
Ajax call is a simply method to make a request to remote resource (Get/post/put...) the type of request (GET/POST) depends upon your need.
so if you have an endpoint that return simply data as in your case a simple get/post request is sufficient.
You can send addition data with request to get the data from endpoint (say id of resource (say person) whose other fields you want to get like name, age, address).
here is link for ajax request in jQuery
here is jQuery parse json parse json in jQuery
So for example:
// let's say when you call this function it will make post request to fixed end point and return data else null
function rvOffices() {
var res = null; // let be default null
$.ajax({
url:'https://api.greenhouse.io/v1/boards/roivantsciences/offices',
type:'GET', // type of request method
dataType: 'text', // type of data you want to send if any.
success: function( data) {
res = $.parseJSON(data); // will do the parsing of data returned if ajax succeeds (assuming your endpoint will return JSON data.)
}
});
return res;
}
// lets call the function
var rvOfficesString = rvOffices();
// print the value returned
console.log(rvOfficesString);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can try something like: -
$.ajax({
url:'https://api.greenhouse.io/v1/boards/roivantsciences/offices',
type:'GET',
dataType: 'text',
success: function(response) {
// get string
window.temp = JSON.parse(response);
}
});

AJAX request in ColdFusion

How can I do a AJAX request in ColdFusion?
I have my javascript:
function getdata(){
var formElements=document.getElementById("CFForm_1").elements;
var data=[];
for (var i=0; i<formElements.length; i++){
if(formElements[i].name == 'customersid')
data.push({'customersid':document.getElementById("customersid").value});
if(formElements[i].name == 'customerstoid')
data.push({'customerstoid':document.getElementById("customerstoid").value});
}
$.ajax(
{
type: "get",
url: "components/BillingCalc.cfc",
data: {
method:"ajaxGetTotalCost",
data: data.join()
},
dataType: "json",
success: function( objResponse ){
}
});
}
My component:
component displayName="Calc" {
remote function ajaxGetTotalCost(data){
data = deserializeJSON(arguments.data);
WriteDump(data); abort;
}
I am getting the error: JSON parsing failure at character 2:'o' in [object Object],[object Object]
Does anyone knows how to do AJAX request in CF?
This function:
remote function ajaxGetTotalCost(data){
data = deserializeJSON(arguments.data);
WriteDump(data); abort;
}
is not complete. It's at the stage where you have to call it from a ColdFusion page, not with javascript. That will enable you to see the results of the writedump(data) command to ensure it's what you expect. You have to add more code to the function to get it to produce a variable javascript can receive, and then return that variable to whatever is calling the function.
The issue is related to dataType attribute you are passing with $.ajax() method. dataType: "json" indicates your AJAX request is expecting JSON data as a response. But in your case you are simply returning DUMP of the deserialized JSON, which is HTML not JSON. So if you want it to work properly, then you need to return JSON data from your ColdFusion function. You can try this and see if it works.
remote function ajaxGetTotalCost(data){
data = deserializeJSON(arguments.data);
return serializeJSON(data));
}

How to iterate with javascript a json response from symfony2

i want to itarate a json response from symfony and put it in a table td>
my action :
$search = $this->getDoctrine->...;
$serializer = $this->get('serializer');
foreach ($search as $key => $value) {
$search[$key] = $serializer->serialize($value, "json");
}
$reponse = new JsonResponse($search);
return $reponse;
this is what i have in my twig ( i examine it with Firebug ):
i have a to display at least something but sometimes i have undefined or nothing ... this my javascript function
$(document).ready(function () {
var dataString = $("form").serialize();
var typerequest = $("form").find('input[name="typerequest"]').val();
$('#filtreperseance').ajaxForm({
type: "POST",
url: Routing.generate('myroute'),
data: dataString,
success: function (response) {
$.each(response, function (cle, valeur) {
$("#test").html(valeur);
});
}
});
});
EDIT 1 : Console.log
EDIT 2 :
I'd try to cut down the problem. First make sure, the JSON is valid and looks the way you expect. Don't use jQuery at this point. Call the symfony controller in your browser directly. Then check the json. http://jsonviewer.stack.hu might be of use.
Once you verfified that the JSON itself is valid and contains what you need, we can look at the jQuery part. Then we'd need the code and the errors you get.
i have done a mistake when i returned the JSOn from Controller . its Ok now

I mess up JSON object, arrays and strings

So i´m, trying send data from php to js.
PHP
$balkTypes[] = $stmt->fetchAll();
echo json_encode($balkTypes);
JS
balkTypesData = {}; //Outside Ajaxcall
success: function(result){
balkTypesData = result;
Console.log(balkTypesData);
}
Console
[[{"id":"3","typ":"Bas 200*600","hojd":"200","bredd":"600","rec":"","viktM":"135"},{"id":"2","typ":"Bas 240*600","hojd":"240","bredd":"600","rec":"","viktM":"160"},{"id":"5","typ":"Isol\u00e4tt 240*600","hojd":"240","bredd":"600","rec":"","viktM":"105"},{"id":"4","typ":"Kontur 240*600","hojd":"240","bredd":"600","rec":"","viktM":"105"},{"id":"6","typ":"Passbit","hojd":"0","bredd":"0","rec":"","viktM":"0"}]]
Now, i´d like to search my Json object?!
I´d like to find "viktM" for "typ:Bas 200*600"
//Get balkType weight/m
var searchField = "typ";
var searchVal = "Bas 200*600";
for (var i=0 ; i < balkTypesData.length ; i++){
if (balkTypesData[i][searchField] == searchVal) {
weigth = balkTypesData[i]['viktM'];
console.log(weigth);
}
}
First of all, it seams that i cannot use .lengton "balkTypsData". it gives me 410 hits. Must be all characters?
Second, i cannot find how to access part of my object.
If i use: console.log(balkTypesData[i][searchField]);
I get: "Undefined"
I have also tried to remove the "[i].
So what am i missing?
Be gentle i´m still learning.
Take a look at $.parseJSON() (jQuery) or JSON.parse() (vanilla):
With jQuery
success: function(result){
balkTypesData = $.parseJSON(result);
console.log(balkTypesData);
console.log(balkTypesData[i][searchField]);
}
Without jQuery
success: function(result){
balkTypesData = JSON.parse(result);
console.log(balkTypesData);
console.log(balkTypesData[i][searchField]);
}
When you receive the data from your AJAX request it's not JSON, just a string.
The length result that you're getting is the length of the string, not the amount of elements within the array.
Furthermore you're setting $balkTypes[] which means that you're trying to add 1 entry in the array of $balkTypes however $stmt->fetchAll(); also returns an array so you now have a nested array which is not needed.
In your PHP file change
$balkTypes[] = $stmt->fetchAll()
to
$balkTypes = $stmt->fetchAll()
this will make sure that when you fetch your data it will be an array containing all objects instead of an array containing the array of objects.
Then in your JS, instead of trying to directly read from the string, use JSON.parse() to convert the json string into a collection of JS objects/integers/arrays/strings/booleans
e.g.
success: function(result) {
balkTypesData = JSON.parse(result);
console.log(balkTypesData);
}
EDIT
As pointed out by Armen you could also set the dataType: 'json' in the AJAX request, when the AJAX request returns it will automatically do the JSON.parse() so you can just directly console.log(result); to see the output.
Within the console.log you should now see the nested structure instead of just the string.
From here on your loop which checks the values seems correct and I would not change it unless it tells you that something is wrong.
Docs: JSON.parse();
Set in your jQuery $.ajax request additional attribute dataType: 'json'
$.ajax({
type: "POST",
dataType: "json",
url: url,
data: { params },
success: function( response )
{
// Your data will be already json no need to parse it
console.log(response);
}
});
You are encoding a JSON on the PHP side. You are not decoding it on the JS side.
You should look at JSON.parse()

Post JSON to PHP in AJAX for MongoDB Querying

I am constructing a Javascript object. I am using the id of user who is logged in (from a session variable) and storing it as an attribute with AJAX.
I wanted to post the resulting object as JSON via AJAX to a PHP file which then inserts the document into a MongoDB database:
var numpages=$('.page').length;
var book=new Object();
$.ajax({
type: 'json',
url: '../scripts/getUser.php',
method: 'GET',
success: function(data){
var user=JSON.parse(data);
book.user=data.username;
}
});
book.title=title;
book.pages=new Array();
var page;
var link;
for (var i=0;i<numpages;i++){
var numlinks=$('#p'+i+' .link').length;
page=new Object();
page.text=$('#p'+i+' .textarea').text();
page.links=new Array();
for (var j=0;j<numlinks;j++){
link=new Object();
link.text=$('#p'+i+'l'+j+' .linktext').text();
link.locale=$('#p'+i+'l'+j+' .locale').text();
page.links.push(link);
}
book.pages.push(page);
}
$.ajax({
data: JSON.stringify(book),
url: '../scripts/addstory.php',
method: 'POST',
success: function(msg) {
//var story=JSON.parse(msg);
console.log(msg);
//alert(msg);
}
});
}
Here is the PHP:
<?php
$dbhost = 'localhost';
$dbname = 'story';
$m = new MongoClient("mongodb://$dbhost");
$db = $m->$dbname;
$collection = $db->stories;
$story=$_POST['json'];
if (isset($story)){
$collection->save($story);
}
?>
The document is being inserted into the database but I get this:
Notice: Undefined index: json
You have two problem, first being that ajax is async unless you specify the async flag to false which you probably don't want to do so:
book.owner=data.username;
Is likely to actually be empty when you come to JSON encode in the second ajax call.
To solve this you can use JQuery promises like so:
$.get().done(function(data){
/// extra processing
}).then(function(){ $.get() // etc });
This will ensure that one Ajax calls runs after the other.
As for the missing index you don't actually need to stringify your data at all instead you can just do:
$.get('some_url', {book: book})
And JQuery will actually serialize it for you ready for PHP.
This
JSON.stringify(book),
creates an object something like:
{"title":"East of Eden","author":"John Steinbeck"}
better completely remove the JSON.stringify() bit and just pass the book variable
And it in the ajax call it should be type: "POST", not method: "POST"
So in your php script you can do
$_POST['title'];
$_POST['author'];
Hope that helps
If you want to work exclusively with JSON, you should set your content-type header to application/json and then read that content from PHP raw input:
The javascript:
$.ajax({
data: JSON.stringify(book),
url: '../scripts/addstory.php',
method: 'POST',
contentType: 'application/json',
success: function(msg) {
alert(msg);
}
});
The PHP:
$story = file_get_contents('php://input');
So really you just need to add one line of code and change another.
The reason $_POST['json'] was not being populated is that nowhere did you define a query string (or let jQuery define for you) that has a key json.
You could have, for example done something like this:
data: {'json': JSON.stringify(book)}
And that would have populated $POST['json'], but again if all you are looking to do is pass around a JSON string and directly insert it into Mongo, there is no reason to use form-encoding for this at all, just work with raw POST data.
Note also the problem mentioned by #Sammaye about needing to properly work with event delegation.

Categories

Resources