I want to get dynamic data in one <div id = "view"> </div>
I use ajax to take dynamic data from api and insert it with var a. I will try to describe with code what I want to get exactly
$.ajax({
url:'url', // [{id:"1",name:"name1"},{id:"2",name:"name2"},{id:"3",name:"name3"}];
method: 'get',
dataType: "json",
success: function (data) {
data.forEach(function(elem){
var a = "ID: " elem.id +"<b>" + elem.name"</b> ";
})
$('#view').html(a);
}
});
Here you are getting the result in a foreach loop which means "a" contains all the results returned by the ajax call, in order to show only one result in a single div we would need to put the value of each loop call in the div, one way is to append the div for each result inside a parent div. I have modified your code below hopefully it helps.
HTML:
<div id = "dataholder"> </div>
JS:
$.ajax({
url:'url', // [{id:"1",name:"name1"},{id:"2",name:"name2"},{id:"3",name:"name3"}];
method: 'get',
dataType: "json",
success: function (data) {
var j = 1;
data.forEach(function(elem){
var a = "ID: " elem.id +"<b>" + elem.name"</b> ";
var view_div_id = "view-"+j;
$( "#inner" ).append( "<div id ="+ view_div_id +"> </div>" );
$('#view-'+j).html(a);
j++;
})
}
});
Related
How to pass a variable value from html page using javascript to php?
i created this code in my index.php
$amount = $_GET['pricenumb'];
echo $amount;
and this is my javascript code to call on click of button and send the data to the PHP file.
<script type="text/javascript">
$(".cell").on("click", "input:checkbox", function () {
var thiss = $(this);
var total = $("#price");
var target = $("label[for='" + thiss.attr("id") + "']");
var item_value = +(target.html().replace(/[^0-9\.]/g, "") || 0);
var cur_total = +(total.html().replace("$", "") || 0);
if (thiss.prop("checked") === true) {
cur_total += item_value;
} else {
cur_total -= item_value;
};
total.text("$" + cur_total);
});
</script>
<script type="text/javascript">
$("#pay_btn").on("click", function () {
var price = $("#price").text();
var pricenumb = price.replace(/[^0-9\.]/g, "");
$.ajax({
type: "POST",
url: "forumdisplay.php?fid=2",
data: "price=" + price + "pricenumb="+ pricenumb,
cache:false,
success: function(){
}
});
});
</script>
and this is the checkbox,
<div class="cell">
<div class="form-check"><label for="check-a" class="form-check-label"><input id="check-a" class="form-check-input" type="checkbox">$166<span class="form-check-sign"></span></label>
<div class="mask visible-on-sidebar-regular">Buy Product</div>
</div>
</div>
the work code is, when I check the checkbox, it will update the div content, and I want when I click on pay button, get the div value via javascript and send the value to my index.php
You are using POST in your ajax and GET in php, chage your ajax to GET. Also, In your ajax change
type: "POST",
url: "forumdisplay.php?fid=2",
data: "price=" + price + "pricenumb="+ pricenumb,
to
type: "GET",
url: "forumdisplay.php",
data: {
price: price,
pricenumb: pricenumb,
fid: 2
}
That's not how you pass data in ajax. The correct format is to use curly braces and define props name and then value
data:{propName1: value1,propsName2: value2,propsName3: "Some string value"}
Which can be used in the file like this in case of POST request.
$_POST['propName1'] which will give value1 variable data as a result
$_POST['propName3'] which will give output as Some string value string
The value can be in quotes if it's a string or not in quotes if it's a variable. So you need to redefine your ajax data props to
$.ajax({
type: "POST",
url: "forumdisplay.php?fid=2",
data: {price: price ,pricenumb: pricenumb},
cache:false,
success: function(response){
// Things to do on success
},
error: function(error){
// Error handling in case of error
}
});
These values you passed can be used in the file forumdisplay.php with $_POST['price'] and $_POST['pricenumb']. The name inside the $_POST is the propsName inside data props in ajax function.
I want to add the values inot the database but I am not to able to do that.
var Array;
$(document).ready(function ()
{
$.ajax({
url: '../api/Emp/GetAll',
type: 'Get',
cache: false,
datatype: 'json',
success: function (text) {
Array = text.Table;
var List = JSON.stringify(text);
for (var i = 0; i < data.length; i++) {
var Id = Array[i].id;
var Name =Array[i].name;
var city = Array[i].city;
$('#table body').append('<tr><td>' + Id + '</td><td><input type="text" value="' + Name + '" id="txt' + Id + '" /></td><td>' + city + '</td> </tr>');
}
}
})
If you need to put it back into the database you just need to reverse the process.
Use post for your type and send the data back with ajax to a php script page that inserts the data into your database.
You can edit the data on the php page before you insert it into the database or you can edit the data with javascript then send it back to php page.
Create an ajax post
$.ajax({
type: "post",
datatype: "json",
url: "insertPage.php",
data: {dataNameHere: editedDataGoesHere},
success: function(data){
alert("SUCCESS");
},
error: function(e){
alert("ERROR");
}
});
And then in your PHP:
$obj = $_POST['dataNameHere'];
and insert it into your database like you normally would.
I hope I can explain my issue clearly.
I am running a function to get values from a database using ajax, and adding each result as a row in a table. This is so the user can delete or edit any row they want. I'm adding IDs dynamically to the columns and also the edit and delete buttons which are generated. So it looks like this:
My code:
function getstationdata(){
var taildata1 = $('#tailnumber2').val();
var uid = $('#uid').val();
$.ajax({
// give your form the method POST
type: "POST",
// give your action attribute the value ajaxadd.php
url: "ajaxgetstationdata.php",
data: {tailnumber:taildata1, uid:uid},
dataType: 'json',
cache: false,
})
.success(function(response) {
// remove all errors
$('input').removeClass('error').next('.errormessage').html('');
// if there are no errors and there is a result
if(!response.errors && response.result) {
var trHTML = '';
$.each(response.result, function( index, value) {
trHTML += '<tr><td><input type="text" value="' + value[2] + '"></td><td><input type="text" class="weightinputclass"value="' + value[3] + '"></td><td><input type="text" class="arminputclass"value="' + value[4] + '"></td><td><input type="text" class="momentinputclass" value="' + value[5] + '"></td><td><button id="updatecgbtn" onclick="updatecg()"class="editbuttonclass">Edit</button></td><td><button id="deletecgbtn" class="deletebuttonclass"">Delete</button></td></tr>';
});
$('#mbtbody').html('');
$('#mbtbody').html(trHTML);
var ID = 0;
$('.weightinputclass').each(function() {
ID++;
$(this).attr('id', 'weightinputboxID'+ID);
});
var ID = 0;
$('.arminputclass').each(function() {
ID++;
$(this).attr('id', 'arminputboxID'+ID);
});
var ID = 0;
$('.momentinputclass').each(function() {
ID++;
$(this).attr('id', 'momentinputboxID'+ID);
});
var ID = 0;
$('.editbuttonclass').each(function() {
ID++;
$(this).attr('id', 'editbutton'+ID);
});
var ID = 0;
$('.deletebuttonclass').each(function() {
ID++;
$(this).attr('id', 'deletebutton'+ID);
});
} else {
// append the error to the form
$.each(response.errors, function( index, value) {
// add error classes
$('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
});
}
});
}
The code I have when adding the info is in a form and it looks like this:
$('#addstations').on('submit', function(e){
e.preventDefault();
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: 'json',
cache: false,
})
.success(function(response) {
$('input').removeClass('error').next('.errormessage').html('');
if(!response.errors && response.result) {
$.each(response.result, function( index, value) {
chartdata4=(tailnumber3.value)
});
} else {
// append the error to the form
$.each(response.errors, function( index, value) {
// add error classes
$('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
});
}
});
});
I searched a bit on the internet and found out that I can't add a form inside my table for each row which would have been easy to do and I can reuse my code which I use when adding new info.
So, can someone please point me in the right direction?
Here is the direction you could go
$('#formTable').on('click',"button" function(e){
var $row = $(this).closest("tr"), $form = $("#addstations");
var data = {
passenger:$row.find("passengerClass").val(),
weight :$row.find("weightClass").val()
} // no comma on the last item
data["type"]=this.className=="deletebuttonclass"?"delete":"edit";
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
dataType: 'json',
cache: false,
})
...
I assume that the problem is that you want to add a form as a child of a table / tbody element to wrap your row. You cannot do that and the browser will most likely strip the form tags, leaving you with nothing to serialize.
There are different solutions for that, for example:
Build the data object manually in javascript when a button on a row is clicked;
Use a non-form grid solution for your layout.
Add each row in its own table and have the form wrap that table
The third solution is a bit of a hack, I would use the first or the second myself.
This is my ajax:
$("#submit").on("click",function()
{
$("#add_car_form").submit(function(){
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "text",
url: "add_car_submit.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
$(".the-return").html("<br />JSON: " + data );//this outputs
{"car_name":";ll","car_maker":"njk","car_type":"nkj","passanger":"1","rate":["89","67","45","34","23"],"action":"test"}
}
});
document.getElementById("add_car_form").reset();
return false;
});
});
I simply echo from php script like this: echo $return["json"]; and it will output like this:
{"car_name":";ll","car_maker":"njk","car_type":"nkj","passanger":"1","rate":["89","67","45","34","23"],"action":"test"}
How do append to a div in html table form like this?
Car Name: name
Car Maker: maker
......
try this in your success function
data = jQuery.parseJSON( data ); //parse data if this is text other wise use data directly. hope this is a text param in your case.
var out = '<table>';
$.each(data, function( key, value ) {
out += '<tr><td>'+key+': '+ value +'</td></tr>';
});
out += '</table>';
//append out to your div
$(".the-return").html(out);
You should not create a form submit handler inside a click handler as it could create multiple listeners for single click event.
I think you could just encode the data use json_encode in the server side then, accept the response as json in the client using dataType: 'json' then
$("#submit").on("click", function () {
var $form = $("#add_car_form")
var data = {
"action": "test"
};
data = $form.serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "add_car_submit.php", //Relative or absolute path to response.php file
data: data,
success: function (data) {
$(".the-return").html("Car Name" + data.car_name + '<br />Car Maker' + data.car_maker); //Add more properties here
}
});
document.getElementById("add_car_form").reset();
return false;
});
my updated full script:
$(document).ready(function() {
$.getJSON('table.json',function(data){
$('#mytable').empty();
var html = '';
html += '<tr class="tableheader"><th>Name</th><th>Code</th><th>Value</th><th>Bid</th><th>Offer</th></tr>';
for (var i=0, size=data.length; i<size;i++) {
html += '<tr class="tablecontent"><td>'+ data[i].name+ '</td><td>'+ data[i].code+ '</td><td>'
+ data[i].value+ '</td><td>'
+data[i].bid+'</td><td>'+data[i].offer+'</td></tr>';
}
$('#mytable').append(html);
tablerows('mytable');
setTimeout(poll,5000);
});
});
var poll = setInterval(function(){
$.ajax({
type:"GET",
url: "dummy.json",
success: function(data){
//HANDLE DATA
setTimeout(poll,5000);
}
});
},5000);
Please help me in this. i have 3 JSONs. 1st Json will load initially. That is done.
2nd json needs to be parsed (which has 2 field changes) and show the initial json + changed fields and then again from 3rd JSON.
I have written below script:
var poll = setInterval(function(){
$.ajax({
type:"GET",
url: "dummy.json",
success: function(data){
//HANDLE DATA
JSON.parse(data);
}
});
},5000)
dummy.json is my second changed JSON. Is this the correct way?how should i call this function function in my $(document).ready?
Set it as a regular function and then call it from itself within the success handler so then you are never getting ahead of yourself. Then you can also just call it once from your $(document).ready.
var poll = function(){
$.ajax({
type:"GET",
url: "dummy.json",
success: function(data){
//HANDLE DATA
setTimeout(poll,5000);
}
});
}