Currently I have a button:
<ul>
<li><button onclick="display('1')">1</button></li>
<li><button onclick="display('2')">2</button></li>
<li><button onclick="display('3')">3</button></li>
</ul>
That when pressed, calls a javascript function, and displays PHP based on which button is pressed using AJAX. I figured this out all on my own. The AJAX gets a PHP file with a postgres query that outputs a table of data to a div.
Now I want to be able to add, via form, new data and have it refresh (without reloading the page, yannknow?). I've tried a couple of things, and have hit roadblocks every time.
My initial idea was to have the form submit the data using a javascript function and AJAX, then call my "display()" function after the query to reload the content. I just can't figure it out using GoogleFu.
Based on my current idea, I'd like help with the following:
How do I pass the form data to a javascript function.
How do I use POST to pass that data to PHP using AJAX?
I'm super new to javascript and AJAX. I've looked into jquery as it seems like that's the way to go, but I can't figure it out. If there's a better way to do this, I'm open to suggestions. Please forgive any misuse of nomenclature.
EDIT: Once I solve this problem..., I'll have all the tools needed to finish the project preliminarily.
This example is copied directly from the jQuery API docs for $.post. When in doubt, first place to look is in the API
http://api.jquery.com/jQuery.post/
Example: send form data using ajax requests
$.post("test.php", $("#testform").serialize(), function(data){
/* success- do something with returned data*/
});
Now extend the concept further and wrap the post in a submit handler for the form
$("#testform").submit(function(){
/* code from above, changing form selector to "this" */
$.post("test.php", $(this).serialize(), function(data){
/* success- do something with returned data*/
});
/* prevent browser default submit*/
return false;
})
Refer to jQuery.post method. It does what you want (sends AJAX request with POST data).
To grab values from inputs, use val() method for nodes that have value (textarea, input, .. )
Related
I'm displaying data from DB like this:
<?php foreach ($r as $k => $v):?>
<div data-role="collapsible" data-mini="true" class="collapsible">
Name: <?=$v['name']?>
</div>
<?php endforeach; ?>
Now when I add new data to DB and the form is submitted, my script redirects back to this page. How do I show the new data immediately without manually refreshing the browser? I usually don't have this issue if I'm not using Jquery Mobile.
You could send the form with jquery ajax
$('form[name="myform"]').submit(function(evt){
evt.preventDefault();
$.post('/my_form_handler.php', $(this).serialize())
.done(function(data){
//Populate dom elements here with new data
}).fail(function(data){
//Handle failed ajax post.
});
});
And then on successful post change the content of the dom-elements.
Not 100% sure i got the right syntax for it but i think it should give you a general idea on how to do it.
The problem here is that the data is hard coded into the page's HTML. After your form submission it's jQueryMobile that's changing the page/view, and no refresh of the page takes place so you're still seeing the same data.
You should refactor to create the loop with JSON data (loaded via AJAX). If the data is cached in a local variable, you can either add to it with the form's data, or make a fresh AJAX call to the server (recommended if you need sorting or filtering).
After reloading the data, the rendering code can be called, showing the new list.
it is easy.
you can send the request to the server using ajax.
and on the server side, you have to make the function to return the data added.
the ajax function will get the success or fail function.
the success function will run if it works.
on the success function , you have to add the content using javascript jquery with the returned data.
Thanks
If I want to do some PHP on an event(e.g. onchange) should I use jQuery ajax like:
$("#elm").on("change", function(){
//ajax code
}
, should I use the PHP in the HTML attribute like:
<element onchange="<?php //stuff to do ?>"></element>
You seem to be conflating two different issues.
JS bound events vs intrinsic event attributes.
Bind your event handlers with JS.
Follow the principles of Progressive Enhancement and Unobtrusive JavaScript.
Ajax vs Putting PHP in a JS function
If you put PHP in a JS function then it will run when the PHP outputs the JS function to the browser, not when the JS function is called.
If you want to run PHP in response to an event, then you have to make an HTTP request to the server to run the PHP.
If you want to insert content from the load of page and leave it static, you should use only PHP.
If you want to insert content dynamically (changing with users interactions) you should use AJAX.
I can't found out what are you trying to achieve with your example, so not very sure what you should do there.
taking your code it would give this :
$("#elm").on("change", function(){
//ajax code
$.get('url', {data:'tosend'}, function(data){
// here you have the response of the php script in the data object
// it can be json for exemple
});
}
You must realise two things, your php code will be render when the page is loaded in the
browser so the second code you gave us
means that your "onchange" event is already present in your page.
If you want to request something (data, html, etc) to server from a loaded page, then do an ajax.
In that case below code is correct.
$("#elm").on("change", function(){
//ajax code
}
You cannot execute a piece of php code from client side. But you can assign values from php to javascript and then do operations on client side.
I have a working PHP registration form that goes through $_POST[] requests to check user inputs.
Username length (3-20)
Username availability
Username /^[A-Za-z0-9_]+$/
etc.
Rather than have it take you to a whole new page to display errors, I want a live request to call for the errors from register.php so they will appear in a div on the registration.
<div id="errors">" . $usernameErrors . "</div>
I've been trying to read up on AJAX but have noticed most codes involve utilizing $_GET[].
What will I have to do to get my current forms integrated with AJAX?
My Current Basic Registration Form Logic:
<form method="post" action="register.php">
<input type="text" name="username" id="username" required />
$usernameErrors
</form>
And register.php contains all of the checks already.
If you're using jQuery, it's pretty simple.
<script type='text/javascript'>
$.post('/register.php',
{username: $('#username').val()
// insert values of other fields here
},
function(response) {
// update your div with errors
$('#errors').html(response);
})
</script>
You should invoke this code, for example, when user changes username in registration form. It will happen in background and update page asynchronously.
Your register.php script should, in this case, emit only errors, not the whole page, or you will see unexpected results. :-)
In order to simplify ajax, you can use jQuery (a very powerful JS lib).
Add jquery***.js to your project and refer it on your page:
<< script type="text/javascript" src="#js/jquery-ui-1.8.16.custom.min.js" />
Then, you create the javascript function that will make the ajax call.
On the ajax call, you specify the php file to call and the function to handle the return of php(callback). On this callback function, you add the error message to body.
function verifyForm(){
$.ajax({
type: "POST",
url: "register.php",
data: "username=NAME_GOT_FROM_FORM_&location=Boston"
}).done(function( returned ) { //the callback
$('#errors').html(returned); // add the string returned to div id=errors
});
}
So, the crux of the problem as you're asking it seems to be that you're (correctly) using a POST request on your register form, but your tutorials all want to use GET. Here's a discussion about the difference between the two methods:
http://thinkvitamin.com/code/the-definitive-guide-to-get-vs-post/
If you're actually registering the user with AJAX (rather than just validating) you should be submitting the AJAX request as a POST. If you're using jQuery, the answer has already been given. If you're not using jQuery, then look for the XMLHttpRequest object in your tutorial, and where its "open" method is called (reference here: http://www.w3.org/TR/XMLHttpRequest/). The first parameter of that function is a request method--change it to "post" rather than "get", and the request will be treated like a POST, which register.php expects.
That being said, it sounds like you just want AJAX to validate the form. In that case, GET is the correct verb to use--all you want to do with AJAX is check data against the database, not actually make a change to data. I would suggest that you actually write a new PHP script like validate_registration.php that will perform only the validation logic in register.php, and then return a JSON array of errors (which would be empty if no errors occurred). You can activate/deactivate your form submit button based on that return value, and let the user submit the form just like your old workflow if everything is okay.
The tl;dr here is that you should read up on what makes $_GET and $_POST different, and then write an AJAX-specific validation script so that you're separating the data-retrieval part of your process from the data-insertion part. Once you understand the difference, the rest should follow.
I have a form rendered in the view which action is setted to the same page /index. <form action="" name="formRegistro" id="formRegistro"> and a JQuery function which is called when the form is submitted
$('#formRegistro').submit(function() {
// Retrevies data from the form
data = $('#someInput').val()
//Execute AJAX
$.get(
'http://localhost/myproject/',
{ data },
function(data){
$('#divStatus').html(data);
}
);
//Prevent page loading
return false;
});
I'm using and if statement in the IndexController to change between normal view and post view if ($this->_request->isGet()) { and I'd like to output a message in the #divStatus but with I don't know how to do it
Ok, first off. A normal HTTP request is always a GET request, so your condition would always be true (isGet())
what do you mean you want to output a message in the #divStatus ? That seems to be what you're doing with the callback function.
Are you using Firebug? It's a Very NECESSARY tool for working with ajax requests.
Download and install it for firefox, then do the following:
Press the new firebug button at the bottom of the screen
reload your page
try submitting the form
watch the console as your ajax request gets displayed down there
find out what's happening by using Firebug
I recommend using the $.ajax() function with jquery instead of the $.get() function. You'll have more control.
If you want to display a message from the ajax request in your script when it loads, you could parse the data output of the success callback function - or you could make the function return a json object.
I hope this helps. Good luck :)
With ZF there is a very cool way to manage AJAX & "normal" requests within the same Controller class.
It is based on the fact that most JS framework send the X-Requested-With: XmlHttpRequest HTTP header.
Take a look at AjaxContext and ContextSwitch in Zend Controller Action Helpers
If you want to use jQuery to show this message, you can inject text/html into another html element with the appendTo() function, like this:
$('My Message').appendTo('#divStatus');
I'm building a page which loads the contents of our MySQL db for editing. Each row of the table is in a seperate, editable textarea on the page. I need the user to be able to update each row (ie send it's contents to the db) without reloading the whole page, with a click of a button that's responsible for that specific textarea.
I understand that such procedure would involve some JavaScript, but sadly I know none - I did all I could with php, so I need a pointing in that direction. Basically my question (I think) is how do I grab a text from an edited textarea and send it to MySQL without reloading the page. If I'm heading in the wrong direction I'd be more than willing to hear other suggestions.
Yes this will require javascript. Namely an async call to a PHP page you have. This is often called AJAX.
I hate to be the "use jquery" answer here but the hump of learning jQuery to use AJAX based calls is very low to the value you gain from calls like this.
The documentation has great examples and most of them are quite simple.
That's precisely what AJAX does: Asynchronous JavaScript and XML. It lets you send requests to the server without reloading the page.
I'd recommend starting with jQuery which you'll notice has a lot of support in the StackOverflow community, as well as elsewhere, and which makes cross-browser AJAX requests very easy.
With the jQuery script on your page, you can do something like this:
$("#id-of-the-button-the-user-will-click").click(function() {
$.post('/path/to/your/script.php', { field1: value1, field2: value2 }, function(data) {
// This function is called when the request is completed, so it's a good place
// to update your page accordingly.
});
});
Understanding the details will still require a thorough understanding of JavaScript, so really the best thing to do is dive in and start writing (and thus learning) a lot of JavaScript. AJAX is a fine place to start.
There is a good introduction to JavaScript at Opera. Jibbering covers the use of the XHR object, which is the usual way to send data to the server without leaving the page. Libraries such as YUI or jQuery can do some of the heavy lifting for you.
What you're looking for is AJAX. jQuery makes a lot of that easier; try starting here.
You can add JavaScript event to textarea:
onblur="sendUpdate(this.value)"
This event will happen when user has finished editing the text and leaves the input.
In example, "this" references current textarea component.
And then use Ajax, as previously mentioned. An example would be:
function sendUpdate (text) {
$.post('script.php', {textarea_value:text},function(){});
}
You need to make asynchronous calls to server from your script (javascript).Use ajax to achieve this.You need to have a look at using XMLhttp objects to communicate with the server /database from your client side script (javascript) . You need not submit the entire page using a button click,instead you can invoke the javscript code in a button click event or a onBlur event or a onTextChange event etc...
jQuery is a javascript framework library which helps you to reduce the number of lines of code to implement this. But its not necessary that you need to use jquery .You can do ajax calls without using jquery.Usage of jQuery will reduce the number of lines.
Check this
http://docs.jquery.com/Ajax/jQuery.ajax
You will definitely require JavaScript, and some method of sending a HTTP request to your PHP server without reloading the page. Generally, this is called AJAX.
It is probably best to use a JavaScript library, as AJAX is a bit complicated for beginning JavaScript developers. A good choice is JQuery, or MooTools
AJAX libraries usually use XMLHttpRequest or JSONP to implement the HTTP requests. Understanding those should make it a bit easier.
JQuery AJAX: http://docs.jquery.com/Ajax
MooTools AJAX: http://mootools.net/docs/core/Request/Request
Selecting the textarea element, updating it, would require use of the DOM (http://www.w3.org/DOM/). Most JavaScript frameworks now use an implementation of CSS or XSLT selectors to query the DOM.
JQuery Selectors: http://docs.jquery.com/Selectors
MooTools Selectors: http://mootools.net/docs/core/Utilities/Selectors
You can do this fine without JavaScript. Just have each textarea+button in its own <form>, then submit the form to a script that updates the database from the textarea value, and returns a:
204 No Content
status instead of 200 OK and a new page. The old page will stay put.
You can start by adding a jquery function to pick up any changes made ie:
$('#inputelement').on('input propertychange', function(){
alert("Alert to test jquery working");
});
You should then use AJAX to create a php script with the data (as php is how you update to the server) and send using either a GET or POST variable. Then use that script file to upload the changes to your server. e.g.
$('#yourElement').on('input propertychange', function(){
$.ajax({
method: "POST",
url: "updatedatabase.php",
data: {content: $("#yourElement").val()}
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
Script upload:
session_start();
if(array_key_exists("content", $_POST)){
include("connection.php");//link to your server
$query = "UPDATE `users` SET `updateColumn`= '".mysqli_real_escape_string($link, $_POST['content'])."' WHERE id= ".mysqli_real_escape_string($link, $_SESSION['id'])." LIMIT 1";
if(mysqli_query($link, $query)){
echo "success";
}else {
echo "failed";
}
}
Try to read more about Ajax. There are a lot of libraries for it.