How to insert multiple values to database table using php? - javascript

Plz check this jsfiddle. My results are like this,
http://jsfiddle.net/kz1vfnx2/
i need to store these datas to database(sql server) one by one in each row using PHP Codeigniter. Insert to table looks like
Date Frequency
05-Feb-2019 1st Basic Treatment
12-Mar-2019 2nd Control Treatment
----------------------------------
--------------------------------
when button clicks call the function and insert to datatabase
$('#saveactivityarea').on('click', function(event) { //save new activity area
var act_contractbranch_firstjobdt = "2019-01-01";
var Contractend_firstjobdt = "2020-01-01";
var act_job_freq_daysbtw= "30";
saveschedule(act_contractbranch_firstjobdt,Contractend_firstjobdt,act_job_freq_daysbtw,0);
var contractID = $('#contractID').val();
var act_job_freq_contract = $("#act_job_freq_contract option:selected").val();
$.ajax({
type: "POST",
url: 'activity_submitted',
data: {
//here i need to pass date and frequency. insert to table like one by one row
getcontract_id: contractID,
getcontractbranch_firstjobdt: act_contractbranch_firstjobdt,
//etc....
},
success: function(data) {
alert('success')
}
})
PHP MODAL FUNCTION
$data_jobschedule = array(
'Contract_id' => $this->input->post('getcontract_id'),
'job_freq_id' => $this->input->post('getcontractbranch_freq')
);
$insert_id = 0;
if ($this->db->insert("job_schedule", $data_jobschedule))
$insert_id = $this->db->insert_id();
}

Please find the jQuery Ajax code here
Inside while loop
var dataArray = [];
while(condition) {
details = [];
//do your calculations
details['date'] = date;
details['frequency'] = frequency;
dataArray[] = details;
}
$.ajax({
url: "<?php echo site_url('activity_submitted'); ?>",
data: {dateArray: dataArray},
success: function(data){
alert('success');
},
error: function() { alert("Error."); }
});
In the controller and model, you need to get the data and insert it into the table.
$data = $_REQUEST['dateArray'];
$this->db->insert_batch('mytable', $data);

Related

AJAX returns only last array item

I want to create async AJAX query to check server status when web page finish loading. Unfortunately when it comes to data display from processed PHP, I receive only single value.
JS:
<script>
window.onload = function() {
test();
};
function test()
{
var h = [];
$(".hash td").each(function(){
var hash = $(this).closest('#h').text();
if (hash) {
$.ajax({
url: 'stat.php',
method: 'POST',
async: true,
data: {hs: JSON.stringify(hash)},
success: function(data) {
$('.result').replaceWith(data);
}
});
}
});
}
</script>
PHP:
<?php
require_once ('inc/config.php');
require_once ('inc/libs/functions.php');
if (isset($_POST['hs'])) {
$hash = json_decode($_POST['hs']);
serverstatus($hash);
}
function serverstatus($hash) {
$address = DB::queryFirstRow("SELECT address,hash FROM servers WHERE hash=%s", $hash);
$address_exploded = explode(":", $address['address']);
$ip = $address_exploded[0];
$port = $address_exploded[1];
$status = isServerOnline($ip,$port);
if ($status) {
$s = "Online $ip";
} else {
$s = "Offline";
}
echo $s;
}
?>
I embed result from PHP to a table row. I see that AJAX iterating over the array, but all rows receive same value (last checked element in array).
$('.result') matches all elements with the class result. replaceWith will then replace each of them with the content you provide.
If you want to only affect the .result element within some structure (perhaps the same row?), you need to use find or similar:
function test()
{
var h = [];
$(".hash td").each(function(){
var td = $(this); // <====
var hash = td.closest('#h').text();
var result = td.closest("tr").find(".result"); // <====
if (hash) {
$.ajax({
url: 'stat.php',
method: 'POST',
async: true,
data: {hs: JSON.stringify(hash)},
success: function(data) {
result.replaceWith(data); // <====
}
});
}
});
}
Obviously the
var result = td.closest("tr").find(".result"); // <====
...will need to be tweaked to be what you really want it to be, but that's the idea.
This line in your question suggests an anti-pattern:
var hash = $(this).closest('#h').text();
id values must be unique in the document, so you should never need to find the one "closest" to any given element. If you have more than one id="h" element in the DOM, change it to use a class or data-* attribute instead.
Thank you all for help. My final, obviously very dirty but working code:
function testServerPage()
{
var h = [];
$(".hash li").each(function(){
var hash = $(this).closest('#h').text();
if (hash) {
$.ajax({
url: 'stat.php',
method: 'POST',
//async: true,
data: {hs: JSON.stringify(hash)},
success: function(data) {
$('#' + hash).replaceWith(data);
}
});
}
});
return false;
}
I just added dynamic variable to element:
success: function(data) {
$('#' + hash).replaceWith(data);
}

Using AJAX to post data into API

I have a script that uses AJAX to comunicate with PHP based API.
First part loads trade history:
$(document).ready(function () {
var orders = $('#History ul');
var user = "<?php echo $user; ?>";
$.ajax({
type: "GET",
url: "api.php",
data: {
user: user
},
success: function (response) {
console.log(response);
var res = JSON.parse(response);
$.each(res, function (index, value) {
console.log(value);
if(value['PL']>=0){
orders.append("<li style=\"color:green;\">" + value['User'] + "</li>");
}else{orders.append("<li style=\"color:red;\">" + value['User'] + "</li>");}
});
}
});
Second part posts a trade to database:
$("#submit").click(function(){
//event.preventDefault();
var oPrice = newOrder.elements["oPrice"].value;
var cPrice = newOrder.elements["cPrice"].value;
var oType = newOrder.elements["oType"].value;;
var oSymbol = newOrder.elements["oSymbol"].value;
var oAmount = newOrder.elements["oAmount"].value;
var json ={
'user': user,
'oPrice': oPrice,
'cPrice': cPrice,
'oType': oType,
'oSymbol': oSymbol,
'oAmount': oAmount};
alert(JSON.stringify(json)); //---check zda je naplněný
$.ajax({
type: "POST",
url: "api.php",
data: json,
success: function (response) {
alert(response);
}
});
});
The problem is, that when i press the button and send json, its missing the 'user' data and looks like this:
TraderBook.php?oPrice=1&cPrice=1&oType=LONG&oSymbol=1&oAmount=1
I have no idea why does ajax exclude it. The json variable has it filled out
I think your problem might be here
$(document).ready(function () {
var user = "<?php echo $user; ?>";
var is the JS scoping declaration. So you're limiting your user value to just the anonymous function being triggered by the page DOM load completing. What you should do is try scoping it outside the function
var user; //global scope
$(document).ready(function () {
user = "<?php echo $user; ?>";
This way, when your $("#submit").click(function() fires, there's a value to feed into your script.
I was wrongchecking the problem a mistook data from a form for the json. Problem was inside the API --> There was a tabulator in a SQL command..
Thanks to everyone for suggestions.

Plot marker for each users location from database IP

I have a users table in my database that stores an ip address.
I have an api that gets the users latitude and longitude.
Firstly, I need to get every users lang and long.
At the moment, my code is only returning the last user in my database's lang and long.
This is my code for trying to return every clients long and langs:
$user_grab = mysqli_query($con, "SELECT * FROM users");
while($users_ = mysqli_fetch_array($user_grab)) {
$username_ = $users_['username'];
$client_ip = $users_['ip'];
//This is for getting each users location on our map
$ip = $client_ip;
$geocode = file_get_contents("http://freegeoip.net/json/{$ip}");
$output = json_decode($geocode);
$client_latitude = $output->latitude;
$client_longitude = $output->longitude;
}
Then I return this to my home PHP page using:
$response = array('client_latitude'=>$client_latitude,'client_longitude'=>$client_longitude);
echo json_encode($response);
I recieve the AJAX request with the following JS / JQUERY code:
<script>
function fetchOnline() {
$.ajax({
url: "includes/get_dash_settings.php",
context: document.body,
type: 'POST',
data: {get_data:true},
success: function(value) {
var data = JSON.parse(value);
$('#lat').html(data['client_latitude']);
$('#long').html(data['client_longitude']);
},
complete:function(){
setTimeout(fetchOnline,5000);
}
})
}
$(document).ready(function() { setInterval(fetchOnline,5000); });
</script>
And then finally, I try and display these in div's for testing.
Eventually, I want them to go in to the jVectorMap Markers JS code so It can plot markers on my map from each users lang and long.
But for now, It's not getting each users lang and long. Only the last user in my database's.
UPDATED CODE
The code Sumarai posted below isn't working.
It is not updating the div id - all-the-coordinates.
Does anyone know what's wrong with my version ?
I am using some different code to the question I asked. I have been using it from the start but didn't post it here because I didn't think it would be this difficult.
My new script is the same but I am calling them in separate files now because I am already calling an array in my other file (get_dash_settings).
This is my script in my main PHP file:
<script>
function fetchOnline() {
$.ajax({
url: "includes/get_dash_settings.php",
context: document.body,
type: 'POST',
data: {get_data:true},
success: function(value) {
var data = JSON.parse(value);
$('#totalUsers').html(data['totalUsers']);
$('#totalOnline').html(data['totalOnline']);
$('#freeModeStatus').html(data['freemode']);
$('#bypassesStatus').html(data['bypasses']);
$('#isOnline').html(data['client_is_online']);
},
complete:function(){
setTimeout(fetchOnline,5000);
}
});
$.ajax({
url: "includes/get_dash_map.php",
context: document.body,
type: 'POST',
data: {get_data_:true},
success: function(value_) {
const data_ = JSON.parse(value_);
const $parent = $('#all-the-coordinates');
for (const row of data) {
const $element = $('<span></span>');
$element.text(`${data_['client_latitude']}, ${data_['client_longitude']}`);
$parent.append($element);
}
},
complete:function(){
setTimeout(fetchOnline,5000);
}
});
}
$(document).ready(function() { setInterval(fetchOnline, 5000); });
</script>
My get_dash_map.php:
$user_grab = mysqli_query($con, "SELECT * FROM users");
$response = [];
while($users_ = mysqli_fetch_array($user_grab)) {
$client_ip = $users_['ip'];
//This is for getting each users location on our map
$ip = $client_ip;
$geocode = file_get_contents("http://freegeoip.net/json/{$ip}");
$output = json_decode($geocode);
$client_latitude = $output->latitude;
$client_longitude = $output->longitude;
$response[] = ['client_latitude' => $client_latitude,'client_longitude' => $client_longitude];
}
echo json_encode($response);`
Since you want to get a bunch of coordinates back, it makes sense to return them in an array of sorts. You are currently only getting the last one, because you are overwriting the values. Make an entry, then add that entry to the response as an array item. You can easily create a new array item with the [] suffix. $response[] = $x will add an array item to $response containing $x.
$user_grab = mysqli_query($con, "SELECT * FROM users");
$response = [];
while($users_ = mysqli_fetch_array($user_grab)) {
$client_ip = $users_['ip'];
//This is for getting each users location on our map
$ip = $client_ip;
$geocode = file_get_contents("http://freegeoip.net/json/{$ip}");
$output = json_decode($geocode);
$client_latitude = $output->latitude;
$client_longitude = $output->longitude;
$response[] = [
'client_latitude' => $client_latitude,
'client_longitude' => $client_longitude
];
}
echo json_encode($response);
You obviously need to change your javascript too, as it currently expects an Object back with two keys, but you now get an Array of Objects back.
<script>
function fetchOnline() {
$.ajax({
url: "includes/get_dash_settings.php",
context: document.body,
type: 'POST',
data: {get_data:true},
success: function(value) {
const data = JSON.parse(value);
const $parent = $('#all-the-coordinates');
for (const row of data) {
const $element = $('<span></span>');
$element.text(`${row['client_latitude']}, ${row['client_longitude']}`);
$parent.append($element);
}
}
})
}
$(document).ready(function() { setInterval(fetchOnline, 5000); });
</script>
with in the html
<div id="all-the-coordinates"></div>

How to do the ajax + json using zf2?

i am using zf2. i want to load my second drop down by using the ajax call. i have tried with following code. i can get hard coded values. but i dont know how to add database values to a array and load that values to the drop down using ajax.
Ajax in phtml :
<script type="text/javascript">
$(document).ready(function () {
$("#projectname").change(function (event) {
var projectname = $(this).val();
var projectkey = projectname.split(" - ");
var projectname = {textData:projectkey[1]};
//The post using ajax
$.ajax({
type:"POST",
// URL : / name of the controller for the site / name of the action to be
// executed
url:'<?php echo $this->url('userstory', array('action'=>'answer')); ?>',
data:projectname,
success: function(data){
//code to load data to the dropdown
},
error:function(){alert("Failure!!");}
});
});
});
</script>
Controller Action:
public function answerAction() {
// ead the data sent from the site
$key = $_POST ['textData'];
// o something with the data
$data= $this->getProjectTable ()->getkeyproject( $key );
$projectid = $data->id;
$projectusers[] = $this->getRoleTable()->fetchRoles($projectid);
// eturn a Json object containing the data
$result = new JsonModel ( array (
'projectusers' => $projectusers
) );
return $result;
}
DB query :
public function fetchRoles($id) {
$resultSet = $this->tableGateway->select ( array (
'projectid' => $id
) );
return $resultSet;
}
your json object new JsonModel ( array (
'projectusers' => $projectusers
) json object become like this format Click here for Demo
var projectkey = [];
projectkey = projectname.split(" - ");
var projectname = { "textData" : "+projectkey[1]+" };
$.ajax({
type:"POST",
url : "url.action",
data : projectname,
success : function(data){
$.each(data.projectusers,function(key,value){
$('#divid').append("<option value="+key+">"+value+"</option>");
});
});
});
<select id="divid"></select>
This is what i did in my controller. finaly done with the coding.
public function answerAction() {
// ead the data sent from the site
$key = $_POST ['textData'];
// o something with the data
$data= $this->getProjectTable ()->getkeyproject( $key );
$projectid = $data->id;
$i=0;
$text[0] = $data->id. "successfully processed";
$projectusers = $this->getRoleTable()->fetchRoles($projectid);
foreach ($projectusers as $projectusers) :
$users[$i][0] = $projectusers->username;
$users[$i][1] = $projectusers->id;
$i++;
// eturn a Json object containing the data
endforeach;
$result = new JsonModel ( array (
'users' => $users,'count'=>$i
) );
return $result;
}
and the ajax is like this
<script type="text/javascript">
$(document).ready(function () {
$("#projectname").change(function (event) {
var projectname = $(this).val();
var projectkey = projectname.split(" - ");
var projectname = {textData:projectkey[1]};
//The post using ajax
$.ajax({
type:"POST",
// URL : / name of the controller for the site / name of the action to be
// executed
url:'<?php echo $this->url('userstory', array('action'=>'answer')); ?>',
data:projectname,
success: function(data){
// alert(data.users[0][0]+" - " + data.users[0][1] );
var count= data.count;
alert(count);
$('#myDropDown').empty();
for(var i=0;i<count;i++){
$('#myDropDown').append($('<option></option>').attr('value', data.users[i][1]).text(data.users[i][0]));
}
},
error:function(){alert("Failure!!");}
});
});
});
</script>
used the same zf2 query to access the database. thanks for the help everyone :)

Pass Array FROM Jquery with JSON to PHP

hey guys i read some of the other posts and tried alot but its still not working for me.
when i alert the array i get all the results on the first site but after sending the data to php i just get an empty result. any ideas?
$(document).ready(function() {
$('#Btn').click(function() {
var cats = [];
$('#cats input:checked').each(function() {
cats.push(this.value);
});
var st = JSON.stringify(cats);
$.post('foo.php',{data:st},function(data){cats : cats});
window.location = "foo.php";
});
});
Php
$data = json_decode($_POST['data']);
THANK YOUU
my array looks something like this when i alert it house/flat,garden/nature,sports/hobbies
this are a couple of results the user might choose (from checkboxes).
but when i post it to php i get nothing. when i use request marker (chrome extension) it shows me something likethat Raw data cats=%5B%22house+themes%22%2C%22flat+items%22%5D
i also tried this way-- still no results
$(document).ready(function() {
$('#Btn').click(function() {
var cats = [];
$('#cats input:checked').each(function() {
cats.push(this.value);
alert(cats);
$.ajax({
type: 'POST',
url: "foo.php",
data: {cats: JSON.stringify(cats)},
success: function(data){
alert(data);
}
});
});
window.location = "foo.php";
});
});
php:
$json = $_POST['cats'];
$json_string = stripslashes($json);
$data = json_decode($json_string, true);
echo "<pre>";
print_r($data);
its drives me crazy
Take this script: https://github.com/douglascrockford/JSON-js/blob/master/json2.js
And call:
var myJsonString = JSON.stringify(yourArray);
so now your code is
$(document).ready(function() {
$('#Btn').click(function() {
var cats = [];
$('#cats input:checked').each(function() {
cats.push(this.value);
});
var st = JSON.stringify(cats);
$.post('foo.php',{data:st},function(data){cats : cats});
// window.location = "foo.php"; // comment this by this page redirect to this foo.php
});
});
//and if uou want toredirect then use below code
-------------------------------------------------
$.post('foo.php',{data:st},function(data){
window.location = "foo.php";
});
---------------------------------------------------
Php
$data = json_decode($_POST['data']);
var ItemGroupMappingData = []
Or
var ItemGroupMappingData =
{
"id" : 1,
"name" : "harsh jhaveri",
"email" : "test#test.com"
}
$.ajax({
url: 'url link',
type: 'POST',
dataType: "json",
data: ItemGroupMappingData,
success: function (e) {
// When server send response then it will be comes in as object in e. you can find data //with e.field name or table name
},
error: function (response) {
//alert(' error come here ' + response);
ExceptionHandler(response);
}
});
Try this :-
$data = json_decode($_POST['data'], TRUE);
I think you should move the "window.location = " to the post callback, which means it should wait till the post finshed and then redirect the page.
$.post('foo.php', {
data : st
}, function(data) {
window.location = "foo.php";
});

Categories

Resources