Passing JavaScript array from view to Laravel controller - javascript

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.

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

Activate and run a jQuery script using a value from a Django view?

On a Django template I have a form that allows users to upload images to a remote server. Once the upload is complete, the server returns the url to the image to my Django view. I have this image url as a string in my view.
How can I use this url to activate and be used in a jQuery script? I'd like to append it a form without refreshing the page. I'm pretty sure I'm supposed to be returning a JsonResponse and using an Ajax sciprt, but I am pretty new to this and am having a hard time getting it working. I'm not getting any errors from the Ajax script, and I can see the img_url is in the JsonResponse content, but when I upload a file, nothing happens. This is the relevant bits to what I have so far:
Django View:
else:
img_form = forms.PostImageForm(request.POST, request.FILES or None)
if img_form.is_valid():
new_img = models.PostImage.objects.create(post=post)
new_img.file = request.FILES['file']
new_img.save()
img_url = new_img.file.url
return JsonResponse({'img_url': img_url})
HTML/Ajax:
<script>
function append_form() {
$.ajax({
method: "POST",
url: "/blogs/{{topic}}/{{post_url}}/edit_post/",
data: {},
success: function(){
var contentField = $("#myPostForm textarea[name=content]");
contentField.val( contentField.val() + "<img src='" + data.img_url + "' >" );
}
})
};
</script>
You need to pass the JSON result to your success function like so:
success: function(resultData){
var contentField = $("#myPostForm textarea[name=content]");
contentField.val( contentField.val() + "<img src='" + resultData.img_url + "' >" );
}
Forthermore, you can delete the data: {}, line from your AJAX request since you aren't passing anything to your API. That line is the data you would be passing. The parameter in the success function is the data you are receiving.

Joomla & JS; Sending data from form to Controller

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.

How to POST with AJAX using just an a tag

I have an a tag that is dynamically generated with database content, it includes a data-target that I capture in javascript when it is clicked on, this is an example of one of the generated buttons:
Edit
Simple, right?
Now, what I do in the JS when it is clicked, is as so:
var $this = $(this),
$target = $this.data("target"),
$endpointURL = "";
$endpointURL = $target.split("?id=")[0];
$id = $target.split("?id=")[1];
This allows me to set the endpoint I want, in out example above, it would be "edit" and also set the id which is just a number at this point.
Now, I have to POST this ID to the edit endpoint to return the right info, correct?
So, here is my AJAX for that:
$.ajax({
type: "POST",
data: '{"id": ' + $id + ' }',
url: "../assets/scripts/php/" + $endpointURL,
success: function (data) {
$("#content-lockup").html(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log("error: " + textStatus + ", error thrown: " + errorThrown);
}
});
This does not throw an error and does indeed output a var dump of the $_POST array as I have set it to, however it doesnt contain my ID that I passed over, here is the code on the endpoint and a screenshot of the output:
<?php
var_dump($_POST);
?>
Why would the vardump on $_POST not contain the id that I passed over in the apparently successful AJAX request?
What I expect is that I can say on the endpoint, something like:
$id = $_POST['id'];
Maybe its something obvious that i'm doing wrong but yeah, any ideas?
it's because you are passing a string to data that isn't form encoded
Make it an object and jQuery will encode it for you
data: {"id": $id },
If it's a string it needs to be in format
data: 'id=' +id + '&someOtherParam=' + somevar

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);

Categories