I am working in codeigniter. I have created one table and its html is like this:
<table>
<tr>
<td>
<center><label style="font-weight:normal" class="t_date"><?php echo date('Y-m-d'); ?></label></center>
</td>
<td>
<center><label style="font-weight:normal" class="b_id"><?php echo $result[0]->branch_id; ?></label></center>
</td>
</tr>
<tr>
<td></td>
<td><input type="button" onClick="window.print();" value="Print" name="print" id="print"/></td>
</tr>
</table>
Now I want to get the value of td so I have written jQuery like this:
<script>
jQuery(document).ready(function(){
jQuery("#print").click(function(){
//alert(123);
var to_date = jQuery(".t_date").text();
var to_date = jQuery(".b_id").text();
});
});
</script>
And I got value of it. Now i want to insert these all value into database so what code should i have to write?
jQuery(document).ready(function () {
jQuery("#print").click(function () {
alert(123);
var to_date = jQuery(".t_date").text();
var to_id = jQuery(".b_id").text();
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>index.php/controller/function",
data: {to_date: to_date, to_id: to_id},
success: function (html) //we're calling the response json array 'permissions'
{
// action
}
});
});
});
this ajax will call your function in controller.. in your function call a model function to insert the values to db.
you can do so using AJAX.
Create a webpage to accept inputs as parameters and save them into database.
And study this link: http://www.w3schools.com/jquery/jquery_ajax_get_post.asp
code to do so:
$.get("web page address with parameters ", function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
For example: if you created a webpage named "savedata.php" that takes inputs as parameters and saves into database.
Then
$.get("[root_path]/savedata.php?[paramaters]", function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
[root_path] is the root path of you webpage and [parameters] is "&" separated parameters.
Refer - AJAX
<script>
jQuery(document).ready(function () {
jQuery("#print").click(function () {
$.ajax({
url: '/path/to/file',
type: 'default GET (Other values: POST)',
dataType: 'default: Intelligent Guess (Other values: xml, json, script, or html)',
data: {
t_date: jQuery(".t_date").text(),
b_id: jQuery(".b_id").text(),
},
success: function (response) {
alert(response);
}
});
});
});
</script>
this will do the work
Related
I'm new to wordpress and I have little coding knowledge.I wanted to get few data from external API and display those data in my wordpress site html area.
here is external API: https://www.hpb.health.gov.lk/api/get-current-statistical
API contains lot of details.I dont want all of them.I just need 4,5 of them..
(eg:local_new_cases,update_date_time,local_total_cases,local_deaths,local_recovered)
here is the details :https://www.hpb.health.gov.lk/en/api-documentation
here is external web site :https://www.hpb.health.gov.lk/en
I created some code by using stackoverflow,but I don't know how to parse few data into my html area.some tutorial teaching button event.I'dont want button click event.
I have created below code:(It means ,I took data from API )
var data;
$( document ).ready(function() {
getHealthData();
});
/**
*Gets data from API
**/
function getHealthData(){
$.ajax({
type : "GET",
dataType : "json",
url : "https://www.hpb.health.gov.lk/api/get-current-statistical",
data : {action: "get_data"},
success: function(response) {
alert(response);
data= response.data;
}
});
}
Now I want to parse few data(eg:local_new_cases,update_date_time,local_total_cases,local_deaths,local_recovered) from API, into html code.
How to do that? please help me to save my life.Thank you.
You can get data using response.data and get respective value using value['something'] like below :
var data = "";
$(document).ready(function() {
getHealthData();
});
/**
*Gets data from API
**/
function getHealthData() {
$.ajax({
type: "GET",
dataType: "json",
url: "https://www.hpb.health.gov.lk/api/get-current-statistical",
data: {
action: "get_data"
},
success: function(response) {
//getting value from server
var value = response.data;
data = "local_total_cases : " + value['local_total_cases'] + "<br/>local_deaths : " + value['local_deaths'] + "<br/>local_new_deaths : " + value['local_new_deaths'] + "<br/>local_recovered : " + value['local_recovered'] + "<br/>local_new_cases : " + value['local_new_cases'];
//putting values in div with id="data"
$("#data").html(data);
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div id="data">
</div>
Update 1 :
Here in below code i have added some html tag ,you can add more tag to your data like below and do changes as per your requirement
var data = "";
$(document).ready(function() {
getHealthData();
});
/**
*Gets data from API
**/
function getHealthData() {
$.ajax({
type: "GET",
dataType: "json",
url: "https://www.hpb.health.gov.lk/api/get-current-statistical",
data: {
action: "get_data"
},
success: function(response) {
//getting value from server
var value = response.data;
data = "<h5>local_total_cases :</h5><b>" + value['local_total_cases'] + "</b><br/><h5>local_deaths :</h5><b> " + value['local_deaths'] + "</b><br/><h5> local_new_deaths : </h5><b>" + value['local_new_deaths'] + "</b><br/><h5>local_recovered : </h5> <b>" + value['local_recovered'] + "</b><br/><h5>local_new_cases :</h5> <b>" + value['local_new_cases']+"</b>";
//putting values in div with id="data"
$("#data").html(data);
//adding value separately
$("#something").text("local_total_cases :" + value['local_total_cases'])
}
});
}
h5{
font-size:20px;
color:blue;
}
b{
font-size:25px;
color:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div id="data">
</div>
<h3 id="something"></h3>
I'm using jquery datepicker on a page. Next to datepicker i have a section which will show events on mouseenter of the datepicker. I have figured out a way to get the date into the header of this section. The problem i am having is getting that variable over to the php page that will be displayed on mousenter.
Below is the page that the datepicker and events will be shown:
<div id=events>
<div id=eventcontent>
</div>
</div>
<div id=eventsheading>
<div id=headingcontent>
</div>
</div>
<div id = "datepicker">
</div>
This is the Jquery i am using to fill in the header with the date (which works), send the same variable to events.php (which doesnt work), and show events.php in the content div (which does work as when i highlight a date, hello is shown):
$(document).on('mouseenter', '.ui-datepicker-calendar .ui-state-hover', function(e){
var daynum1 = $(this).text();
var month1 = $('.ui-datepicker-month').text();
var year1 = $('.ui-datepicker-year').text();
var Date = daynum1 + " " + month1 + " " + year1;
$('#headingcontent').html(Date);
//ajax call with date information
var request = $.ajax({
url: "events.php",
type: "POST",
data: {Date: Date},
dataType: "html"
});
$.ajax({
url: "events.php",
cache: false,
success: function(html){
$("#eventcontent").append(html);
}
});
});
Below is events.php:
if(isset($_POST['Date']))
{
$date = $_POST['Date'];
echo <<<_END
<p>$date</p>
_END;
}
else
{
echo <<<_END
<p>hello!</p>
_END;
}
once i get this bit working, events PHP will be changed to select events from mysql.
To clarify, the problem i am having is getting variable date to send via ajax with this code:
//ajax call with date information
var request = $.ajax({
url: "events.php",
type: "POST",
data: {Date: Date},
dataType: "html"
});
i cant seem to find anywhere that explains how data: {...}, should be used and I'm guessing this is my problem.
Sorry if the code is just completely wrong i'm very new to learning it all and thanks for any help.
you must not use variable names which collide with inbuilt objects as #CBroe said.
and rest like this
var myDate = daynum1 + " " + month1 + " " + year1;
$('#headingcontent').html(myDate);
$.ajax({
url: "events.php",
type: "POST",
data: {myDate: myDate},
dataType: "html",
success: function(html){
$("#eventcontent").empty();
$("#eventcontent").append(html);
}
});
no need for second ajax call
I'm having a problem when I click my generate cards button multiple times(it generates a new set of cards randomly on every click) and then I click on any of my buttons that sort it will run multiple ajax calls instead of just the latest generated array. It will pass in every array of cards that has been generated not just the most recent one, sort of like it's keeping a queue.
console log will output, "sending color sort", "sending color sort", "sending color sort", etc. *For as many times as i've clicked my generate_cards* button
How can I have it so the sort function only runs once.
<input type="button" value="Generate Cards" id="generate_cards"> </input>
<input type="button" class="sorter" value="Color Sort" id="color_sort"> </input>
<input type="button" class="sorter" value="Shape Sort" id="shape_sort"> </input>
Generate Cards:
$('#generate_cards').click(function() {
$.ajax({
url: ''+set,
async: false,
type: 'POST',
dataType: 'html',
success: function(data) {
var obj = JSON.parse(data);
//sent array to sorting function :
sorting(obj);
var tmpl = $("#formInfo_tmpl").html();
var html = Mustache.to_html(tmpl, obj);
pool_window.html(html);
initilizejs();
},
error:function(jqXHR, textStatus, errorThrown){
alert("Error type" + textStatus + "occured, with value " + errorThrown);
}
});
card sort function
function sorting(cards) {
$('.sorter').on("click", function() {
var cards_window = $("#sealed_pool");
var sort_type = $(this).attr('id');
//just give me the first word:
sort_type = sort_type.replace(/(\w+).*/,"$1");
console.log('sending'+sort_type);
$.ajax({
url: '',
async: false,
type: 'POST',
data: ({'cards':cards, 'sort_type':sort_type}),
dataType: 'html',
success: function(data) {
var obj = JSON.parse(data);
if(sort_type =='color_sort')
{
var tmpl = $("#color_sort_tmpl").html();
}
if(sort_type =='shape_sort')
{
var tmpl = $("#formInfo_tmpl").html();
}
var html = Mustache.to_html(tmpl, obj);
cards_window.html(html);
initilizejs();
},
error:function(jqXHR, textStatus, errorThrown){
alert("Error type" + textStatus + "occured, with value " + errorThrown);
}
});
});
}
remove the previous click-listener before you add a new:
$('.sorter')
.off("click")
.on("click", function() {
//code
});
You need to use setInterval within the document ready function, like this:
$(document).ready(function() {setInterval(doAjax, 5000);});
I am using Twitter Bootstrap Typeahead for an autocomplete field.
End state goal: The user first enters details into field 1. When they enter details in field 2, ajax passes the query as it is written to a PHP file which queries a database based on what was also entered into field 1.
How do I pass both the query from field 2 and the contents of field 1 to the PHP file and access them.
Here is what I have so far:
HTML FILE:
<div class="field1">
<input type="text" id="field1" data-provide="typeahead" name="field1">
</div>
<div class="field2">
<input type="text" id="field2" data-provide="typeahead">
</div>
<script src="js/jquery-1.9.1.min.js"></script>
<script src="js/bootstrap.js"></script>
<script>
$(function() {
$("#field2").typeahead({
source: function(query, process) {
var textVal=$("#field1").val();
$.ajax({
url: 'field2.php',
type: 'POST',
data: 'query=' + query,
dataType: 'JSON',
async: true,
success: function(data) {
process(data);
console.log(textVal);
}
});
}
});
});
</script>
PHP FILE:
if (isset($_POST['query'])) {
$db_server = mysql_connect("localhost", "root", "root");
mysql_select_db("db_test");
$query = $_POST['query'];
$other = '**This needs to be field 1**';
$sql = mysql_query("SELECT * FROM table WHERE row1 LIKE '%{$query}%' AND row2 = '$other'");
$array = array();
while ($row = mysql_fetch_assoc($sql)) {
$array[] = $row['row1'];
}
echo json_encode($array);}
At the moment, the query part works perfectly and the results are returned (the console also displays the value from 'Field1'. Just need to get that value into the php file at the same time!
Any help would be great
If I understood this correctly, you want to parse both the values of field 1 and 2 to the same AJAX call. This is how you do it.
<script>
$(function() {
$("#field2").typeahead({
source: function(query, process) {
var textVal=$("#field1").val();
$.ajax({
url: 'field2.php',
type: 'POST',
data: 'query=' + query + '&field1=' + textVal,
dataType: 'JSON',
async: true,
success: function(data) {
process(data);
console.log(textVal);
}
});
}
});
});
</script>
Now you just make another $_POST['field1'] in your PHP file.
var userQuery = $('#ID of query input element').val();
var field1 = $('#ID of input 1 element').val();
$.ajax({
type: "POST",
url: '',
data: {query: QueryVariable, input1: input1variable},
success: function(data) {
// code within this block
},
error: function() {
alert('System Error! Please try again.');
},
complete: function() {
console.log('completed')
}
}); // ***END $.ajax call
i have been looking around to try and work out how to pass 2 variables arcoss the page thru ajax i have at this moment a page where a check box dynamailcy saves its value to the database on the click of it but i need it to be able to only edit rows with a certian id at thi moment i have gotten this far but i am stuck. any help would be greatly appricated
$(function()
{
$("input[type='checkbox']").on('click', function(){
var chkName = $(this).attr('checked');
if($(this).is(":checked")) {
var checkVal = $(':checkbox[checked='+chkName+']').attr('value');
}
else{
var checkVal =$("#frm input:checkbox").attr("id");
}
var userid = $(':checkbox[checked='+chkName+']').attr('name');
$.ajax({
type: "GET",
url: 'request.php?uname=' + checkVal '&id'= + userid ,// this is where i cant send the &id varible across but i can send the checkVal
success: function(data) {
if(data == 1){//Succues
alert('Data was saved in db!');
}
if(data == 0){//Faliure
alert('Data was NOT saved in db!');
}
}
});
});
});
</script>
</head><body>
<div class="content">
<table border="0.02px" class="mytable">
<thead>
<th><strong>Paid</strong></th>
<th><strong>Repaired</strong></th>
<th><strong>Returned</strong></th>
</thead>
<tr>
<form id="frm" name="frm">
<td><input type="checkbox" value="Paid" id="Waiting on Payment" name="29" /></td>
<td><input type="checkbox" value="Repaired" id="Waiting on Repairs" name="uname" /></td>
<td><input type="checkbox" value="With Student" id="Awaiting Pickup" name="uname" /></td>
</form>
</tr>
</table>
</div>
Below line in your code is incorrect:
url: 'request.php?uname=' + checkVal '&id'= + userid ,
Should be:
url: 'request.php?uname=' + checkVal +'&id=' + userid,
Also consider using var isChecked = $(this).prop('checked'); to get the checked status of checkbox.
In line var chkName = $(this).attr('checked');, value of chkName would be 'undefined', while the checkbox is unchecked and so as the line
var userid = $(':checkbox[checked='+chkName+']').attr('name');.
If I understand your code correctly, then you may try this:
$("input[type='checkbox']").on('click', function() {
var $this = $(this);
var isChecked = $this.prop('checked');
var checkVal = isChecked ? $this.attr('value') : $this.attr("id");
var userid = $this.attr('name');
$.ajax({
type: "GET",
//url: 'request.php?uname=' + checkVal '&id' = +userid,
url: 'request.php?uname=' + checkVal +'&id=' + userid,
// this is where i cant send the &id varible across but i can send the checkVal
success: function(data) {
if (data == 1) { //Succues
alert('Data was saved in db!');
}
if (data == 0) { //Faliure
alert('Data was NOT saved in db!');
}
}
});
});
Currently there is an error with the url variable you are trying to send
Current:
url: 'request.php?uname=' + checkVal '&id'= + userid,
Corrected:
url: 'request.php?uname=' + checkVal + '&id=' + userid,
I think you are looking for .serialize from jquery.
You can check the api here. It has the example as well. Please go through the example how to pass serialized data.
Later in server end, you can have $_POST['<your input name here>'] to get the value.
In addition, I see you try to get back the value from server. You can always echo json_encode(<your data object here>) to send to server end.