Send an associative array from Laravel function to CasperJS - php

I am new to CasperJS and laravel. I need a help, I want to send an associative array(all the contents in that array at once) to CasperJS from a function, currently i am encoding it using the JSON_encode as the CasperJS script doesn't take array. The following piece of code encodes the array and sends as one string. On the other side i am fetching the string in casperJS script and unable to decode the JSON. The format of json changes on reaching the casperJS script.
$array = array
(
[1] => http://www.xxxx.com,
[2] => http://www.yyyy.com,
[3] => http://www.zzzz.com
);
$data_fetch=json_encode($array);
$casperjs = new CasperJS;
$result = $casperjs->execute($this->script2,$data_fetch);
print_r($data_fetch);
which outputs after encoding the array
{"1":"http://www.xxxx.com","2":"http://www.yyyy.com","3":"http://www.zzzz.com"}
The CasperJS script
var system = require('system');
var casper = require('casper').create({
verbose: true,
logLevel: 'error',
pageSettings: {
loadImages: false,
loadPlugins: false
}
});
var data = system.args[4];
casper.start(function() {
var decode=json.stringify(data);
});
casper.run();
when you check the input in 'data' variable using console.log it is
{1:http://www.xxxx.com,2:http://www.yyyy.com,3:http://www.zzzz.com}
which is different from the json.encode it is omitting double quotes, because of different formats i am unable to decode the content.
Can anyone help why is it doing that way?? Any solution for this?? OR is there any other better way to pass an array to casper and return back the result as an array.

Related

How to encoding multiple json object in php

I am working on a project where a user has to fill up a form and can upload multiple documents. Everytime he uploads a document, he calls a webservice which returns a JSON file with id and type.
Since he can upload multiple documents so the webservice is called many times. When he completes his form and submits it, I need to send a json with the multiple id and type that I have received previously from JSON.
This is the JSON that I need to send to the server when the user finally submits the form:
"docls":[
{
"id":"123",
"ty":"101",
},
{
"id":"456",
"ty":"102",
}
],
How do I encode the JSON when I dont know how many files the user has uploaded?
P.S. I have already been able to get the response from the first JSON in the form of 'id' and 'ty'. Do I need to store it in array? If yes then how do I decode it into json?
$json_string = array(
'docls' => array (
'id' => '123',
'ty' => '101',
),
);
You're going to want to build the array with php then json_encode it when your ready to send it back to the server
// Create an array to hold the documents
$documents = [];
// push each document into the array as the user does their thing
$documents[$id] = $ty;
// When the user is finished
$json = json_encode($documents);
Well, you just have to use json_decode to convert json string you receive to php array, and json_encode to convert convert php array to json formatted string.
Check this example:
<?php
$json = '{"foo-bar": 12345}';
$obj = json_decode($json);
print $obj->{'foo-bar'}; // 12345
?>
more information here

Can't get it working: jQuery AJAX array to PHP

I've been experiencing a lot of trouble with my issue all afternoon. Endless searches on Google and SO haven't helped me unfortunately.
The issue
I need to send an array to a PHP script using jQuery AJAX every 30 seconds. After constructing the array and sending it to the PHP file I seemingly get stuck. I can't seem to properly decode the array, it gives me null when I look at my console.
The scripts
This is what I have so far. I am running jQuery 1.11.1 and PHP version 5.3.28 by the way.
The jQuery/Ajax part
$(document).ready(function(){
$.ajaxSetup({cache: false});
var interval = 30000;
// var ids = ['1','2','3'];
var ids = []; // This creates an array like this: ['1','2','3']
$(".player").each(function() {
ids.push(this.id);
});
setInterval(function() {
$.ajax({
type: "POST",
url: "includes/fetchstatus.php",
data: {"players" : ids},
dataType: "json",
success: function(data) {
console.log(data);
}
});
}, interval);
});
The PHP part (fetchstatus.php)
if (isset($_POST["players"])) {
$data = json_decode($_POST["players"], true);
header('Content-Type: application/json');
echo json_encode($data);
}
What I'd like
After decoding the JSON array I'd like to foreach loop it in order to get specific information from the rows in the database belonging to a certain id. In my case the rows 1, 2 and 3.
But I don't know if the decoded array is actually ready for looping. My experience with the console is minimal and I have no idea how to check if it's okay.
All the information belonging to the rows with those id's are then bundled into a new array, json encoded and then sent back in a success callback. Elements in the DOM are then altered using the information sent in this array.
Could someone tell me what exactly I am doing wrong/missing?
Perhaps the answer is easier than I think but I can't seem to find out myself.
Best regards,
Peter
The jQuery.ajax option dataType is just for the servers answer. What type of anser are you expexting from 'fetchstatus.php'. And it's right, it's json. But what you send to this file via post method is not json.
You don't have to json_decode the $_POST data. Try outputting the POST data with var_dump($_POST).
And what happens if 'players' is not given as parameter? Then no JSON is returning. Change your 'fetchstatus.php' like this:
$returningData = array(); // or 'false'
$data = #$_POST['players']; // # supresses PHP notices if key 'players' is not defined
if (!empty($data) && is_array($data))
{
var_dump($data); // dump the whole 'players' array
foreach($data as $key => $value)
{
var_dump($value); // dump only one player id per iteration
// do something with your database
}
$returningData = $data;
}
header('Content-Type: application/json');
echo json_encode($returningData);
Using JSON:
You can simply use your returning JSON data in jQuery, e.g. like this:
// replace ["1", "2", "3"] with the 'data' variable
jQuery.each(["1", "2", "3"], function( index, value ) {
console.log( index + ": " + value );
});
And if you fill your $data variable on PHP side, use your player id as array key and an array with additional data as value e.g. this following structure:
$data = array(
1 => array(
// data from DB for player with ID 1
),
2 => array(
// data from DB for player with ID 2
),
...
);
// [...]
echo json_decode($data);
What I suspect is that the data posted is not in the proper JSON format. You need to use JSON.stringify() to encode an array in javascript. Here is an example of building JSON.
In JS you can use console.log('something'); to see the output in browser console window. To see posted data in php you can do echo '<pre>'; print_r($someArrayOrObjectOrAnything); die();.
print_r prints human-readable information about a variable
So in your case use echo '<pre>'; print_r($_POST); to see if something is actually posted or not.

Assigning identifier/name to JSON object in PHP

I'm grabbing data from a mysql database and encoding a JSON object with PHP to use in JS.
On the PHP end, I did this
while($row = mysql_fetch_array($result))
{
$jmarkers = array(
'id'=> $row['id'],
'lat' => $row['lat'],
'lng' => $row['lng'],
etc...
);
array_push($json, $jmarkers);
}
$jsonstring = json_encode($json);
echo $jsonstring;
I can access the data in JS using jQuery, and I made an array to save the JSON data:
$.getJSON("getjson.php", function(data)
{
myMarkers = data;
console.log(myMarkers);
});
I'd planned to access the data in the myMarkers array inside loop, with a statement like this:
var tempLat = myMarkers.jmarkers[i].lat;
The problem is my JSON objects aren't called jmarkers or anything else, they have this generic name "Object" when I print them to the console:
Object { id="2", lat="40.6512", lng="-73.9691", more...},
So I'm not sure how to point to them in my JS array. I looked the PHP JSON encode function and I can't see where to set or change the object name. Any suggestions? Thank you!
That's to be expected. JSON is essentially the right-hand-side of an assignment operation:
var x = {'foo':'bar'};
^^^^^^^^^^^^^---- JSON
The x part is not included, since that's simply the name of the object. If you want your jmarkers text included, it'll have to be part of the data structure you're going to encode:
$arr = array(
'jmarkers' => array(...your data here...);
);
But all this does is add another layer to your data structure for no useful reason.
$jmarkers is simply the identifier on the PHP side for the JSON object. When it gets passed, it converts the array value into a JSON-encoded string and therefore loses the identifier as a result.
In your PHP code at the moment, array_push($json, $jmarkers) is appending an array to your current $json array. You are therefore instancing a two-dimensional array, which will not be retrievable by the jmarkers identifier in your Javascript code. Simply retrieve the data using myMarkers[i] instead.
You... don't. The whole thing is an object. You only need to refer to the elements within.
alert(myMarkers.id);

Sending an array to server side using $.getJSON

I am using $.getJSON() to pass some data to the server side (PHP, Codeigniter) and using the return data to do some work. The data that I am sending over to the server is in the form of an array.
Problem: When an associative array is sent to the server, no result is received on server side. However, if a normal array with numerical indexes is sent, the data is received on server side. How can I send an array of data over to the server?
JS Code (Not Working)
boundary_encoded[0]['testA'] = 'test';
boundary_encoded[0]['testB'] = 'test1';
$.getJSON('./boundary_encoded_insert_into_db_ajax.php',
{boundary_encoded: boundary_encoded},
function(json) {
console.log(json);
});
JS Code (Works)
boundary_encoded[0][0] = 'test0';
boundary_encoded[0][1] = 'test1';
$.getJSON('./boundary_encoded_insert_into_db_ajax.php',
{boundary_encoded: boundary_encoded},
function(json) {
console.log(json);
});
PHP Code
$boundary_encoded = $_GET['boundary_encoded'];
print_r($_GET);
Error Msg
<b>Notice</b>: Undefined index: boundary_encoded in <b>C:\xampp\htdocs\test\boundary\boundary_encoded_insert_into_db_ajax.php</b> on line <b>11</b><br />
Array
(
)
Working Result
Array
(
[boundary_encoded] => Array
(
[0] => Array
(
[0] => test
[1] => test1
)
)
)
The reason this isn't working is because JavaScript does not support associative arrays. This assignment:
boundary_encoded[0]['testA'] = 'test';
appears to work in JS because you can assign a new property to any object, arrays included. However they won't be enumerated in a for loop.
Instead, you must use an object literal:
boundary_encoded[0] = {'testA':'test'};
You can then use JSON.stringify to convert boundary_encoded to a JSON string, send that to the server, and use PHP's json_decode() function to convert the string back into an array of objects.
I would suggest using converting the arrays to JSON. If you can't do so in PHP (using the json_encode function), here are a couple of JS equivalents:
http://phpjs.org/functions/json_encode:457
http://www.openjs.com/scripts/data/json_encode.php
In your getJSON call, use
{boundary_encoded: JSON.stringify(boundary_encoded)},
instead of
{boundary_encoded: boundary_encoded},

How to get the POST values from serializeArray in PHP?

I am trying this new method I've seen serializeArray().
//with ajax
var data = $("#form :input").serializeArray();
post_var = {'action': 'process', 'data': data };
$.ajax({.....etc
So I get these key value pairs, but how do I access them with PHP?
I thought I needed to do this, but it won't work:
// in PHP script
$data = json_decode($_POST['data'], true);
var_dump($data);// will return NULL?
Thanks, Richard
Like Gumbo suggested, you are likely not processing the return value of json_decode.
Try
$data = json_decode($_POST['data'], true);
var_dump($data);
If $data does not contain the expected data, then var_dump($_POST); to see what the Ajax call did post to your script. Might be you are trying to access the JSON from the wrong key.
EDIT
Actually, you should make sure that you are really sending JSON in the first place :)
The jQuery docs for serialize state The .serializeArray() method creates a JavaScript array of objects, ready to be encoded as a JSON string. Ready to be encoded is not JSON. Apparently, there is no Object2JSON function in jQuery so either use https://github.com/douglascrockford/JSON-js/blob/master/json2.js as a 3rd party lib or use http://api.jquery.com/serialize/ instead.
The OP could have actually still used serializeArray() instead of just serialize() by making the following changes:
//JS
var data = $("#form :input").serializeArray();
data = JSON.stringify(data);
post_var = {'action': 'process', 'data': data };
$.ajax({.....etc
// PHP
$data = json_decode(stripslashes($_POST['data']),true);
print_r($data); // this will print out the post data as an associative array
its possible by using the serialize array and json_decode()
// js
var dats = JSON.stringify($(this).serializeArray());
data: { values : dats } // ajax call
//PHP
$value = (json_decode(stripslashes($_REQUEST['values']), true));
the values are received as an array
each value can be retrieved using $value[0]['value'] each html component name is given as $value[0]['name']
print_r($value) //gives the following result
Array ( [0] => Array ( [name] => name [value] => Test ) [1] => Array ( [name] => exhibitor_id [value] => 36 ) [2] => Array ( [name] => email [value] => test#gmail.com ) [3] => Array ( [name] => phone [value] => 048028 ) [4] => Array ( [name] => titles [value] => Enquiry ) [5] => Array ( [name] => text [value] => test ) )
The JSON structure returned is not a string. You must use a plugin or third-party library to "stringify" it. See this for more info:
http://www.tutorialspoint.com/jquery/ajax-serializearray.htm
I have a very similar situation to this and I believe that Ty W has the correct answer. I'll include an example of my code, just in case there are enough differences to change the result, but it seems as though you can just use the posted values as you normally would in php.
// Javascript
$('#form-name').submit(function(evt){
var data = $(this).serializeArray();
$.ajax({ ...etc...
// PHP
echo $_POST['fieldName'];
This is a really simplified example, but I think the key point is that you don't want to use the json_decode() method as it probably produces unwanted output.
the javascript doesn't change the way that the values get posted does it? Shouldn't you be able to access the values via PHP as usual through $_POST['name_of_input_goes_here']
edit: you could always dump the contents of $_POST to see what you're receiving from the javascript form submission using print_r($_POST). That would give you some idea about what you'd need to do in PHP to access the data you need.
Maybe it will help those who are looking :)
You send data like this:
$.ajax({
url: 'url_name',
data: {
form_data: $('#form').serialize(),
},
dataType: 'json',
method: 'POST'
})
console.log($('#form').serialize()) //'f_ctrType=5&f_status=2&f_createdAt=2022/02/24&f_participants=1700'
Then on the server side use parse_str( $_POST['form_data'], $res).
Then the variable $res will contain the following:
Array
(
[f_ctrType] => 5
[f_status] => 2
[f_createdAt] => '2022/02/24'
[f_participants] => 1700
)
You can use this function in php to reverse serializeArray().
<?php
function serializeToArray($data){
foreach ($data as $d) {
if( substr($d["name"], -1) == "]" ){
$d["name"] = explode("[", str_replace("]", "", $d["name"]));
switch (sizeof($d["name"])) {
case 2:
$a[$d["name"][0]][$d["name"][1]] = $d["value"];
break;
case 3:
$a[$d["name"][0]][$d["name"][1]][$d["name"][2]] = $d["value"];
break;
case 4:
$a[$d["name"][0]][$d["name"][1]][$d["name"][2]][$d["name"][3]] = $d["value"];
break;
}
}else{
$a[$d["name"]] = $d["value"];
} // if
} // foreach
return $a;
}
?>

Categories