Laravel use AJAX to append view - php

I am just wondering how I can append a view within Laravel to my page using AJAX.
So when I didn't use Laravel I would have just done something like this:
$.ajax({
url: "your.html",
success: function (data) { $('body').append(data); },
dataType: 'html'
});
That would have then appended my html file to the current page. I am just wondering what is the cleanest way to do this with a Laravel View?
UPDATE: I forgot to mention that the View in question would be a html form. Nothing resource heavy.

So with the laravel you goes like this:
$.ajax({
url: "get-form",
success: function (data) { $('body').append(data); },
dataType: 'html'
});
Now in your routes.php you define:
Route::get('get-form', function() {
return view('form');
});
And your view file let's say: form.blade.php:
<form action="...">
(...) // here goes form
</form>
This should create an ajax request/response relation on the page. Each time you call ajax request new form will be rendered into body.

Let's assume you have your form hardcoded but hidden in html (could also be included via blade)
<div id="my-hidden-form" style="display:none;">
<form ...>
<!-- form goes here -->
</form>
</div>
<div id="my-forms"></div>
Then you could simply clone your hidden form to create new ones
$( "#my-hidden-form form" ).clone().appendTo( "#my-forms" );
Without knowing further details it's still hard to tell if this matches all your requirements. However, it will dynamically add forms (as you needed) and in addition it will not require an ajax call or mess up your html.
Using blade to include the form this will be even more structured.

Related

How to populate a dropdown list with a locally stored JSON file

Below is my JSON File , I am using Laravel and also i'm wondering where is the correct practice to store my json file.
{
"people": [
"john",
"jim",
"mark"
]
}
What I am currently looking to achieve is populate a dropdown list as shown below also.
<form method="POST" action="/Update">
#csrf
<select name="dropdown" id="dropdown" onchange="this.form.submit()">
</select>
</form>
Here is my jquery script how I have tried doing it however i'm getting a 404 HTTP error. Also as I noted above where do you think I should store the json file locally within my project folder.
$(document).ready(function() {
var people = "storage/people.json";
$.getJSON(people, function (data) {
$.each(people,function(iIndex, sElement) {
$('#dropdown').append('<option>' + sElement + '</option>');
});
});
});
In Laravel, page contents such as scripts, styles, images, etc. are usually stored in the public folder. So I would suggest you store your JSON file in the 'public' folder.
Testing your code gave some errors and a quick fix to your code is provided below:
$(document).ready(function() {
var people = "/document/people.json";
$.getJSON(people, function (data) {
data.people.forEach(function(value, index){
$('#dropdown').append('<option>' + value + '</option>');
});
});
});
This adjustment to your jquery code works and the placement of the json file is public/document/people.json
Create a symlink from your public to your storage
ln -s storage/app/public public/storage
and use asset('storage/your.json')
Laravel routes.php
Route::get('/json/people', 'JsonController#people')->name('json.people');
Run artisan command in your laravel root project
php artisan make:controller JsonController
In your JsonController
Create a method called people
public function people(Request $request)
{
$data = file_get_contents(asset('storage/your.json'));
return response()->json(['data'=> $data]);
}
Change your Jquery for Ajax request
$.ajax({
url: "/json/people",
data: {"_token": //you need to add a CSRF Token to your form. Fetch it via JQuery to add it here and send with your Ajax}
}).done(function(data) {
console.log(data);
// once you confirm your JSON data is here, do what you wish to achieve! :)
});
As for the CSRF, if you prefer, you can add it as a meta tag and use that in your Ajax as stated below:
<meta name="csrf-token" content="{{ csrf_token() }}" />
Then before your Ajax call, add a setup for your Ajax:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
If you decide to use the Meta Tag approach for the CSRF then you can scrap out the datavariable from your Ajax call:
$.ajax({
url: "/json/people"
}).done(function(data) {
console.log(data);
// once you confirm your JSON data is here, do what you wish to achieve! :)
});

phpgrid - change edit route

I am using phpgrid in a Slim Framework integration and I see all the editing and creating functionality of the phpgrid system sends the data to a file called "edit.php" that sits inside the phpgrid folder.
Is there any way that I can change that and actually route the result of the form to a different file, preferably a controller in Slim?
L.E: It's worth to mention that I am not using a DB connection to process the data. Instead, I use an API to fetch and process my data, and I feed the data to phpgrid in an array.
Google "phpgrid save local array" gives this post
Save Local Data Array Back to Server via Ajax
You can use submit the changes in jQuery ajax post to whatever url of your choice
Demo
<script src="http://malsup.github.com/jquery.form.js"></script>
<form id="admin_form">
<div>
<input type="submit" value="Submit Local Changes">
</div>
</form>
<script>
$(function() {
// bind to the form's submit event
$('#admin_form').submit(function(event) {
$(this).ajaxSubmit({
type: 'post',
dataType:'json',
url:'save_local_array.php',
data:{
langArray:[] //leave as empty array here
},
beforeSubmit: function(arr, $form, options){
options.langArray = $('#data1').jqGrid('getRowData'); //current
console.log(JSON.stringify(options.langArray));
// return false; // here to prevent submit
},
success: function(){
// add routine here when success
}
});
// return false to prevent normal browser submit and page navigation
return false;
});
});
</script>
It seams that on closer inspection to the documentation, somewhere hidden without the ability to clearly search for it, there is a method called: set_js_editurl().
This method lets you set your own URL and everything else works the same :)
Happy coding,
Ares D.

Access JavaScript functions from scripts loaded from ajax

I have a project in PHP using CodeIgniter in an HMVC approach.
Now, I run into a problem where I'm really confused what to do next.
Here's my situation:
I have a view which looks like this:
//logs_v_month.php
<div id="logs" class="tab-pane active">
</div>
<script type="text/javascript">
$(function(){
$.ajax({
url: "<?php echo load_global_assets('system/js/log.js')?>",
dataType: "script",
success: function(e){}
});
});
</script>
Then I have a controller:
//view.php
function display_logs_month(){
$data['logs_v'] = $this->load->view('logs_v_month');
echo json_encode($data);
}
Then I have another view which is the main view.
//logs.php
<div class="tab-content" id="logs_content">
<!--logs loaded via ajax call-->
</div>
<script type="text/javascript">
function view_month(group_id, start_end){
$.ajax({
type : "POST",
dataType: "json",
url : "<?=base_url()?>logs/view/display_logs_month",
data : {"group_id" : group_id},
success : function (data){
$("div#logs").remove();
$("#logs_content").append(data.logs_v);//logs_v
},
error : function(data){
console.log(data);
}
});
}
The logs.php view has an ajax call to load the logs_v_month.php view through the view.php controller.
My question is, how do I access JavaScript functions (which are also loaded via ajax) from the logs_v_month.php from the logs.php view?
I've tried searching for the answer on the web and most answers people give is using the eval() function but many discourages from using that.
Is there a way I can restructure or rearrange my JavaScript so it will be easy for me to access them in this kind of situation? I'm also taking into account Namespacing if this can help the problem.
I just started learning CI and HMVC so I'm fairly new to this.
Thanks!
You need to put the returned scripts into the DOM for the page.
when you get the script data back in the success method of your ajax call, you can create a script element with the code inside it and append it to the DOM, something like:
success:function(data){
var scriptElement = document.createElement('script');
scriptElement.setAttribute('type', 'text/javascript');
scriptElement.textContent = data;
var head = document.getElementsByTagName('head').item(0);
head.appendChild(scriptElement);
}
Now the functions will be accessible to all scripts.

ajax jquery search form in PHP

This is my form:
<form id="submitsearch" action="Classes/system/main/searchresult.php" method="POST">
Search by <span style="font-size:15px;">(developer, specialization, profession,major)</span>
<input type="text" name="searchbox" id="searchbox" />
in
<select style="text-align:center;" name="countrysearch" id="countrylist">
<option selected="selected" value="0">None</option>
<option value="1">USA</option>
</select>
<input style="margin-left:25px;" id="submitSearch" type="submit" value="Search"/>
</form>
and this is the Ajax jquery code:
$("#submitSearch").click(function(){
$.ajax({type:'POST', url: 'Classes/requests/search.php', data:$('#submitsearch').serialize(), cache: false, success: function(response) {
$('#submitsearch').find('#pagePanel').html(response);
});
Why isn't it working ? The php file is returning the correct result normaly.
But i want it to load inside another div with an id "pagePanel" without reloading, using ajax.
Any help ? I'm new to Ajax.
Edit:
$("#submitbutton").click(function(){
$.ajax({type:'POST', url: 'Classes/system/main/searchresult.php', data:$('#submitsearch').serialize(), cache: false, success: function(response) {
$('#pagePanel').html(response);
}})});
This worked out with me.
Thanks for all your help.
If you have a input of type submit, it will, guess what :), submit the form, and therefore reload the page. Turn it into:
<input style="margin-left:25px;" id="submitSearch" type="button" value="Search"/>
Then make sure you actually have a pagePanel element in your html.
And now a couple of suggestions:
don't id your form #submitsearch and the button as #submitSearch... confusion may arise
you can use AJAX's .load() instead of .ajax() to get directly the result in the DIV:
So:
$("#pagePanel").load('Classes/requests/search.php', {$('#submitsearch').serialize()});
If you want to use ajax in the form submition you'll need to cancel it.
$("#submitSearch").click(function(event){
$.ajax({type:'POST', url: 'Classes/requests/search.php', data:$('#submitsearch').serialize(), cache: false, success: function(response) {
$('#pagePanel').html(response);
});
event.preventDefault();//prevents submitting of the form
}
First you need to stop the default form submittal. return false in the submit handler to stop default. Just use the ID of the element without using find() to insert data into. The elemnt you are trying to find doesn't appear in your html though within the form where your code suggests it should be
$("#submitSearch").click(function(){
$.ajax({type:'POST',
url: 'Classes/requests/search.php',
data:$('#submitsearch').serialize(),
cache: false,
success: function(response) {
$('#pagePanel').html(response);
}
})
return false;
});
After pushing the submit button, the default behaviour is to submit the form and indeed go to the action URL you provided to your form. Now, you want to prevent that behaviour. This means, you'll have to look at the onsubmit event of the form, and prevent the actual submission. jQuery has a preventDefault() method to do this.
In your case, all you'll have to do is add the following code:
$(document).ready(function() {
$("#submitsearch").on("submit", function (e) {
e.preventDefault();
});
});
And here is a jsFiddle to demonstrate it.
You can obviously do the same thing to your submit button, just add the e variable as the argument to your click event and use e.preventDefault() to cancel the actual submit (but you can still perfectly do the AJAX request).
First of all, you are missing a few closing parenthesis and curly brackets. Be sure to run your dev tools in your browser to check console for errors like that. I normally don't use $.ajax...I usually use $.post, but using what you have so far, I would rewrite to something closer to:
$("#submitsearch").submit(function(){
var submitData = $(this).serialize();
$.ajax(
{
type:'POST',
url: 'Classes/requests/search.php',
data: submitData,
cache: false,
success: function(response) {
$('#pagePanel').html(response);
}
}
);
return false;
});​
Instead of sending back loads of HTML to the page, you could just send results in form of a set of JSON objects and then dynamically create the HTML based on the results, this means a lot less data being sent back to the browser which is quicker and more efficient.

Using ajax for form submission with multiple forms generated by php on page

I have a page with multiple forms that do the same thing, acting as a like button for each post in the page, and right next to it the number of likes inside a div named "likes".$id, so I can identify where to write the likes count after the ajax call. I was trying to use jQuery ajax function, but I couldn't set what div to write the results of the function.
$.ajax({
type:'POST',
url: 'likepost.php',
data:$('#like').serialize(),
success: function(response) {
$('#like').find('#likediv').html(response);
}
});
And how would I access the data on likepost.php? I am terrible with javascript, so I hope someone could help me and explain how the jQuery function really works, because I've been copying and pasting it without really knowing what I was doing.
Would this work?
$(function () {
$("#likebutton").click(function () {
var id = $('input[name=id]'); // this is me trying to get a form value
$.ajax({
type: "POST",
url: "likepost.php",
data: $("#like"+id).serialize(), // the form is called like+id e.g. like12
success: function(data){
$("#likes"+id).html(data); // write results to e.g. <div id='likes12'>
}
});
});
});
I put this in the code but when the button is clicked, the usual post refreshing page is done. Why is that?
Making a mini-form, serializing it, and POSTing it seems like a lot of heavy lifting when all you really want to do is send the ID to the likepost.php script.
Why not just retrieve the ID and post it to the script?
First let's break down your function:Type is the type of the request we're making, you specified POST here. This means in your PHP file you'll access the data we're sending using $_POST. Next up is URL which is just the url of where you're sending the data, your php file in this case.
After that is data, that is the data we're sending to the url (likepost.php). You're serializing whatever has a ID of "like" and sending it to the php file. Finally success is a function to run once the request is successful, we get a response back from the PHP and use it in the function to output the response.
As for the multiple forms I'd recommend doing something like:
http://www.kavoir.com/2009/01/php-checkbox-array-in-form-handling-multiple-checkbox-values-in-an-array.html
Here's documentation on the stuff we talked about, if you're every confused about jquery just break it down and search each part.
http://api.jquery.com/serialize/
http://api.jquery.com/jQuery.ajax/
you can try :
function submitform(id) {
var jqxhr = $.post('./likepost.php',$("#"+id).serialize(), function(data) {
$("#"+id).find('#likediv').html(data);
}, "json")
return false;
}
in form:
<form method="post" id="likeForm" onsubmit="return submitform(this.id);">
<input..... />
<input type="submit" value="Submit" />
</form>
in likepost.php add first line:
if ($_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest") {
header("location: " . $_SERVER['HTTP_REFERER']);
exit();
}
you can see more : http://api.jquery.com/serialize/
working for me.

Categories