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.
Related
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.
So here I am posting my first PHP function that I am proud of but I just recently learned about AJAX and wanted to test it out. Unfortunately I can't get it to work.
My experience: PHP (3 weeks). CSS3, HTML, Basic Javascript.
My Problem: Getting AJAX to work. I want ajax to get my data from the php file which gets the votes from my test server (Xampp) database. So each time the user clicks on good or bad AJAX should display the new results without refreshing the page. The issue is however that: A) My if statements work by checking isset($_POST) which wont work anymore if I call by AJAX. B) Preventing refresh. C) Making AJAX update after every click. I know im nearly there, im just missing something and I dont know exactly what it is to be honest.
What I tried: Checked my database connection. Checked if my php code worked without ajax and it does perfectly fine (I am just displaying half of the functionality here, a lite version, for the sake of simplicity). Tried to change submit to button. Cache clearing. Jquery is in the head of my document and the path is correct. Watched tutorials and read the documentation but I am just not heading anywhere, probably due to lack of experience.
Edit: Sessions and everything php works fine. I my session start and database connection are included on the very top.
Summary: How do I fix this ajax so that it always updates my numbers?
Let me know if you want me to explain parts of my php code. Im willing to comment the parts if neccesary.
JQUERY / AJAX CODE
function vote() {
var request = $.ajax({
url: "php/core/voting_system.php",
type: "POST",
dataType: 'html'
});
request.done(function(vote_sum) {
$("#votes").html(vote_sum);
});
}
HTML CODE:
<div id='votes'></div>
<form id="good" action="" method="post">
<input type="submit" name="good" onclick="vote()" value="+">
</form>
<form id="bad" action="" method="post">
<input type="submit" name="bad" onclick="vote()" value="-">
</form>
In HTML you don't need <form>, you are doing it with AJAX, right?
<div id='votes'></div>
<button onclick="vote('good');">+</button>
<button onclick="vote('bad');">-</button>
In JavaScript, it is easier to use post rather than ajax function
function vote(gb) {
$.post("php/core/voting_system.php", { vote: gb }, function(vote_sum) {
$("#votes").html(vote_sum);
});
}
In PHP, extract the vote and use it as needed (add validation/sanitation):
$vote = $_POST['vote']; // either 'good', or 'bad'
// do what you need with it
TL;DR version:
You didn't include a data field inside your $.ajax call. Also, your script isn't checking which button was pressed.
The long version
When you're performing your $.ajax call, you fail to attach any data to the request. This can be done easily like so:
$.ajax({
method: 'POST',
dataType: 'json',
data: ...someJSONData...
});
Usually, you're going to want to pass JSON to anything, because it can contain complex object structures that you would usually want to communicate between the client and the server. You're clearly not in this example, but if you're trying to learn this stuff, it's better to start off the right way.
Both javascript and php make using the JSON format extremely easy: JS JSON.stringify() and JSON.parse(), PHP json_encode() and json_decode().
function vote(e) {
// e.target.id stores the id of the button that was clicked
var data = {vote: e.target.id}
$.ajax({
method: 'POST',
dataType: 'json',
data: JSON.stringify(data),
... callbacks and other properties ...
});
}
document.getElementById("good").addEventListener("click", vote);
document.getElementById("bad").addEventListener("click", vote);
This would be a simple example of how you could solve your problem. If you did a simple var_dump in your php script after running the data through json_decode() you would get a nice associative array:
[
'data' => 'good',
]
I hope this illustrates how easy it is to pass data around in this format.
Also notice I defined the event handlers in the javascript. This is generally better, because you keep all your javascript in one place and it makes things cleaner and easier to debug.
Like Jay said you're not sending POST data through the AJAX. You also need to echo your results from PHP.
function vote(event) {
event.preventDefault();
$.ajax({
url: "php/core/voting_system.php",
type: "POST",
dataType: 'html',
data: 'bad='+$('input[name="bad"]').val()+'&good='+$('input[name="good"]').val(),
success: function(data){
var votes = $("#votes").val().empty();
$("#votes").html(data+votes);
}
]);
}
I've got this problem that the form refreshes on submit, i dont want it to refresh but i do want it to submit. any of you know what i could do ?
click this link to an older post about this.
<form method="post" id="radioForm">
<?
foreach($result as $radio):
printf('
<button type="submit"
href="#radio"
name="submitRadio"
value="'.$radio['id'].'">
Go!
</button>
');
endforeach;
?>
</form>
<script type="text/javascript">
$('#radioForm').submit(function(event) {
event.preventDefault();
$.ajax({
url:'index.php',
data:{submitRadio:[radiovalue]},
type:'POST',
success:function(response) {
/* write your code for what happens when the form submit */
});
});
</script>
</div>
Use submit() handler and pass the value of your button to your other script
First set the id on the form.
<form method="post" id="formId">
Then bind a listener
$( "#formId" ).submit(function( event ) {
event.preventDefault();
//This is where you put code to take the value of the radio button and pass it to your player.
});
To use this you need jQuery.
You can read more about this handler here: http://api.jquery.com/submit/
This is the default behavior of a HTML <form> on submit, it makes the browser POST data to the target location specified in the action attribute and loads the result of that processing to the user.
If you want to submit the form and POST the values behind the scenes without reloading the page, you have to disable the default behavior (the form submit) and employ the use of AJAX. This kind of functionality is available readily within various JavaScript libraries, such as a common one called jQuery.
Here is the documentation for jQuery's AJAX functionality http://api.jquery.com/jquery.ajax/
There are lots of tutorials on the interwebs that can introduce you to the basic use of jQuery (Including the library into your HTML pages) and also how to submit a form via AJAX.
You will need to create a PHP file that can pick up the values that are posted as a result of the AJAX requests (such as commit the values to a database). The file will need to return values that can be picked up within your code so that you know if the request was un/successful. Often the values returned are in the format JSON.
There are lots of key words in this answer that can lead you on your way to AJAX discovery. I hope this helps!
use ajax like this of jquery
$('form').submit(function(event) {
event.preventDefault();
$.ajax({
url:'index.php',
data:{submitRadio:[radiovalue]},
type:'POST',
success:function(response) {
/* write your code for what happens when the form submit */
}
});
});
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.
I'm writing a game in html5 and using wordpress for the rest of the site. I want users to be able to save their progress, but I'm not clear on how the architecture looks.
I would just do an ajax call to a php page that access the database, but I feel like using the existing wordpress database and API is the correct thing to do. Not only that, but using the wordpress api will give me access to things like nonce.
That said, do I write a wordpress plugin to do this? How do I properly execute the save request from the javascript that runs my game?
In your js file, do your ajax request like this:
jQuery.post('path/to/wp-admin/admin-ajax.php', {action:'save_progress',other_parameter:'other_value'}, function(response) {
// let your user know if his progress is saved or not
});
add this to your theme's functions.php:
function save_progress() {
global $wpdb;
// do the saving job with received parameters here
die(); // this is necessary
}
add_action('wp_ajax_save_progress', 'save_progress');
If you're interested in a more generalizable solution than what the wordpress API allows (for more overall understanding), below is a simple, but complete demo:
Here's the HTML:
<input id="posted_data" ></input>
<button id="saveBtn">Save</button>
Here's the JS:
$(document.body).on('click', '#saveBtn', function(){
var posted_data=$('#posted_data').val();
var url="/submit_page.php";
$.ajax({url: url, data: {posted_data:posted_data }, type: "POST",
success: function(response){
//do something with the `response` data
} //success
}); //ajax
}); //.saveEditBtn
Here's the submit_page.php:
$posted_data=$_POST['posted_data'];
$posted_data; //do something with this variable, like insert it into a database
echo "Success"; // this will be the `response` variable in the JS above.