I can't push the value of my array to my php file.
Script:
<script>
$(document).ready(function() {
var item_code = [];
$('#save').click(function() {
var item_name = [];
var item_value = [];
var item_quantity = [];
for (var i = 0; i < item_code.length; i++) {
item_code.push($(this).val());
}
$('.item_name').each(function() {
item_name.push($(this).val());
});
$('.item_value').each(function() {
item_value.push($(this).val());
});
$('.item_quantity').each(function() {
item_quantity.push($(this).val());
});
$.ajax({
url: "insert2.php",
method: "POST",
data: {
item_name: item_name,
item_code: item_code,
item_value: item_value,
item_quantity: item_quantity,
},
success: function(data) {
}
});
</script>
I have a value storing at "item_code" whenever I search the item code on my search bar. And after that, I want to push the value of item_code[] on the insert2.php.
I'm not getting any error, but the system itself is frozen.
I am guessing that "item_code" variable is also declared globally somewhere else in your code, otherwise there would be no point in iterating through it. Try using a different name instead of "item_code" to send it to "insert2.php".
for (var i = 0; i < item_code.length; i++) {
item_code.push($(this).val());
}
You can't push data into the same array that you are looping because you will never reach the end of it, unless the memory limit will tell you otherwise. Declare "item_code_second" and push into that:
$(document).ready(function() {
var item_code_second = [];
and change your loop:
for (var i = 0; i < item_code.length; i++) {
item_code_second.push($(this).val());
}
also you are pushing the same value "$(this).val()" as many times as there are values in item_code, which is not making any sense and the exact same value in name, quantity and value. $(this) represents the button that was pushed, don't forget you are in an on click event.
Related
I have a dropdown that is filled by a database and everything works well. However I want to pass a parameter to php based on the value of the dropdown which I can do. If I force the var to have a particular number it gets the corresponding item in the database. I'm having a problem to get the value of a dropdown. I've tried all the suggestions here in the forum and nothing works in this particular area of my code. I have it working on another piece of my code but not on this particular one and I don't know why. Here is my code:
<select id="servicos" onChange="return selectServ();">
<option value="item" class="itemoption">Serviço</option>
This is the code that is not working:
function selectServ() {
var e = document.getElementById("servicos");
var idserv = e.options[e.selectedIndex].value;
$.getJSON("http://ib.esy.es/gestao/_php/servicos_threadingpreco.php", { serv: idserv }, null).then(function(data) {
console.log(data);
var tr = data
for (var i = 0; i < data.length; i++) {
var tr = $('<tr/>');
// Indexing into data.report for each td element
$(tr).append("<td>" + data[i].preco + "</td>");
$('.table1').append(tr);
}
});
}
If I put
var idserv = "1"
It is working, however this:
var e = document.getElementById("servicos");
var idserv = e.options[e.selectedIndex].value;
Is not getting a value. The console log gives:
selectdynamicpreco.html:76 Uncaught TypeError: $(...).value is not a function
You should consider using jQuery to get the value of the dropdown:
$('#dropdown').val() will give you the selected value of the drop down element. Use this to get the selected options text.
$("#dropdown option:selected").text();
Should get you the text value of the dropdown.
This is working on another piece of the code
<script>
function selectCat(){
$('#servicos').change(function() {
$('#demo').text($(this).find(":selected").text());
});
//for textbox use $('#txtEntry2').val($(this).find(":selected").text());
var e = document.getElementById("categoria");
var servSelected = e.options[e.selectedIndex].value;
var url = "";
var items="";
if(servSelected === "1"){
url = "http://ib.esy.es/gestao/_php/servicos_threading.php";
}
if(servSelected === "2"){
url = "http://ib.esy.es/gestao/_php/servicos_sobrancelhas.php";
}
if(servSelected === "3"){
url = "http://ib.esy.es/gestao/_php/servicos_manicure.php";
}
$.getJSON(url,function(data){
$.each(data,function(index,item)
{
items+="<option value='"+item.ID+"'>"+item.servico+"</option>";
});
$("#servicos").html(items);
});
};
</script>
I have a little bit of a problem, I have a JavaScript with jQuery where I work with an Array I got from PHP, in the script I add some data to two new arrays and here comes my problem, how can I work with those two arrays in my PHP file? I need to save the data from the two new arrays in a database. In the PHP I have a form where I enter some data about a User. Does someone knows a easy way to send my data back to the PHP?
Some information about the script: I have a table with the names of schools, and a checkbox with the id of the school as a value. when i check or uncheck one of the checkboxes the script checks if it is a school already saved in the database for this specific user or if it's a new user.
<script>
var schools = [];
var oldschools = [];
var uncheckedschools = [];
oldschools = <?php echo json_encode($oldschoolids); ?>;
$(".checkbox").change(function() {
if(this.checked) {
var additem = $(this).val();
for (var i=0; i<oldschools.length; i++) {
if (additem == oldschools[i]) {
uncheckedschools = jQuery.grep(uncheckedschools, function(value) {
return value != additem;
});
}
}
schools.push(additem);
} else {
var removeitem = $(this).val();
for (var i=0; i<oldschools.length; i++) {
if (removeitem == oldschools[i]) {
uncheckedschools.push(removeitem);
}
}
schools = jQuery.grep(schools, function(value) {
return value != removeitem;
});
}
});
</script>
I hope someone can help me with this problem!
You'll need to use AJAX to send your updates back to your server. Using jQuery's ajax() method, it would looks something like this:
$.ajax({
url: 'path/to/serverside/file.php',
dataType: 'json',
data: {schools: schools},
success: function(dataFromServer) {
//after the save is successful, you can do something here
},
error: function(dataFromServer) {
//if there was an error handle it here
}
});
EDIT: As mentioned by a few commentors, you'll need to use json_decode on the server-side to decode the JSON Object you're sending back: http://php.net/manual/en/function.json-decode.php
Having trouble using ajax to retrieve info from a database. I was getting the code from here:
http://openenergymonitor.org/emon/node/107
the code from here worked but would only output 1 item
Simple Ajax Jquery script- How can I get information for each of the rows in the table?
I tried to add this to my code but I could not get it to work.
I am getting everything from a table with the following php:
$result = mysql_query("SELECT * FROM voterecords");
$data = array();
while ( $row = mysql_fetch_row($result) )
{
$data[] = $row;
}
echo json_encode($data);
which outputs the following if I navigate to that php page:
[["68","1234","0","1234",""],["69","added with ajax","0","this item was added using ajax",""]]
The format of the above is as follows:
id, title, votes, description, owner
I think that bit all works but I cant be sure because i dont know what JSON is supposed to look like.
Ok now here is the jquery which is supposed to retrieve the info from the JSON and put it into the html element #output
$(function ()
{
$.ajax({
url: 'retrieve.php', data: "", dataType: 'json', success: function(rows)
{
for (var i in rows)
{
var row = rows[i];
var id = row[0];
var name = row[1];
var votes = row[2];
var info = row[3];
$('#output').append("<b>id: </b>"+id+"<b> name: </b>"+name+"<b> votes: </b>"+votes+"<b> info: </b>"+info)
.append("<hr />");
}
}
});
I was expecting this to output all the info but nothing happens.
Your code is fine except you have a missing closing ) from the callback function.
Also, in JavaScript, it's better to place opening braces on the same line, not on the next, as is common in some other languages.
Corrected/cleaned-up code:
$(function () {
$.ajax({url: 'retrieve.php', dataType: 'json'}).done(function(rows) {
for (var i in rows) {
var row = rows[i];
var id = row[0];
var name = row[1];
var votes = row[2];
var info = row[3];
$('#output')
.append("<b>id: </b>"+id+"<b> name: </b>"+name+"<b> votes: </b>"+votes+"<b> info: </b>"+info)
.append("<hr />");
}
});
});
i have an ajax call and it works good , when i call a new ajax call inside the old one , i got error in the first call
just one ajax call
$.getJSON("http://localhost/Mar7ba/Ontology/getRelatedConceptsAndRelations/"+conceptName+"/TRUE",function(data){
var concepts = data[0];
var relations = data[1];
for(var i = 0 ; i < concepts.length ; i++){
var IOS = '';
$("#ioAddRelatedConcepts").append('<p>\n\
connect to\n\
<span class="ioAddConcept">'+concepts[i]+'</span>\n\
with\n\
<span class="ioAddRelation">'+relations[i]+'</span>\n\
<select name ="concetedIOs[]" class="TypeSelector">\n\
'+IOS+'</select>\n\
<span class="errorMessage"></span>\n\
remove\n\
</p>\n\
<p>');
}
});
after adding this ajax call
$.getJSON("http://localhost/Mar7ba/Ontology/getRelatedConceptsAndRelations/"+conceptName+"/TRUE",function(data){
var concepts = data[0];
var relations = data[1];
for(var i = 0 ; i < concepts.length ; i++){
$.getJSON("http://localhost/Mar7ba/InformationObject/getIOsForConcept/"+concepts[i]+"/TRUE",function(data1){
var IOS = '';
$("#ioAddRelatedConcepts").append('<p>\n\
connect to\n\
<span class="ioAddConcept">'+concepts[i]+'</span>\n\
with\n\
<span class="ioAddRelation">'+relations[i]+'</span>\n\
<select name ="concetedIOs[]" class="TypeSelector">\n\
'+IOS+'</select>\n\
<span class="errorMessage"></span>\n\
remove\n\
</p>\n\
<p>');
});
}
});
after that , the concepts[i] and the relations[i] will be as undifined
and the data1.length always null
and the this is the second php code for ajax
public function getIOsForConcept($conceptName, $AJAX) {
if ($AJAX) {
$results = $this->model->getIOsForConcept($conceptName);
$IOs = array();
$i = 0;
while ($row = $results->fetch()) {
$IOs[$i] = $row['name'];
$i++;
}
return json_encode($IOs);
}
}
and i tried it and it works good
You can't use a loop variable ( i in your case) inside a callback function - it'll have whatever value it had when the loop terminated by the time your async callback function is invoked.
As you're already using jQuery, you might as well use $.each():
$.getJSON(..., function(data) {
var concepts = data[0];
var relations = data[1];
$.each(concepts, function(i, value) {
// concepts[i] is OK to use now, and is also in "value"
// relations[i] is OK to use too
$.getJSON(..., function() {
// you can still use them here, too!
});
});
});
which will ensure that i is correctly bound to the current iteration number each time.
The reason that concepts[i] and the relations[i] are undefined within the callback function of the inner $.getJSON() function is that $.getJSON() is aysnchronous which means that the entire for loop will have finished running before any of the callbacks occur on the inner $.getJSON() calls - so by the time these inner callbacks occur i is one higher than the maximum index of the concepts and relations arrays.
To get around this you can introduce an extra closure to keep the values from each iteration:
$.getJSON("http://localhost/Mar7ba/Ontology/getRelatedConceptsAndRelations/"+conceptName+"/TRUE", function(data){
var concepts = data[0];
var relations = data[1];
for(var i = 0 ; i < concepts.length ; i++){
(function(currentConcept, currentRelation) {
$.getJSON("http://localhost/Mar7ba/InformationObject/getIOsForConcept/"+currentConcept+"/TRUE" , function(data1){
var IOS = '';
$("#ioAddRelatedConcepts").append('<p>\n\
connect to\n\
<span class="ioAddConcept">'+ currentConcept +'</span>\n\
with\n\
<span class="ioAddRelation">'+ currentRelation +'</span>\n\
<select name ="concetedIOs[]" class="TypeSelector">\n\
'+IOS+'</select>\n\
<span class="errorMessage"></span>\n\
remove\n\
</p>\n\
<p>');
});
})(concepts[i], relations[i]);
}
});
The anonymous function I've added inside the for loop will run once per iteration creating separate closures each with their own currentConcept and currentRelation.
EDIT: To make it really obvious what I've changed compared to your original code--
Add the following line as the first thing inside your existing for loop:
(function(currentConcept, currentRelation) {
And then the following line as the last thing before your existing for loop's closing }:
})(concepts[i], relations[i]);
And then everywhere inside the for loop where you did have concepts[i] and relations[i] change them to currentConcept and currentRelation.
I am using the following code to get a list of members and their information using ajax, jquery, php, json.
The only problem is when i use .html , it only displays the first record, it doesn't display all of the records. Totally confused.
<script type="text/javascript">
$( document ).delegate("#member_home", "pagecreate", function() {
var refreshId = setInterval(function(){
var friends= new Array();
$.ajaxSetup({cache: false})
$.ajax({
url:'http://www.l.example.com/app/scrip/friends_lookup.php',
data: "",
dataType: 'json',
success: function(data){
$.each(data, function(key, val) {
var friend = val['friend'];
var phone = val['phone'];
var status = val['status'];
var email = val['email'];
var updated = val['updated'];
$('#member_friends').append("<div class='member-box'>"+friend+"<span class='status-pic1'><img src='images/"+status+".png' width='40' height='40'/></span><span class='phone_box'><a href='tel:"+phone+"'><img src='images/icons/phone.png' width='40' height='40' /></a></span><span class='email-box'><a href='mailto:"+email+"'><img src='images/mail.png' width='40' height='40' /></a></span><div class='clear'></div><span class='update-status'><i>last update: "+updated+"</i></span>");
});
}
});
}, 1500);
});
</script>
I tried this, and it didn't work:
<script type="text/javascript">
$( document ).delegate("#member_home", "pagecreate", function() {
var refreshId = setInterval(function() {
var friends= new Array();
$.ajaxSetup({cache: false})
$.ajax({
url: 'http://www.l.example.com/pp/scripts/friends_lookup.php',
data: "",
dataType: 'json',
success: function(data){
var output = [];
for (var i = 0, len = data.length; i < len; i++) {
output[output.length] = {
friend : data[i].friend,
phone : data[i].phone,
status : data[i].status,
email : data[i].email,
updated : data[i].updated
};
$('#member_friends').html("<div class='member-box'>"+friend+"<span class='status-pic1'><img src='images/"+status+".png' width='40' height='40'/></span><span class='phone_box'><a href='tel:"+phone+"'><img src='images/icons/phone.png' width='40' height='40' /></a></span><span class='email-box'><a href='mailto:"+email+"'><img src='images/mail.png' width='40' height='40' /></a></span><div class='clear'></div><span class='update-status'><i>last update: "+updated+"</i></span>");
}
}
});
}, 1500);
});
</script>
You are over-writing the values each iteration of your $.each loop. Before the loop, create an array to store the data, then add to the array each iteration:
$.ajax({
success : function (data) {
var output = [];
for (var i = 0, len = data.length; i < len; i++) {
output[output.length] = {
friend : data[i].friend,
phone : data[i].phone,
status : data[i].status,
email : data[i].email,
updated : data[i].updated
};
}
//you now have an array of objects that each contain a set of information
}
});
The for loop I used is quite fast, here's a JSPerf to show the performance increase over using $.each(): http://jsperf.com/jquery-each-vs-for-loops/2
Also you may have noticed that I used output[output.length] = ... instead of output.push(...). The former performs faster in old browsers (the latter performs faster in modern browsers), I tend to try to help the old browsers out since they really need the help.
I guess your problem is that when you use .html() within a loop, for every iteration, it will replace all content added with the .html() during the previous iteration. Logically that would however leave you with only the last record, not the first.
You have to call .html() after the loop, currently it will replace the contents of #member_friends
in every loop iteration, so you will always see the last item.
This should be the workaround:
var output = [];
var html = []
for (var i = 0, len = data.length; i < len; i++) {
output[output.length] = {
friend : data[i].friend,
phone : data[i].phone,
status : data[i].status,
email : data[i].email,
updated : data[i].updated
};
html.push("<div class='member-box'>"+friend+"<span class='status-pic1'><img src='images/"+status+".png' width='40' height='40'/></span><span class='phone_box'><a href='tel:"+phone+"'><img src='images/icons/phone.png' width='40' height='40' /></a></span><span class='email-box'><a href='mailto:"+email+"'><img src='images/mail.png' width='40' height='40' /></a></span><div class='clear'></div><span class='update-status'><i>last update: "+updated+"</i></span>");
}//end of for
$('#member_friends').html(html.join(''));