Laravel Eloquent in jQuery Script - php

EDIT
I just realized I didn't post the entire code.
I am using an Ajax live search to retrieves cards when a user types in a part of their last name. When the results appear, a user will click on the row and it will retrieve that cards information.
From there, I want to use the card information to generate additional html.
$.ajax({
type: "get",
url : '{{ route('compare.search') }}',
data: {'search':$(this).val()},
success: function(data) {
$("#suggestion-box-1").slideDown();
$("#suggestion-box-1 tbody").html(data);
$(data).each(function(index){
$("#suggestion-box-1 tbody").append('<tr><td><a href="#" class="player-name" data-card=' + data[index].id + '>' + data[index].first + ' ' + data[index].last + '</a></td><td><span class="card-type"></span>' + data[index].card_type.replace('-', ' ') + '</td><td align="center"><span class="card-overall">' + data[index].overall + '</span></td></tr>');
});
// This is the part that I can't figure out
$('#suggestion-box-1 .player-name').click(function() {
var cid = $(this).data('card');
var card = {!! App\Card::where("id", $cid)->get() !!};
console.log(card);
});
}
});
} else if (len == 0) $('#suggestion-box-1').slideUp();
});
Any sort of help would be greatly appreciated!

That's gonna be impossible without an API since blade won't talk back to the server for that function.
You'll need to create an API endpoint that takes that javascript cid variable and responds with the card information you need.
The flow is blade generates the page THEN the cid variable gets populated in the frontend so cid doesn't exist at the moment the ::where function is called.

Related

Laravel clears session data with ajax get request

I have 2 laravel apps ,currently working on localhost
askspidy (http://localhost/askspidy/public/)
askspidymailer (http://localhost/askspidymailer/public)
In askspidy app, i am using ajax get to fetch the data which is stored in askspidymailer app.
Below is code to fetch the content written in askspidymailer into askspidy app
$.ajax({
url: "http://localhost/askspidymailer/public/get-inbox/1",
dataType: "json",
type:"get",
async: false,
success: function(data)
{
console.log(data);
if(data!='NULL')
{
for (var i=0; i<data.length; i++)
{
var fromName = data[i].fromName;
var fromAddress = data[i].fromAddress;
var subject = (data[i].subject).substr(0,50);
var date = data[i].date;
var row = $('<tr><td><input type=checkbox></td><td class=mailbox-star><a href=#><i class=fa fa-star text-yellow></i></a></td><td class=mailbox-name><a href=# title='+ fromAddress + '>' + fromName + '</a></td><td class=mailbox-subject>' + subject + '</td><td class=mailbox-attachment><i class=fa fa-paperclip></i></td><td class=mailbox-date>' + date + '</td></tr>');
$("#inboxtable").append(row);
}
}
}});
but whenever this code is executed, the askspidy laravel app session data is deleted or session id is modified , not sure
because when i click on any other link in askspidy laravel app or refresh the current page it redirects me to login page automatically.
I am not sure , if it's because we are connecting 2 different laravel apps or what? I have checked that if i use different url here then it works fine , but this url it somehow modifies/deletes session value
This might be affected due to same session cookie name in session config file.
So to prevent this issue change the session cookie name in config/session.php

Cannot pass bootstrap table cell data to php?

I'm developing a web based inventory system. In my project i have a user management page and it has a table to view all the users.
+----------------------------------------+
+ username + user type + + +
+----------+-----------+--------+--------+
+ sample + sample + edit + delete +
+----------+-----------+--------+--------+
+ sample + sample + edit + delete +
+----------+-----------+--------+--------+
+ sample + sample + edit + delete +
+----------+-----------+--------+--------+
It has two buttons to edit user type and to delete user from the database. i need to get username from this table to php script, to execute delete query. I tried this,
$(document).on('click','.remove' ,function(){
var $item = $(this).closest("tr").find('td:eq(0)').html();
console.log($item);
<?php $username = <script>$item</script>?>
});
but i can't pass this 'username' variable to php. How to do this? Thank you :-)
To achieve this you need to perform an ajax request like this:
$(document).on('click','.remove' ,function(){
var $item = $(this).closest("tr").find('td:eq(0)').html();
$.post("url/file.php", { // your php file
username: $item
}, function(data, status){
// you will get response from your php page (what you echo or print)
});
});
PHP side:
$username = $_POST['username'];
//Do whatever you want ...
echo "success";
You can do it by Ajax, this is suggested for your code:
$.ajax({
url: "data.php",//file wich has query select to db table
data: {id:theid},//describe your data here
dataType: 'json',// type of data that will you get (JSON/HTML).
type: 'POST',//sending type (POST/GET)
success: function(data) {
//do change the select option
}
});
Goodluck!

jQuery not generating correct queryString

I have been working on a website that uses a combination of PHP, jQuery, MySQL and XHTML in order to register students for a piano recital. This has no official purpose other than a learning exercise for me in getting all of these to work together. However, I have had a lot of problems getting the PHP to talk with the database and I'm not sure what my problem is. But before that can be tackled there is a really annoying issue that I've run across. For some reason my jQuery is not building a complete post URL for the PHP.
I am using jQuery version: 1.4.2 from Google. The query string is being built by using:
var ajaxOpts = {
type: "post",
url: "../php/addRecital.php",
data: "&performance=" + $("#performanceType :selected").text() +
"&groupName=" + $("#groupName").val() +
"&student1fName=" + $("#firstName").val() +
"&student1lname=" + $("#lastName").val() +
"&student1id=" + $("#studentID").val() +
"&student2fname=" + $("#Second_Student_firstName").val() +
"&student2lname=" + $("#Second_Student_lastName").val() +
"&student2id=" + $("#Second_Student_studentID").val() +
"&skillSelect=" + $("#skillSelect :selected").text() +
"&instrument1=" + $("#instument1 :selected").text() +
"&otherInstrument1=" + $("#otherInstrument1").val() +
"&instrument2=" + $("#Instument2 :selected").text() +
"&otherInstrument2=" + $("#otherInstrument2").val() +
"&location=" + $("#locationSelect :selected").text() +
"&roomNumber=" + $("#roomNumber").val() +
"&time=" + $("#timeSlotSelect :selected").text()
,
success: function(data) { ...
There is more than the above function, but I didn't think that it would pertain to here. I then call the code using:
$.ajax(ajaxOpts);
However, instead of creating the entire query string I get:
http://sterrcs123.mezoka.com/schoolProject/assign/assign13.html?groupName=&firstName=Samuel&lastName=Terrazas&studentID=23-343-3434&Second_Student_firstName=&Second_Student_lastName=&Second_Student_studentID=&otherInstrument=&Second_Student_Instrument=&roomNumber=2
Which as you can tell is missing a number of keys and their values. I would appreciate any help I can get because this is really driving me insane. Thanks.
It appears that your form is simply submitting itself without using your AJAX operation. Did you attach to the form's submit event and THEN run your ajax call? You will also want to return false from the submit event handler to prevent the default behavior you are seeing above.
Example:
$('#formid').submit(function(){
//your ajax code here.
return false;
});
If you're talking to an ASP.Net web service then you would need data to be a JSON string of your arguments. Otherwise, you can pass your data in by using an object literal (truncated for brevity):
var ajaxOpts = {
type: "post",
url: "../php/addRecital.php",
data: {
performance: $("#performanceType :selected").text(),
groupName: $("#groupName").val(),
student1fName: $("#firstName").val(),
student1lname: $("#lastName").val()
},
success: function(data)
}
As per the missing values, make sure you're capturing the button click / form submit.
$('form').submit(function (e) {
$.ajax(ajaxOpts);
return false;
});

JQuery Ajax error

I am posting some form values through ajax to a PHP script. The PHP echoes 1 if it's successful and 2 if not.
The PHP seems to be working ok but I am being redirected to the url in the javascript and shown the number 1 on a blank page instead of it being echoed back to the ajax request.
This is my javascript, can anyone see where I am going wrong?
$(".save").click(function() {
var area = $("input#area").val();
var january = $("input#january").val();
var target = $("input#target").val();
var ach = $("input#achieved").val();
var comments = $("input#comments").val();
var token = "<?php echo $token; ?>";
var dataString = 'area='+ area + '&january=' + january + '&target=' + target + '&achieved=' + ach + '&comments=' + comments + '&ci_token=' + token;
$.ajax({
type: "POST",
url: "review/update-review/<?php echo $yr; ?>",
data: dataString,
success: function(msg) {
if(msg == 1)
{
alert("Your review has been updated.");
}
else
{
alert("There was a problem updating your review. Please try again.");
}
}
});
return false; });
I think the problem may be down to the format of your data parameters. for
type : "POST"
then for
data : "{param1: 'param1', param2: 'param2'}"
do you have a tool like fiddler to view the communications between your browser and server. if not i would recommend downloading fiddler (it's free). it will give you a lot of insight as to what is actually happening behind the scenes and can give invaluable information about what might have gone wrong with an ajax style post.
The code looks pretty much fine to me, including the syntax. Still some possibilities arise, which are:-
The URL for executing the PHP code, which you are using in the example ("review/update-review/<?php echo $yr; ?>"), may be incorrectly given with reference to your current page.
The variables which you are using it here to capture the values of the INPUT elements, may be producing some extra special characters (like "&") which may lead to erroneous processing, resulting in the JavaScript problem.
Hope it helps.
For starters if(msg == 1) will not be == 1 because what your fetching is a string so it would b if(msg == '1').
Where you have
var dataString = 'area='+ area + '&january=' + january + '&target=' + target + '&achieved=' + ach + '&comments=' + comments + '&ci_token=' + token;
Change that to an object like so:
var dataObject = {
area : area,
january : january,
target : target,
achieved : ach,
comments : comments,
ci_token : token
}
and then change it in the ajax request to dataObject
Debug
Firefox: firbug.
if your using chrome hit Ctrl+Shift+J to open the javascript console and debug. look out for all the heaDers and data your sending and you can use console.log(varaible) to track the values of a variable.

Delete a div id using ajax and jquery and delete from DB

I've got several div id's, each containing a different client. I want to be able to click the delete button and using ajax and jquery delete the specific div from the database. I'm getting success in AJAX but it's not deleting anything from the DB. And then obviously, upon deletion, I would like the container to reload dynamically. help!!!
function DeleteClient(){
clientID = $('.clientblock').attr('id')
alert(clientID);
var yes = confirm("Whoa there chief! Do you really want to DELETE this client?");
if (yes == 1) {
dataToLoad = 'clientID=' + clientID + '&deleteclient=yes',
$.ajax({
type: 'post',
url: '/clients/controller.php',
datatype: 'html',
data: dataToLoad,
success: function(html) {
alert('Client' + clientID + ' should have been deleted from the database.');
$('#clientscontainer').html(html);
},
error: function() {
alert('error');
}});};
};
controller.php info //
Variables necessary are:
$deleteClient
$clientID
on the delete click, when being passed through post (via firebug)
clientID = 0
deleteClient = yes
edit: so obviously, it's not getting the correct client ID to delete it to the DB as it is passing through post but I am getting an ajax success call and where i have the client ID variable displaying there, it is picking the correct client ID.
alert(clientID) is pulling in 0 as well.
Any ideas?
dataToLoad = 'clientID=' + clientID + '&deleteclient=yes',
Your controller is getting clientID value of 0.
Track down your clientID javascript variable and see if it is fetching the correct clientID.

Categories