javascript array to string JSON - php

First of all i am new to php and javascript
I have a web form where users can add multiple contacts ans send to ther server.
Due to some reasons i cant use the normal html elements to store the values ,so i am using an array to store values.
//init array
var contacts = new Array(); //contact array
var tempArray = new Array(); //temp array to store current contacts
//getting the contact info and setting to a temp array
tempArray = {
name:"username",
age:12,
sex:false
};
//push the content to the `contacts` array
contacts.push(tempArray);
I added many contacts to the contacts array and now i need to submit the array to server.
Problem
I am using Codeignitor and Malsup FORM plugin.
as per malsup i can configure the data option like this
var options = {
dataType:'json', //type of data
data:[contactArray:contacts], //additional parm
};
and on ajaxSubmit option i can give this option as a parm.
when i do this i am getting the following error
uncaught exception: [Exception... "Component returned failure code: 0x80460001 (NS_ERROR_CANNOT_CONVERT_DATA) [nsIDOMFormData.append]" nsresult: "0x80460001 (NS_ERROR_CANNOT_CONVERT_DATA)" location: "JS frame :: /js/form.js :: fileUploadXhr :: line 224" data: no]
temp/jquery.min.js
Line 4
IT WORKS with $.POST in jQuery.
so i tried the JSON.stingify() to convert the data to string.
but on server i am getting like this
'contactArray' => string '[{"name":"username","sex":"12","sex":"false"}]'
If i used the json_decode then i cant use the form validation.
I want to use the FORM VALIDATION LIBRARY IN CODEIGNITOR.
CI supports validation of array of elements.
so
if i get something like name[],age[],sex[] then i can validate easily.
Please help me to solve the problems or give me suggestions.
Thank you.

This code does not create an array:
tempArray = {
name:"username",
age:12,
sex:false
};
It creates an object (completely overwriting the blank array you assigned to tempArray earlier).
if i get something like name[],age[],sex[] then i can validate easily.
If you want, you can create post data that would look like that, as a prep step prior to sending in your data. It's fairly easy::
function prepContacts(contacts) {
var result = []; // Build up string in array, we'll join at the end
var nameKey, ageKey, sexKey;
// I've put [] in these because you use PHP
nameKey = encodeURIComponent("name[]");
ageKey = encodeURIComponent("age[]");
sexKey = encodeURIComponent("sex[]");
for (index = 0; index < contacts.length; ++index) {
contact = contacts[index];
result.push(nameKey + "=" + encodeURIComponent(contact.name));
result.push(ageKey + "=" + encodeURIComponent(contact.age));
result.push(sexKey + "=" + encodeURIComponent(contact.sex));
}
return result.join("&");
}
Then post that via $.ajax:
$.ajax({
url: "/path/to/resource",
type: "POST",
data: prepContacts(contacts),
success: function(response) {
// POST worked, but you have to check response for whether
// it worked at the logic level
},
error: function() {
// POST failed
}
});

Related

Trying to build a json object to send to laravel. Problems with key name

I am trying to make a key and value array to send to my laravel backend.
this is my current code
$http.post('../survey/'+$scope.clientID+'/getSurvey', {client: $scope.clientID }).
success(function(data, status, headers, config) {
console.log(data);
$scope.survey_id = data[0];
$scope.questions = data;
//$scope.dLength = data.length;
$scope.dLength = 5;
console.log($scope.questions);
// When an answer button is clicked
$scope.clicky = function(value) {
// Add a class to hide the div cntainng the question
$scope.class = "hideit";
//Set a timeout function so the question can fadeOut before we proces anything
var callAtTimeout = function() {
// Check to see if this is the last question
if($scope.qid >= $scope.dLength -1){
// All questions have been answered. AJAX the data back to Laravel
alert("complete")
$http.post('../survey/'+$scope.survey_id.survey_id+'/submitSurvey', {data: angular.fromJson($scope.answers)}).
success(function(data, status, headers, config) {
console.log(data);
})
//})
//console.log($scope.answers)
}else{
//Build up the Array of answeres
// Get Question name - this will be the key
var questionName = $scope.questions[$scope.qid].name;
// This is the value
var questionAnswer = value
//build the aray element
var line = { questionName : value };
//Push it to the array
$scope.answers.push({questionName: questionAnswer});
//console.log($scope.answers)
//add to the count variable
$scope.qid += 1;
// Animate the question div back up to display the next question
$scope.class = "showit";
}
}
$timeout(callAtTimeout, 1000)
}
}).
When I look at the data I am building it is showing questionname as the key instead of the data that is in the variable question name.
When I alert the variable question name it shows the correct data, but the array is just showing the key as "questionname", Am I building the array wrong, if so how should I be building it?
If I understand you right, you may try to build it like that:
var question = {};
question[questionName] = questionAnswer;
$scope.answers.push(question);
Also, it looks like with ECMAScript 6 it will be possible to achieve the same thing in a slightly prettier manner:
$scope.answers.push({ [questionName]: questionAnswer});
UPD:
According to the comments, you don't need to create an array, but build an object instead. It might be something like this:
$scope.answers = {};
// loop through the questions:
$scope.answers[questionName] = questionAnswer;
After that you'll be able to access answers like this:
var answer = $scope.answers["MyQuestionName"];

calling php and javascript functions with one button

This is what I'm trying to achieve, but my Googling hasn't helped:
I have a button that adds a new row to a table dynamically. I also add a select component to a cell with the same action all in javascript. I'd like for that select component to populate with values from a sql select statement. Of course I don't want to define the connection to the DB in the JavaScript. So I was wondering if there was a way I could call a PHP function to retrieve the values then store it in variable within JavaScript.
PS I understand that PHP is server side as opposed to JS. But surely this is possible.
here's a simple implementation of such a thing using jQuery's ajax and php.
html
<select data-source-url="/category/list"></select>
javascript using jQuery
$("select[data-source-url]").each(function(){
var url = $(this).attr("data-source-url");
var el = $(this);
$.get(url, function(data){
for (i=0;i<data.length;i++){
el.append("<option>" + data[i] + "</option>");
}
},"json");
});
category/list endpoint (a php script)
$list = array();
$list[0] = "category 1";
$list[1] = "category 2";
$list[2] = "category 3";
$list[3] = "category 4";
$list[4] = "category 5";
echo json_encode($list);
a little explanation: what happens is a request being made via the JavaScript client to a php script, which returns an array of values in JSON (which is basically a javascript data-structure), those values are added to the select box dynamically.
Please note that on initial load of the page, the select box will be empty.
yes ofcourse you can. for storing s php variable in a js ariable you can do like this.
before storing it into js variable store the required value in your php variable
var value = '<?php echo $value;?>';
Javascript cannot connect directly to a database.
You want AJAX. A basic flow for this functionality looks like this.
Create a PHP script that connects to the database and gets the options for your select element (let's call it options.php). This script should fetch the options from the database and output them as a JSON array.
In your javascript, you would create an ajax request to options.php. With the JSON data returned from that script, you would loop over each element and create and append a corresponding option element to the dom inside of your select element.
Also consider using jQuery. It greatly simplifies ajax and provides a cross-browser solution.
Option 1
Pass a php array with all possible values to the client side using something like this on the client side:
var opt_values = [<?php echo $php_values; ?>]; //javascript array
or
var opt_values = <?php echo json_encode($php_values); ?>; //json object
Option 2
Another way is making an ajax request. Write a php function that return a JSON object and then you can manipulate the result using jQuery ajax method:
PHP function:
$json = array();
$result = mysqli_query ($connection, $query);
while($row = mysqli_fetch_array ($result))
{
$bus = array(
'id' => $row['id'],
'text' => $row['name']
);
array_push($json, $bus);
}
return = json_encode($json)
Jquery
$('#button-id').click(function(){
//adds a new row to a table dynamically
$.ajax({
type: "get",
dataType: "json",
url: "/get_values.php",
success: function (response) {
var $el = $("#myselect"); //get the select
$el.empty(); // remove old options
//Append the new values
$.each(response, function(key, value) {
$el.append($("<option></option>")
.attr("value", value.id).text(value.text));
});
}
});
});
Just thought i'd put it out there since w3schools is my friend and i kinda follow what they're saying in this post.
W3Schools PHP & AJAX communication

How to create multidimensial arrays with PHP and access with jQuery?

So I have got to a stage in my website where I need to pack a lot of information into a single json array like object, so in order to do this I need to pack a list of array information under a certain key name, then another set of data under another key name.
So for example:
$array = array();
foreach(action goes here)
{
$array['data1'] = array('information' => data, 'more_information' => more_data)
}
$array['data2'] = array("more data");
This basically illustrates what I am trying to do, I am able to partially do this, however naming the key for the new data set only replaces each data, instead of adding into it in the foreach loops.
Now if this part isn't too confusing, I need some help with this. Then in addition to this, once this is sorted out, I need to be able to use the data in my jQuery response, so I need to be able to access each set of data something like: json.data1[i++].data, which would ideally return "more_information".
You need an incremental number in that loop and make the results available as a json object...
$array = array();
$i = 0;
foreach(action goes here)
{
$array['data'.$i] = array('information' => data, 'more_information' => more_data)
$i++;
}
$array['data2'] = array("more data");
$data = json_encode($array);
Then in php you might set a js var like so:
<script type="text/javascript">
var data = <?php echo $data; ?>;
</script>
which could then be accessed in js easily:
alert(data.data1.information);
If I understand your question correctly you expect to get this object as a response to something? Like a jQuery .ajax call?
http://api.jquery.com/jQuery.ajax/
This link illustrates how to use it pretty clearly. You would want to make sure to specify dataType = "json" and then place your data handling in the success call:
$.ajax({
url: 'some url string',
type: "GET",
dataType: "json",
success: function(data)
{
$.each(data, function(i, v){
console.log(data[i]);
});
},
error: function()
{
//error handling
}
});
This is relatively untested, but the concept is what I am trying to convey. You basically make your multi-dimensional array in php and json_encode it. Either of these methods will allow you to parse the json.

How to unserialize a serialized array sent to the server using GET method with a jQuery Ajax call?

I'm trying to deserialize an array from an URL I've sent from a JQuery Ajax call to a PHP script in the server.
What I have done
I've been sending variables with values to the server successfully with jQuery Ajax this way:
// A simple text from an HTML element:
var price = $("#price option:selected").val();
// Yet another simple text:
var term1 = $('#term1').val();
Then I prepare the data to be sent via Ajax this way:
var data = 'price=' + price + '&term1=' + term1;
//if I alert it, I get this: price=priceString&term1=termString
And send it with jQuery Ajax like this:
$.ajax({
url: "script.php",
type: "GET",
data: data,
cache: false,
dataType:'html',
success: function (html) {
// Do something successful
}
});
Then I get it in the server this way:
$price = (isset($_GET['price'])) ? $_GET['price'] : null;
$term1 = (isset($_GET['term1'])) ? $_GET['term1'] : null;
And I'm able to use my variables easily as I need. However, I need to do this with an array.
Main question
Reading a lot, I've managed to learn the professional way to send an array to the server: serialize it! I've learnt this way to do it with jQuery:
var array_selected = [];
// This is used to get all options in a listbox, no problems here:
$('#SelectIt option:not(:selected), #SelectIt option:selected').each(function() {
array_selected.push({ name: $(this).val(), value: $(this).html().substring($(this).html().indexOf(' '))});
});
var array_serialized = jQuery.param(array_selected);
// If I alert this I get my array serialized successfully with in the form of number=string:
//Ex. 123=stringOne&321=StringTwo
This seems to be right. I add this to the data as before:
var data = 'price=' + price + '&' + array_selected + '&term1=' + term1;
//if I alert it, I get this: price=priceString&term1=termString&123=stringOne&321=StringTwo
How do I reconstruct (unserialize) my array in the server? I've tried the same as before:
$array_serialized = (isset($_GET['array_serialized'])) ? $_GET['array_serialized'] : null;
with no success! Any ideas why? How can I get my serialized array passed this way in the server as another array which PHP can handle so I can use it?
Or am I complicating my life myself needlessly? All I want is to send an array to the server.
If you name a variable with [] in the end of it, it will create an array out of the values passed with that name.
For example, http://www.example.com/?data[]=hello&data[]=world&data[]=test, will result in the array $_GET["data"] == array('hello', 'world', 'test'); created in PHP.
In the same way, you can create an associative array in PHP: http://www.example.com/?data[first]=foo&data[second]=bar will result in $_GET["data"] == array("first" => "foo", "second" => "bar");
BTW, you might be interested in using jQuery's .serialize() or .serializeArray(), if those fit your client side serializing needs.
I'm not too knowledgeable with PHP, but I think you may have overlooked something pretty simple, <?--php unserialize($string) ?>.

Javascript get form value in URL without jQuery

If data is submitted via POST through the classic HTML form method is it possible to access those values using standard Javascript without libraries? How would this be done?
Edit for clarity: The variables have been posted. I am trying to access those values via javascript.
Thinking outside the box: (A hack that should never see the light of day)
For this example the posted variable is "a":
var val=document.URL;
var start;
start = val.search(/a=/);
var end;
end = val.search(/&/);
var thispos = val.substring(start+2,end);
document.URL returns the url of the current site.
val.search returns the position of the first occurrence of the regular expression in
the parameter field.
substring the two and...
thispos now contains the posted variable.
Brutal but functional. Is this too terrible to be an answer?
use:
var myField = document.getElementById('myFieldId');
then myField.value will contain the value.
If you have submitted the page, then you have to get the form data using PHP.
Here is a tutorial that should help: http://www.phpf1.com/tutorial/php-form.html
But if you decide to test jQuery, you can use this:
jQuery('#submit').live('click', function()
{
var form_data = jQuery("#data_form").serialize();
//Save data
jQuery.ajax({
url: siteURL +"/path/to/php/file/jquery.php",
data: {formData : form_data,
success: (function(data) {
//data is whatever you return from jquery.php
//I use json for return data
alert('Data has been saved');
}),
dataType: 'json'
});
After a post, the data is send to the server, javascript cant do anything with that since its client side. What you can do is pre-check with document.getElementById('formid') and use those values in the form. After validating or doing what you want to do, end with form.submit() to really send it to the server.
function getUrlInfo() {
var data = window.location.search.substring(1).split("&");
//returns an array of strings containing the params and their values
// data = [ "param=value","param=value","param=value"]
var params1Array = data[0].substring(0).split("=");
//Splits the first string element at the "=" symbol and
//returns an array with the param and value
//param1Array = ["param","value"]
var param1Value = param1Array[1].replace("+", " ");
//Gets the value from the second element in the param1Array
//Replaces the spaces, if any, in the second element,
//which is the value of the url param
var param2Array = data[1].substring(0).split("=");
//Repeat steps for the second param element,in the url params data array
var param2Value= param2Array[1].replace("+", " ");
return {
param1Value,
param2Value
}
};
The submitted data (either POST or GET) is proccesed on the server side. Javascript runs on the client-side so you can't access the variables from the page receiving the form request.
But you can access them before the post using the input field id (specially to check the input values before sending them).

Categories