Laravel AJAX: insert with loop (looping DB table row) - php

I'm new in Laravel and Ajax, and I have working code (see below).
I have 2 tables, criteria and rating.
I want to query first the table named:criteria like (select * from criteria where level = 1),
then using the result, I want to save multiple rows in "ratings" using some field of query result + some input variable from user.
Like this:
for (i = 0; i < criteria-result.length; i++) {
$addItem= New Rating;
$addItem->empname = $request->empname; //this is from user this is a repeating value
$addItem->criteria = criteria-result[i].(criteria)
}
Existing Ajax:
$.ajax({
type: 'POST',
url: 'generate-rating-criteria',
data: {
'employee_name': $("#emp_name").text(),
},
success: function()
{
swal("Saved", "Ok", "success")
},
error: function(xhr, status, error)
{
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
Existing Controller:
$addItem= New Rating;
$addItem->employee_name = $request->employee_name;
$addItem->save();

You can just use a count() method instead of length.
$criteria = DB::table('criteria')->where('level', 1)->get();
for ($i = 0; $i < count($criteria); $i++) {
$addItem= New Rating;
$addItem->empname = $request->empname;
$addItem->criteria = $criteria[$i]->criteria; /* if criteria column exist in the rating table. */
$addItem->save();
}

Related

Flot.js with php and mysql not working with time

I have a system trying to display a graph of a count over time using flot js. The issue I am having is that the graph isnt actually rendering any lines. I have cast the time to UTC and multiplied by 1000 as suggested in other posts but to no avail. Does anyone have any idea what I am doing wrong?
PHP:
public function liveGraphAjax()
{
$query = "SELECT
time as time,
COUNT( id ) as count
FROM table
WHERE HOUR( TIME ) = HOUR( CURRENT_TIME ) -1
GROUP BY DATE_FORMAT(`time`, '%H:%i')";
$result = DB::select($query);
if(isset($result))
{
$temp = array();
foreach ($resultas $row )
{
$temp [] = array(
'time' =>strtotime($row->time) * 1000,
'count' =>(int) $row->count,
);
}
}
return Response::json($temp);
}
JS:
var options = {
colors : [$UpdatingChartColors],
xaxis: {
mode: "time",
timeformat:"%hh:%mm"
},
series: {
lines: { show: true },
points: { show: true }
},
};
$("button.dataUpdate").click(function ()
{
data = [];
$.plot("#updating-chart", data, options);
function fetchData()
{
function onDataReceived(series)
{
var res = [];
data = [series];
for (var i = 0; i < data[0].length; ++i)
{
res.push([data[0][i].time,data[0][i].count]);
}
console.log(res);
$.plot("#updating-chart", res, options);
}
$.ajax({
url: "liveGraphAjax",
type: "GET",
dataType: "json",
success: onDataReceived
});
}
});
The fetchData() function is never called so you never get data.
In your onDataReceived() function the res variable contains only one data series. You have to change your call to $.plot("#updating-chart", [res], options);

GET key value from AJAX response

I'm making a cross domain call to a php which returns this:
response=2&count=15&id=84546379&firstname=adsa&emailstatus=
I want to pick out the values of response and id, but not sure how, my code is as follows:
**
xhr.request({
url: "../promo_getstate2.php",
method: "POST",
data: {
email: emailaddress,
country: country,
lang: lang,
source: '1312_XMAS_dly'
}
}, function(response){
getstate = response['response'];
regID = response['id'];
console.log(getstate)
console.log(regID)
})
but it's not geting those values. How do I do this?
The response is:
" response=2&count=15&id=84546379&firstname=adsa&emailstatus="
**
What you can do is create a params object of all parameters in the response as shown below:
function parseResponse(str) {
var arr = str.split("&");
var temp, params = [];
for(var i = 0; i < arr.length; ++i) {
temp = arr[i].split("=");
params[temp[0]] = temp[1];
}
return params;
}
var values = parseResponse("response=2&count=15&id=84546379&firstname=adsa&emailstatus=")
You can then access values as:
values['response']; // 2
values['id']; // 84546379
Code as that:
<Script language="javascript">
var vars=GetRequest("response=2&count=15&id=84546379&firstname=adsa&emailstatus=");
document.write(JSON.stringify(vars));
function GetRequest(v) {
var url = "?"+v;//location.search;
var theRequest = new Object();
if (url.indexOf("?") != -1) {
var str = url.substr(1);
strs = str.split("&");
for(var i = 0; i < strs.length; i ++) {
theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);
}
}
return theRequest;
}
</script>
Then you can get the values. For example, the json of the result is
{"response":"2","count":"15","id":"84546379","firstname":"adsa","emailstatus":""}

How to send my json array to sevaral rows in my sql database

I got several elements called workers, they all got an id, position left, and position top.
I have made it to an array and then made it to a json object, which a would like to send to my database. but when i test it, in the controller and model, it says the value is null.
what to do?
the first function:
function GetUnitInfo(){
for(i=0 ; i < $('.Worker').length ; i++){
$('.Worker').each(function(){
aUnitsInfo = [{'unitid':$(this).attr("id"),
'unitposleft':$(this).position().left,
'unitpostop':$(this).position().top
}];
jUnitsInfo.push(aUnitsInfo[i]);
aUnitsInfo = JSON.stringify(jUnitsInfo);
console.log(i);
});
console.log("unitinfo: "+jUnitsInfo[i].unitid);
console.log("uniposleft: "+jUnitsInfo[i].unitposleft);
console.log("unitpostop: "+jUnitsInfo[i].unitpostop);
console.dir(jUnitsInfo[i]);
}
}
in my log i see 3 objects with the correct values.
then i want to send it to the database:
setInterval(function(){
SaveUnits();
function SaveUnits()
{
GetUnitInfo();
$sLoginEmail = $('#TxtLoginEmail').val();
// TODO: Check that the email is valid
// console.log("The email is:"+$sLoginEmail);
$.ajax({
type: 'post',
url: 'bridge.php',
data: {"sFunction":"SaveUnits", "unitsInfo":jUnitsInfo[i]},
success: function(data){
console.log(data);
$oXml = $(data);
}
});
}
},5000);
And here's where it get's tricky. I know from the first function that my jUnitsInfo[i] is containing the right objects but after this part it seems to be null.
this is my bridge:
if($_POST['sFunction'] == "SaveUnits")
{
require_once 'Controllers/UserController.php';
$oUnitsInfo = new USerController();
echo $oUnitsInfo->SaveUnits($_POST['unitsInfo']);
}
The Controller:
public function SaveUnits($unitsInfo)
{require_once 'Models/UserModel.php';
$oUserModel = new UserModel();
$unitsInfo = json_decode($unitsInfo);
$saveUnits = $oUserModel->SaveUnits($unitsInfo);}
and the model:
public function SaveUnits($unitsInfo){
// Create connection
$con = mysqli_connect("localhost","root","","awesomegame");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$unitsInfo = array();
foreach( $unitsInfo as $row ) {
$sql[] = '("'.mysql_real_escape_string($row['unitId']).'", '.$row['unitPosTop'].','.$row['unitPosLeft'].')';
}
mysql_query('INSERT INTO units (unitid, unitpostop, unitposleft) VALUES '.implode(',', $sql));}}
And when i var dump it in the controller
var_dump(json_decode($unitsInfo));
it just comes back with a null.
how do i send the array correctly? - and get the values written to the database on drifferent rows (one for each worker).
It seems like
jUnitsInfo[i]
is reasonable since you are out of the for loop.
Take the code
function GetUnitInfoAndSave(){
var jUnitsInfo=[];
$('.Worker').each(function(){
var aUnitsInfo ={'unitid':$(this).attr("id"),
'unitposleft':$(this).position().left,
'unitpostop':$(this).position().top
};
jUnitsInfo.push(aUnitsInfo);
});
for(var i=0 ; i < jUnitsInfo.length ; i++){
var $sLoginEmail = $('#TxtLoginEmail').val();
// TODO: Check that the email is valid
// console.log("The email is:"+$sLoginEmail);
var data=$.extend({},{sFunction:"SaveUnits"},jUnitsInfo[i]);
$.ajax({
type: 'post',
url: 'bridge.php',
data: data,
success: function(data){
console.log(data);
$oXml = $(data);
}
});
//console.log("unitinfo: "+jUnitsInfo[i].unitid);
//console.log("uniposleft: "+jUnitsInfo[i].unitposleft);
//console.log("unitpostop: "+jUnitsInfo[i].unitpostop);
//console.dir(jUnitsInfo[i]);
}
}
setInterval(GetUnitInfoAndSave,5000);
PS: $.Ajax and setInterval functions are asynchronous, so you don't know when data are really sent to the server. (This code sends the array items one after another)

Having Multiple Variables in POST search?

I'm trying to do a Jquery Ajax search with multiple conditions, and this is my first time. I did some research and found ways to send data to a php file, however it's only with one variable. I'm not sure how to implement all of my 6 variables into data: data.
here they are:
var FromDate
var ToDate
var MusicStyles
var Locations
var FromPrice
var ToPrice
Now here is where I got stuck, I should do a post with some data. When I have multiple variavbles, can I do data: dataFromDate, dataToDate, dataMusicStyles,?
$("#SearchButton").click(function() {
var dataFromDate = 'dataFromDate='+ FromDate;
var dataToDate = 'dataToDate='+ ToDate;
var dataMusicStyles = 'dataMusicStyles='+ MusicStyles;
var dataLocations = 'dataLocations='+ Locations;
var dataFromPrice = 'dataFromPrice='+ FromPrice;
var dataToPrice = 'dataToPrice='+ ToPrice;
$.ajax({
type: "POST",
url: "do_search.php",
data: dataFromDate, dataToDate, dataMusicStyles, dataLocations, dataFromPrice, dataToPrice,
beforeSend: function(html) { // this happens before actual call
$("#results").html('');
$("#searchresults").show();
$(".word").html(searchString);
},
success: function(html){ // this happens after we get results
$("#results").show();
$("#results").append(html);
}
});
});
Where the MySQL would look like this:
<?php
//if we got something through $_POST
if (isset($_POST['dataFromDate'])) {
include('db.php');
$db = new db();
// never trust what user wrote! We must ALWAYS sanitize user input
$word = mysql_real_escape_string($_POST['search']);
$word = htmlentities($word);
// build your search query to the database
$sql = "SELECT
events.ID,
events.EVENT_NAME,
events.start_datetime,
events.end_datetime,
events.VENUE_LOCATION,
events.ENTRANCE_PRICE,
venues.VENUE_NAME,
GROUP_CONCAT(music_styles.MUSIC_STYLE_NAME) AS MUSIC_STYLE_NAME
FROM events
INNER JOIN venues
ON events.VENUE_LOCATION = venues.ID
INNER JOIN events_music_styles
ON events.ID = events_music_styles.event_id
INNER JOIN music_styles
ON events_music_styles.music_style_id = music_styles.id
WHERE start_datetime >= '$phpFromDate'
AND end_datetime <= '$phpToDate'
AND ENTRANCE_PRICE >= '$phpFromPrice'
AND ENTRANCE_PRICE <= '$phpToPrice'
GROUP BY events.ID";
// get results
$row = $db->select_list($sql);
if(count($row)) {
$end_result = '';
foreach($row as $r) {
$result = $r['title'];
// we will use this to bold the search word in result
$bold = '<span class="found">' . $word . '</span>';
$end_result .= '<li>' . str_ireplace($word, $bold, $result) . '</li>';
}
echo $end_result;
} else {
echo '<li>No results found</li>';
}
}
?>
I am 100% certain that it doesn't work like this, but I think I got it almost right. I would love it if someone could at least please let me know what I could do to fix the code.
Thanks!
You send it as an object, like so:
$.ajax({
type: "POST",
url: "do_search.php",
data: {dataFromDate : FromDate,
dataToDate : ToDate,
dataMusicStyles : MusicStyles,
dataLocations : Locations,
dataFromPrice : FromPrice,
dataToPrice : ToPrice
},
beforeSend: function(html) { // this happens before actual call
$("#results").html('');
$("#searchresults").show();
$(".word").html(searchString);
},
success: function(html) { // this happens after we get results
$("#results").show();
$("#results").append(html);
}
});​
Where the firs value is the key, and the second is the value, so {key: value} would be accessed on the server as $_POST['key'], which your values would be accessed the way you seem to want :
$_POST['dataFromDate']
Also, you don't need all those variables at the start, just use them directly in the object.
Try to concatenate your strings with a "," and explode them on the server.

AJAX: Problems returning multiple variables

First off sorry if I'm missing something simple just started working with AJAX today. I have an issue where I'm trying to get information from my database, but different records have different amounts of values. For instance, each record has a "features" column. In the features column I store a string. (ex: Feature1~Feature2~Feature3~Feature4... ) When I'm building the object I take apart the string and store all the features into an array. Some objects can have 1 feature others can have up to whatever. So... how do I return this values back to my ajax function from my php page? Below is my ajax function that I was trying and I'll provide a link with my php file. [ next.php : http://pastebin.com/SY74jV7X ]
$("a#next").click(function()
{
$.ajax({
type : 'POST',
url : 'next.php',
dataType : 'json',
data : { nextID : $("a#next").attr("rel") },
success : function ( data ) {
var lastID = $("a#next").attr("rel");
var originID = $("a#next").attr("rev");
if(lastID == 1)
{
lastID = originID;
}
else
{
lastID--;
}
$("img#spotlight").attr("src",data.spotlightimage);
$("div#showcase h1").text(data.title);
$("div#showcase h2").text(data.subtitle);
$("div#showcase p").text(data.description);
$("a#next").attr("rel", lastID);
for(var i=0; i < data.size; i++)
{
$("ul#features").append("<li>").text(data.feature+i).append("</li>");
}
/*
for(var j=1; j < data.picsize; j++)
{
$("div.thumbnails ul").append("<li>").text(data.image+j).append("</li>");
}
*/
},
error : function ( XMLHttpRequest, textStatus, errorThrown) {
$("div#showcase h1").text("An error has occured: " + errorThrown);
}
});
});
First replace the below in your next.php file:
for ( $i=0; $i < $arraySize; $i++ )
{
$return['feature'.$i.''] = $features[0];
}
With:
$return['features'] = $features;
P.S: the current code is wrong you should have ... = $features[$i]; anyway, you don't need that just send the array as is. and then in the JS part replace:
for(var i=0; i < data.size; i++)
{
$("ul#features").append("<li>").text(data.feature+i).append("</li>");
}
With:
$.each(data.features, function(k,v){
var li = '<li>' + v + '</li>';
$("ul#features").append(li);
});
This way, don't need the data.size anymore.

Categories