I have the following code to pass a Javascript array to PHP using ajax :
in HTML :
echo "<input type=\"hidden\" id= \"que_id\" name= \"que_id[]\" value=".$questions['que_id'].">";
This is inside a loop.
in Javascript :
var que_id_array = new Array();
$('input[name="que_id[]"]').each(function(){
que_id_array.push($(this).val());
});
AJAX Call :
$.ajax({
type:"POST",
url: 'questionmastermodify.php',
data: { que_id:que_id_array},
success: function(data) {
$('.my_update_panel').html(data);
$('#overlay').fadeOut();
}
});
in PHP :
$que_id = $_REQUEST['que_id'];
echo count($que_id);
The count displays 1 and not the size of the array, whereas in Javascript the console shows :
console.log(que_id_array);
output :
["151", "152", "153", "154", "155", "156", "157", "158", "159", "160", "161", "162", "163", "164", "165", "166", "167", "168", "169", "170", "171", "172", "173", "174", "175", "176", "177", "178", "179", "180", "181", "182", "183", "184", "185", "186", "187", "188", "189", "190", "191", "192", "193", "194", "195", "196", "197", "198", "199", "200"]
I am stuck as i need this array in PHP but unable to pass this array from JS to PHP.
Thanks in advance....
Sandy505
I made a quick test with your code... and with a few changes, It work's for me.
Take a look at your code, specially the loop when you create the <input> fields...
And also.. in the loop you have an ID in the <input>... that's not good at all!.. change it for class for example...
As an example, this is what I tried:
Main PHP
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
<script src="http://code.jquery.com/jquery-1.9.0.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function() {
$('#theForm').submit(function(event) {
event.preventDefault();
createTheArray();
});
});
function createTheArray(){
// Create the Array
var que_id_array = new Array();
$('input[name="que_id[]"]').each(function(){
que_id_array.push($(this).val());
});
console.log(que_id_array); // output ["151", "152", "153"]
sendTheForm(que_id_array); // do the ajax call
}
function sendTheForm(que_id_array){
// AJAX Call
$.ajax({
type:"POST",
url: 'questionmastermodify.php',
data: { que_id:que_id_array},
success: function(data) {
$('.my_update_panel').html(data);
}
});
}
</script>
</head>
<body>
<form id="theForm">
<?php
// your original Array
$arrayName = array(
array('que_id' => '151'),
array('que_id' => '152'),
array('que_id' => '153')
);
foreach ($arrayName as $key => $questions) {
echo "<input type='text' class='que_id' name='que_id[]' value='{$questions['que_id']}'>";
}
?>
<input type="submit" value="send" />
</form>
<div class="my_update_panel">result will be loaded here...</div>
</body>
</html>
And your questionmastermodify.php PHP file
<?PHP
$que_id = $_REQUEST['que_id'];
echo '<pre>';
print_r($que_id);
echo '</pre>';
?>
Result
After form submit.. the HTML will print out:
<pre>Array
(
[0] => 151
[1] => 152
[2] => 153
)
</pre>
And in the console.log();
["151", "152", "153"]
Give a try and good luck!
You could encode the array into JSON:
data: { que_id: JSON.stringify(que_id_array)},
In the PHP, decode it:
$que_id = json_decode($_REQUEST['que_id']);
echo count($que_id);
The problem has been sorted out :
The culprit was the version of the jquery i was using. I was using jQuery JavaScript Library v1.3.2 - which caused this problem.
Using the latest : jquery-1.9.0.min.js solve the problem.
I am accepting the answer provided by #gmo as it brought me near to the problem solving and also about that helpful tip about not using id attribute in the Loop...
Thanks all...
Related
What is the proper way to access a nested array of JSON data to be used in Handlebars template file?
My code works in the Dev environment of chrome but doesn't work in Prod.
Here's a sample data of my JSON file.
{
"slider-card-1": [{
"card-img-1": "img/guillermo-rico-1368543-unsplash.jpg",
"card-date-1": "May 29 2019",
"card-title-1": "Deeper dive",
"card-description-1": "Deeper dive into your finances",
"btn-text-1": "Watch video",
"btn-link-1": "vid.co",
"section-header-1": "Be Heard"
},
{
"card-img-2": "img/thought-catalog-685332-unsplash.jpg",
"card-date-2": "May 29 2019",
"card-title-2": "Experience-led Agile",
"card-description-2": "Bringing experiences of our core stakeholders...",
"btn-text-2": "Learn more",
"btn-link-2": "#",
"section-header-2": "Arya"
},
{
"card-img-3": "img/thought-catalog-685332.jpg",
"card-date-3": "Febuary 4 2019",
"card-title-3": "Simplifying terminology",
"card-description-3": "It can be confusing to understand terms.",
"btn-text-3": "Read More",
"btn-link-3": "#",
"section-header-3": "Do it"
}]
}
Code for that goes into the html template file:
<script id="newsletter-template" type="text/x-handlebars-template">
<div>
<div>
<img src={{slider-card-1.[0].card-img-1}}>
</div>
<span>{{slider-card-1.[0].card-date-1}}</span>
<div>
{{slider-card-1.[0].section-header-1}}
</div>
<div>
{{slider-card-1.[0].card-title-1}}
</div>
<div>
{{slider-card-1.[0].card-description-1}}
</div>
<a href={{slider-card-1.[0].btn-link-1}}>
{{slider-card-1.[0].btn-text-1}}
</a>
</div>
</script>
Code to compile the template
<script>
var newsletter_method = {
handlerData: function (resJSON) {
var templateSource = $("#newsletter-template").html(),
template = Handlebars.compile(templateSource),
newsletterHTML = template(resJSON);
$("#my-container").html(newsletterHTML);
},
loadNewsletterData: function () {
$.ajax({
url: "./data.json",
method: 'GET',
success: this.handlerData
})
}
};
$(document).ready(function () {
newsletter_method.loadNewsletterData();
});
</script>
Now when the template is compiled, the generated HTML is blank in the browser. Is there a better way to access the nested array of JSON data in Handlebars? How do I do this?
I need to show the entries of the json in a loop.
I'm new in js and angular, and I don't know how to enter a for in the marked place of the code below.
I need to know to do all the code, this just a test for a larger project.
<?php
$estudent[]=array(
"name" => "luis",
"age" => "10");
$estudent[]=array(
"name" => "maria",
"age" => "12");
$objJson=json_encode($estudent);
?>
//here is the js
<script>
var json=eval(<?php echo $objJson; ?>);
//Angularjs and jquery.datatable with ui.bootstrap and ui.utils
var app=angular.module('formvalid', ['ui.bootstrap','ui.utils']);
app.controller('validationCtrl',function($scope){
$scope.data = [
[ //i need to use a loop for show all the studens
json[0].name,
json[0].age,
],
[ //i need to use a loop for show all the studens
json[1].name,
json[1].age,
],
]
$scope.dataTableOpt = {
//custom datatable options
// or load data through ajax call also
"aLengthMenu": [[10, 50, 100,-1], [10, 50, 100,'All']],
};
});
</script>
In my opinion your JSON is valid, try to change format of JSON for something similar to this :
$scope.data = [{
"name": "json[0].name",
"age": "json[0].age"
},
{
"name": "json[1].name",
"age": "json[1].age"
}
]
Then you can easly console or show it
angular.forEach($scope.data, function (value, index) {
console.log($scope.data[index] + ' ' + index);
});
HTML
<ul ng-repeat="json in data">
<li><b>Name: </b> <p>{{json.name}}</p> <b>Age: </b> <p>{{json.age}}</p></li>
</ul>
plunker: http://plnkr.co/edit/s6ix8aEDz0jR3UeXGL6M?p=preview
For this loop you can use:
$scope.data = [];
angular.forEach(json, (item) => {
// here you can get item.age and item.name
$scope.data.push(item);
});
At the end of this loop your $scope.data will have all students in it
This is a zip to the full project QuickLinks.v4
I have been collaborating on a project and we are stuck on an issue, we want all of the icon to have a right click menu that has several options that are unique to each icon. We are almost done but now the icons are not being drawn to the screen. We are only working on the first 5 at the time. This is my first time working with jQuery and I would appreciate any help.
I will now post pieces of the project that I think are relevant.
icon.html
<a target="_blank">
<img class="icons" />
<div class="data">
<div>
<input type="hidden" class="login" />
<input type="hidden" class="username" />
<input type="hidden" class="password" />
</div>
</div>
</a>
icon.js
function buildIcons() {
var icons = [
["https://discordapp.com/", "discord-icon", "icons/discord.png", "social", "Discord",
[
["Main Account", "lela_null", "somepass"],
["Bot Account", "Uta Yuki", "somepass"]
]
],
["https://www.youtube.com/", "youtube-icon", "icons/youtube.png", "social", "YouTube",
[
["Main Account", "lela#email", "somepass"],
]
],
["https://www.facebook.com/?sk=h_chr", "facebook-icon", "icons/facebook.png", "social", "Facebook",
[
["Main Account", "lela#email", "somepass"],
]
],
["https://www.twitter.com/", "twitter-icon", "icons/twitter.png", "social", "Twitter",
[
["Main Account", "lela#email", "somepass"],
]
],
["https://mg.mail.yahoo.com/neo/launch?.rand=8647i3s40jpvp", "ymail-icon", "icons/ymail.png", "social", "Yahoo Mail",
[
["Main Account", "lela#email", "somepass"],
]
]
];
$.get('data/icon.html', function(data) {
var icon;
icons.forEach(function(iconData, index, array) {
console.log(index);
icon = $(data).insertAfter("#" + iconData[3]);
$(icon).find("img").attr("src", iconData[2]);
});
});
};
script.js
/* get icon id */
function buildMenu(iconId) {
$("#remove").click(function() {
$("#" + iconId).hide();
cancel();
});
$("#menu-title").text($("#"+iconId).data("name"));
$("#site-link").attr("href", $("#" + iconId).parent().attr("href")).click(cancel);
switch(iconId) {
};
}
/* set right click for icons */
$(document).ready(function() {
buildIcons();
$(".icons").on("contextmenu", function(e) {
buildMenu(this.id);
$("#contextmenu").show().css({
top: e.clientY,
left: e.clientX
});
e.preventDefault();
});
});
function cancel() {
$("#contextmenu").hide();
}
There is more files and code, if you may need, you may download it above.
Also the console says TypeError: a is null in my jQuery.js file.
Check this
$.get('data/icon.html', function(data) {
icons.forEach(function(iconData, index, array) {
console.log(index);
// Get 'data' as jQuery object
var $data = $(data);
// Find image tag and set source
$data.find('img').attr('src', iconData[2]);
//Finally put it on page
$data.insertAfter("#" + iconData[3]);
});
});
jQuery does not have the ability to include html from another file.
I would like to use autocomplete to search for city and auto fill city name and city id text boxes. Looks simply, but even I pass thru many examples I am simply not able to make it work :(
My biggest success was code below but it makes two separate autocompletes.
HTML:
<form action="form_handler_event_add.php"
method="post"
name="form_event_add">
City: <input type="text" id="city" name="city" />
ID_City : <input type="text" id="id_city" name="id_city" />
</form>
Script:
<script type="text/javascript">
$(document).ready(function(){
$("#city").autocomplete({
source:'handler_getautocomplete.php',
minLength:1
});
$("#id_city").autocomplete({
source:'handler_getautocomplete.php',
minLength:1
});
});
</script>
handler_getautocomplete.php:
$query=mysql_query("SELECT * FROM cities WHERE city_name like '%".$term."%'");
$json=array();
while($city=mysql_fetch_array($query)){
$json[]=array(
'value'=> $city["city_name"],
'id'=>$city["id_city"]
);
}
echo json_encode($json);
So if you want to fill the #id_city input when the city is selected, use the select event:
PHP: handler_getautocomplete.php should return the json encoded string from an array in the following format:
$json = [
[ 'id' => 1, 'value' => 'New York' ],
[ 'id' => 2, 'value' => 'Alabama' ],
[ 'id' => 4, 'value' => 'Seatle' ],
[ 'id' => 6, 'value' => 'San Francisco' ]
];
JS:
$("#city").autocomplete({
source:'handler_getautocomplete.php',
minLength:1,
select: function( event, ui ) {
$( '#id_city' ).val( ui.item.id );
}
});
I think the problem is in the json encoding. In the php handler try this:
$query=mysql_query("SELECT * FROM cities WHERE city_name like '%".$term."%'");
$json=array();
while($city=mysql_fetch_array($query)){
$value[] = $city['city_name'];
$id[] = $city['city_id'];
}
$city_array = array('value' => json.encode(array_values($value)),
'id' => json.encode(array_values($id))
);
return $city_array;
I think is better to make it a function returning a two dimension arrays, wich you can store in a variable $cities.
In the javascript code you should do something like this:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" />
<script type="text/javascript">
$(document).ready(function(){
$("#city").autocomplete({source: <?php echo $cities['value']; ?>, minLength: 1});
$("#id_city").autocomplete({source: <?php echo $cities['id']; ?>, minLength: 1});
</script>
The main problem is that json format is not valid for jquery autocomplete, print it so you can see the difference. Hope it can help you.
Finally manage it. Here is the final codes, maybe it will help to someone:
HTML:
City : <input type="text" id="city" name="city" />
ID_city : <input type="text" id="id_city" name="id_city" />
Script:
<script type="text/javascript">
$(document).ready(function(){
var ac_config = {
source:'handler_getautocomplete.php',
select: function(event, ui) {
$('#id_city').val(ui.item.value);
event.preventDefault();
$("#city").val(ui.item.label); },
minLength:1
};
$("#city").autocomplete(ac_config);
});
</script>
PHP:
$term = trim(strip_tags($_GET['term']));
$query=mysql_query("SELECT city_name, id_city FROM cities WHERE city_name like '%".$term."%'");
$matches = array();
while($city=mysql_fetch_array($query) and $i<10){
$matches[]=array('value' => $city['id_city'],
'label' => $city['city_name'])
;}
print json_encode($matches);
I have the following JSON reply from a PHP file:
[
{
"color": "black",
"product_name": "Prod2",
"revision": "apps/"
},
{
"color": "green",
"product_name": "Prod1",
"revision": "dev/"
}
]
(tested OK on JSONLint)
And Javascript:
$(document).ready(function(){
$('.target').keyup(function() {
var package_name = "name";
var package_version = "version";
var filter_results = "filter";
$.post('includes/package_filter.php', { package_name: package_name, package_version: package_version, filter_results: filter_results }, function(return_result) {
obj = JSON.parse(return_result);
alert(obj.product_name);
var existingDiv = document.getElementById('other');
existingDiv.innerHTML = CreateTable(return_result);
});
});
});
The return_result doesn't seem to be correct since I get Error: SyntaxError: JSON.parse: unexpected end of data when doing the JSON.parse
I also don't go further to the alrt...
What could be wrong?
My PHP file is similar to:
<?php
function package_filter($package_name, $package_version, $filter_results){
foreach ($descriptions as $descriptions_display) {
...
$array_to_return[] = array('color' => $color , 'product_name' => $descriptions_display['product_name'] , 'revision' => $descriptions_display['revision']);
}
return json_encode($array_to_return);
}
?>
My goal is to create a table with my CreateTable function but there is something wrong before.
When dealing with JSON just set fourth parameter in post() method to json:
$.post('includes/package_filter.php', { /* params */ }, function(return_result) {
// return_result[0].product_name;
}, 'json');
Check the encoding of the response UTF-8 ASCII you may have Characters that are messing up with the parser.