Joomla & JS; Sending data from form to Controller - javascript

I am having trouble with a form I created and trying to redirect the data someplace else by a JavaScript method that I call whenever the submit button is clicked.
The first thing that is happening, is that the form is created and filled in, then the user will click on the HTML generated button with this action in it:
onclick="javascript:saveEssayScore(<?php echo $key . "," . $pid; ?>);"
Secondly the script file is read and performed. The code is below:
<script type="text/javascript" language="javascript">
document.body.className = document.body.className.replace("modal", "");
function saveEssayScore(key, pid){
var user_id = document.getElementById("user-"+key).value;
console.log("user " + user_id);
var grade = document.getElementById("grade-"+key).value;
console.log("grade " + grade);
var teacher_answer = document.getElementById("feedback-"+key).value;
console.log("teacher_answer " + teacher_answer);
var question_id = document.getElementById("question-"+key).value;
console.log("question_id " + question_id);
var quiz_id = document.getElementById("quiz-"+key).value;
console.log("quiz_id " + quiz_id);
var req = new Request.HTML({
method: 'post',
url: "<?php echo JURI::base();?>index.php?option=com_guru&controller=guruAuthor&task=saveFeedback&tmpl=component&format=raw",
data: { 'pid' : pid, 'user_id' : user_id, 'grade' : grade, 'teacher_answer' : teacher_answer, 'question_id' : question_id, 'quiz_id' : quiz_id},
onSuccess: function(response, responseElements, responseHTML){
alert('yeyy');
}
}).send();
}
Now in the URL, it is read to run the method (task) saveFeedback() in the controller guruAuthor which is in the component com_guru.
The problem I am having is, how do I read the data that I just send through the HTML request? I am trying stuff like $user_id = JRequest::getVar("user_id"); But whenever I'm trying to echo or dump, it is returned to me but empty. Not the values that I am dumping in JavaScript console.log(user_id);

JRequest is deprecated
Use JInput instead. Read - Retrieving request data using JInput
In your mentioned code - if the controller function is being called, try this code-
$jinput = JFactory::getApplication()->input;
$user_id = $jinput->get('user_id', '', 'INT');
I hope this helps.

Related

Laravel form select onChange value save to databse via AJAX

I have a dropdown list generated by the following code in controller (FocalController.php):
$focalData = DB::table('role_users')->orderBy('users.id','DESC')
->leftJoin('users', function($join){
$join->on('role_users.user_id', '=', 'users.id');
$join->on('role_users.role_id', '=', DB::raw("'1'"));
})
->select('users.id',DB::raw('CONCAT(users.name) AS focal'))
->groupBy('users.id')
->get();
foreach($focalData as $data):
$focals[$data->id] = $data->focal;
endforeach;
in the view, I have the following block generating the drop-down list:
{!! Form::select('focal', [''=>'select focal']+ collect($focals)->toArray() , $project_focal, array('class' => 'form-control','onchange'=>'changeFocal(this, '.$project->id.')' ))!!}
I want to submit the drop-down value onChange and save the value using AJAX.
My ajax for the form submission is following:
function changeFocal(e,project_id) {
var focal_id = $("#e").val();
var project_id = $("#project_id").val();
$.ajax({
type: "PUT",
data: "focal_id=" + e + "&project_id=" + project_id,
url: "{{ URL::to('admin/focal') }}",
success:function(data){
console.log(data);$("#msg").html("New Focal Assigned.");
}
});
}
My route is:
Route::post('admin/focal/','FocalController#saveFocal');
the saveFocal function in my FocalController is:
public function saveFocal(Request $request){
$focal_id = $request->focal_id;
$project_id = $request->project_id;
$project = Project::find('idea_id', $project_id)
->update([
'focal' => $focal_id,
'updated_at' => \Carbon\Carbon::now()->toDateTimeString(),
]);
#\App\Common::createAccessLog($project->focal, "Update Project Focal for Project#" . $project->idea_id . "(" . $project->name . ")");
return view('admin/focal');
}
I am getting the following error in console:
Can anyone please tell me what am I doing wrong and how can I save the select data to database with ajax along with a success message.
Use POST instead of PUT
Also make sure the route you are sending your request to is valid and exists
Below are few corrections:
function changeFocal(e,project_id) {
var focal_id = $(e).val(); //correction
var project_id = $("#project_id").val();
$.ajax({
type: "PUT",
data: "focal_id=" + focal_id + "&project_id=" + project_id, //correction
url: "{{ URL::to('admin/focal') }}",
success:function(data){
console.log(data);$("#msg").html("New Focal Assigned.");
}
});
}
Ude where Clause instead find
Project::where(
find works on primary key

Undefined Index : PHP variables passing by AJAX

I would like to send my php variables and input file by AJAX with something like this ..
$(document).ready(function(){
$("#submit").click(function(){
//var formData = new FormData($('form#data')[0]);
var chaID = "<?php echo $chaID; ?>";
var row_number = "<?php echo $row_number; ?>";
var tag = "<?php echo $tag; ?>";
var data = '&chaID=' + chaID + '&row_number=' + row_number + '&tag=' + tag;
//Returns successful data submission message when the entered information is stored in database.
$.ajax({
type: "POST",
url: "ajax_challenge.php",
data : data,
cache: false,
success: function(result){
$('#level').modal('show');
},
contentType: false,
processData: false
});
return false;
});
});
My formData is working fine so let's focus on var data. When I run this function the ajax_challenge.php response "undefined index" but in request part it shown &chaID=7&row_number=2&tag=6 so it should work.
Maybe I did something wrong with php?
$chaID = $_POST['chaID'];
$row_number = $_POST['row_number'];
$tag = $_POST['tag'];
Additionally, is there anyway to mix formData + data correctly?
EDIT . the screenshots of browser's console
response screenshot
request
EDIT2 -----------------------------------------------------------
The thing is, it's gonna work if I remove
contentType: false,
processData: false
but the problem is If I deleted it also can't pass var formData input:file through URL. What do I suppose to do ?
I think I see what is going on, you're passing the GET parameters wrong to the data variable.
From my understanding of how jQuery appends GET parameters, the fix would be
'?chaID=' + chaID + '&row_number=' + row_number + '&tag=' + tag
If this doesn't solve it, try checking the console for errors or try to console.log the values. Also make sure you're encodeURI the values before putting them in the URL.
Also, it's better practice to make an array with the GET values and pass them instead to the data variable of the jQuery.ajax() function, as it does the string conversion for you automatically, try doing that instead, it might just solve the problem. ;)
You can find the documentation for the AJAX functions of jQuery and EncodeURI here:
http://api.jquery.com/jquery.ajax/
http://www.w3schools.com/jsref/jsref_encodeURI.asp
EDIT: I noticed you're using the POST method, in that case then pass the array of posted values to the data parameter and it should work. Only include the variable values however. Example array:
data = [chaID, row_number, tag];
Pass an array to the data parameter, and it should post the values just fine. Also, try to include in your question a screenshot of the console network tab, which tells us if something is going wrong. Also a console screenshot.
EDIT2: Okay, here are my observations: ProcessData will process the object, therefore it makes sense formData won't work. Try appending the other array:
data = [chaID, row_number, tag];
for (var i = 0; i < formData.length; i++) {
data.append('formData[]', formData[i]);
}
EDIT3: This should work. Just modify your PHP and JS this way:
var data = formData;
var params = $.param({"chaID": chaID, "row_number": row_number, "tag": tag});
//Returns successful data submission message when the entered information is stored in database.
$.ajax({
type: "POST",
url: "ajax_challenge.php?" + params,
data : data ,
and PHP:
$chaID = $_GET['chaID'];
$row_number = $_GET['row_number'];
$tag = $_GET['tag'];
Because you put your php variable to your script. And php compile your code first your javascript run:
var chaID = "<?php echo $chaID; ?>";
var row_number = "<?php echo $row_number; ?>";
var tag = "<?php echo $tag; ?>";
var data = '&chaID=' + chaID + '&row_number=' + row_number + '&tag=' + tag;
And so, you have not click, $_POST['chaID'] and another $_POST variable is not defined.
If you are using $_POST method in ajax no need to start param data with &
var data = '&chaID=' + chaID + '&row_number=' + row_number + '&tag=' + tag;
Replace with:
var data = 'chaID=' + chaID + '&row_number=' + row_number + '&tag=' + tag;
Also check values in php what are you getting by using print_r($_POST);

Passing JavaScript array from view to Laravel controller

I am trying to pass objs array to a function in Laravel controller using ajax. I am not recieving any data after the post.
<script>
var itemCount = 0;
var objs=[];
$(document).ready(function(){
var temp_objs=[];
$( "#add_button" ).click(function() {
var html = "";
var obj = {
"ROW_ID": itemCount,
"STREET_ADDRESS": $("#street_address").val(),
"CITY": $("#city").val(),
"ZIP": $("#zip").val()
}
// add object
objs.push(JSON.stringify(obj));
itemCount++;
// dynamically create rows in the table
html = "<tr id='tr" + itemCount + "'><td>" + obj['STREET_ADDRESS'] + "</td> <td>" + obj['CITY'] + " </td> <td>" + obj['ZIP'] + " </td><td><input type='button' id='" + itemCount + "' value='remove'></td> </tr>";
//add to the table
$("#multiple_table").append(html)
// The remove button click
$("#" + itemCount).click(function () {
var buttonId = $(this).attr("id");
//write the logic for removing from the array
$("#tr" + buttonId).remove();
});
});
$("#submit").click(function() {
$.ajax({
url:'/app/Http/Controllers/Search/search_address',
type: 'POST',
dataType:'json',
contentType: 'application/json',
data: objs
});
});
});
</script>
In my controller function is like this
public function search_address(){
$data = json_decode($_POST['data'], true);
print_r($data);
}
I guess that I am having a problem with the url in ajax and I am not sure how a controller's url is obtained.
Thank you
Can you change:
$data = json_decode($_POST['data'], true);
to:
$data = json_decode(Input::get('data'));
and make sure you have: use Input; above your class extends Controller
See if that works.
Edit: Also make sure your routes (in the Controllers folder) are correct.
You should console.log() your javascript by placing the following in you ajax post:
error : function(e){
console.log(e);
}
You can then see what errors you are getting in your browsers' developers tools panel.
You should also be aware that that Laravel posts require a csrf token unless you have explicitly turned them off, which means you will need to add this token in to your post as well. So you should end up with:
$("#submit").on('click', function() {
$.ajax({
url:'/app/Http/Controllers/Search/search_address', // Is this what you meant, is this the route you set up?
type: 'POST',
data: {'data': objs, '_token' : '<?=csrf_token()?>'},
success : function(data){
// Do what you want with your data on success
},
error : function(e){
console.log(e);
}
});
});
Notice that I've embedded php inside the javascript, which is just to illustrate the point. Ideally javascript is kept in it's own files, so you would then need to find a way to pass this token through. I personally use knockoutjs for this type of thing (AngularJS is also popular), but you can easily do something like:
<input type="hidden" id="_token" value="{{ csrf_token() }}" />
in your HTML, then pull this value from inside your ajax request:
data: {'data': objs, '_token' : $('#_token').val()}
EDIT
I've just noticed your url, it looks like you are trying to access the controller directly. You need to set up a route in your routes.php file, such as:
Route::post('/searchAddress', 'YourController#search_address');
Then use:
url: /searchAddress
in your ajax request.

If condition not working in model of codeigniter

I am trying to implement a "like" button for my website. I am using Codigniter, Ajax and Jquery. When the like button is clicked data should be entered to database and if unlike button is pressed data should delete from database. But I am facing a problem in model, data is not added to database when I click like button. Please help me to find a solution.
This is my Jquery file "likeitem.js"
function likeItem(postId)
{
if ($("#likeItem_"+postId).text() == "Like")
{
$("#likeItem_"+postId).html('Unlike');
var purpose = "Like";
}
else
{
$("#likeItem_"+postId).html('Like');
var purpose = "UnLike";
}
$.ajax({
type : "POST",
url : "http://localhost/codeig_smarty/index.php/user/likeItem",
data : "postId=" + postId + "purpose=" + purpose,
success : function()
{
}
});
return false;
}
This is my model "usermodel.php"
public function itemLike()
{
$id = $this->session->userdata('userID');
$postId = $this->input->post('postId');
$purpose = $this->input->post('purpose');
if($purpose=="Like")
{
// echo 'test';
// exit();
$data = array(
"userID" => $id,
"postTextID" => $postId,
);
$this->db->insert('like', $data);
}
else
{
echo 'hai';
}
}
This is my view file "home.tpl"
<li><a class="like-unlike" href="#" id="likeItem_{$item['postID']}" onclick="likeItem({$item['postID']})">Like</a></li>
This is my Controller "user.php"
public function likeItem()
{
$this->usermodel->itemLike();
}
You mistake here. You forgot to put & symbol. Try this code.
data : "postId=" + postId + "&purpose=" + purpose,
Full code:
If you want to manipulate result returned from ajax, you can do something on success block as following code :
$.ajax({
type : "POST",
url : "http://localhost/codeig_smarty/index.php/user/likeItem",
data : "postId=" + postId + "&purpose=" + purpose,
success : function(data)
{
// do seomthing here with data
// console.log(data) --> to see data return or not
}
});

AJAX is posting to different PHP pages at the same time

I have a page user.php which is a template for different users pages (e.g. user.php?id=5). I run an AJAX script to monitor the database for new messages posted during a conversation with each user.
My problem is that when I post a message to user.php?id=5 it also appears on user.php?id=1 etc.
How do I ensure the real-time message is only sent to the correct user?
Script in user.php:
var refreshId = setInterval(function () {
$.ajax({
url: 'another_file.php',
data: { 'action': '<?php echo $lastID; ?>' },
dataType: 'json',
type: 'post',
success: function (data) {
var avatar = '<img src="images/avatars/' + data[1].avatar + '"/>';
if (compare_id != data[0].cr_id) {
$('#responses').prepend("<div class='row'><div class='col-xs-12'><div class='post_container_left_small' style='float:left;'><div class='reply_avatar'><div id='add_button_small'>" + avatar + "</div></div><div class='reply_text'><h3><span class='post_time'>now</h3>" + data[0].reply + "</div></div></div></div>");
}
compare_id = data[0].cr_id;
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}
});
}, 7500);
The php class function it calls:
public static function getLast($lastID) {
$lastID = (int)$lastID;
$result = mysql_query("SELECT * FROM mc_conversation_reply ORDER BY cr_id DESC LIMIT 1");
$userC = new UserTools();
while($row = mysql_fetch_array($result)) {
//echo json_encode($row);
$userRObj = $userC->get($row['user_id_fk']);
//echo json_encode($userRObj);
echo json_encode(array($row,$userRObj));
}
}
The whole idea is that the user.php is a common "view" (of the mvc model) for users on your app and that by using query parameters you must fetch information for just that user. You have chosen to use AJAX (wich is js and runs only under the view layer of your app, in this case, the user's browser) and therefore you need to have some js code listening to some action in order to have two things done: Have php controller layer update the query parameter id and after that run the ajax request again to fetch the database data and update the html fields.

Categories