Ajax Reading from a Database - php

I'm developing a website/database solution which gives the administrator the option to sign into the webpage and perform actions on the database.
Currently they can add/delete/run pre-defined queries, however to 'edit' records in a table, I would like them to specify the primary key (ID) and then have ajax read in the values associated with that record and allow them to be changed.
What's the best way to go about this?

as stratton suggested you have to use jquery/html on frontend and php/mysql on backend that will have the logic to handle the data you send and retrieve result that will be sent back to the user.
ex.
have a form that will send the id to search:
<form>
<input type="text" id="data" name="data"/>
<--send button-->
</form>
I suggest then to use jquery to send the form via ajax like this:
$(sendbutton).click(function(e){
e.preventDefault();
s.ajax({
url: 'urlofyouphppage',
type: 'post',
data : {data: $("#data").val(), action: 'search_thing'}
success: function(data){
//the response from the php page to insert somewhere.
//beware that if you use json you will have to decode via parseJSON.
}
});
});
On you php side you will have to parse the post and then perform the action
<?php
if($_POST['action'] == 'search_thing'){
$id = $_POST['data'];
//query for searching
//format the result data
echo $result; //or json_encode($result); if you want to use json
}
?>
This way you can create multiple logic step by setting each time a different action, and the anwer can be full html code that contains the "next step" to perform.

make an ajax request (use jQuery) to a php script that reads from the database and outputs the return value in whatever format you prefer (html, json) then display it in the front end with javascript

Related

implemantation of facebook like button

i am developing a site with html and php ...
what i have done so far for like button on my page is as follow(concept is same only name is different on facebook it is like and on my site it is Points Up )
<form method="post">
<input type="hidden" value="<?php echo $posts[postid]; ?>" name="postid">
<input type="submit" name="pointsup" value="Points Up" />
</form>
the above will create the button with name Points Up.
if(isset($_POST['pointsup']))
{ in this if block i have written all queries to update database and user interface and all
}
what i want is instead of that button there should be some link witch will run my sql code.
i also tried JavaScript but it doesn't help anything
Thanks in advance for your answers!
When you are working with a single anchor tag (hyperlink), you should send your parameters by GET method. in case, /your/address/rate.php?id= and check $_GET['id'] in PHP (validate/sanitize/...)
also, you can send your requests as POST by using AJAX.
this is a sample for jQuery:
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
take a look here
but if you want to use pure JavaScript, you should work with XMLHttpRequest object. take a look here.
You should do something like:
Find where you should point your link to and what parameters are needed, i will call it $url. It can involve such things like creating additional files, refactoring your code, etc...
Write js method which will send request to $url. I will call this method sendPointsUp;
Create link which will react to onClick event and call sendPointsUp with desired parameters from there.
What you can do is just add a link with an id so you can reach it easily with jquery.
Create a php-page where you do the query and other stuff (security check, cookie, whatever you want to do), and finally attach an ajax event to the link to call your php-page.
Print the link in your page:
Vote up
Create php
<?php
// do the query and other stuff, return the result in json format
// if you want to do something with the result (for example display the votes)
Javascript
$('#voteup').click(function(e){
$.ajax({
url: "your/url/to/phpfile",
}).done(function(data) {
// rewrite link to undo vote or whatever you want
// do something with the returned data
});
});

onclick -> mysql query -> javascript; same page

I need button to begin a mysql query to then insert the results into a javacript code block which is to be displayed on the same page that the button is on. mysql queries come from the values of drop-down menus.
Homepage.php contains
two drop down menus
div id='one' to hold the results javscript code block
a button to stimulate the mysql query to be displayed in div id ='one' through Javascript
flow of the process is as such
1. user chooses an option from each drop down
2. when ready, the user clicks a button
3. the onclick runs a mysql query with selections from the drop down menu.
4. send the results as array from the mysql query into the javascript code block
5. display the results in div id ='one'
all of this needs to happen on the same page!
The problem I am having is that as soon as the page is loaded, the javascipt is static. I am unable to push the mysql results into the javascript on the page which I need it to appear on. Having everything on the same page is causing trouble.
I'm not looking for the exact code laid out for me, just a correct flow of the process that should be used to accomplish this. Thank you in advance!
I've tried
using both dropdowns to call the same javascript function which used httprequest. The function was directed towards a php page which did the mysql processing. The results were then return back through the httprequest to the homepage.
I've tried to save the entire Javascript code block as a php variable with the mysql results already in it, then returning the variable into the home page through HTTPRequest, thinking I could create dynamic javascript code this way. Nothing has worked
You need to use a technology called AJAX. I'd recommend jQuery's .ajax() method. Trying to do raw XHR is painful at best.
Here is how you'll want to structure your code:
Load the page.
User chooses an option.
An onChange listener fires off an AJAX request
The server receives and processes the request
The server sends back a JSON array of options for the dependent select
The client side AJAX sender gets the response back
The client updates the select to have the values from the JSON array.
Basically, HTTP is stateless, so once the page is loaded, it's done. You'll have to make successive requests to the server for dynamic data.
Use AJAX,
example
$.ajax({
type: "POST",
url: "yourpage.php",
data: "{}",
success: function(result) {
if(result == "true") {
// do stuff you need like populate your div
$("#one").html(result);
} else {
alert("error");
}
}
});
For this purpose you need to learn ajax.This is used to make a request without reloading the page.so that you can make a background call to mysql
your code will be something like that
$("#submitbutton").live("click",function(){
$.ajax({url:"yourfile"},data:{$(this).data}).done(function(data){
//this data will in json form so decode this and use this in div 2
var x =$.parseJSON(data);
$("#div2").html(x.val());
})
})
and "yourfile" is the main file which connect to server and make a database request
here is how I used an onchange method to stimulate a MYSQL query and have the Highchart display the result. The major problem was that the returned JSON array was a string that needed to be converted into an INT. The resultArray variable is then used in the data: portion of the highChart.
$(function(){
$("#awayTeam").change(function(){
$.ajax({
type: "POST",
data: "away=" + $("#awayRunner").val(),
dataType: "json",
url: "/getCharts.php",
success: function(response){
var arrayLength = response.length;
var resultArray = [];
var i = 0;
while(i<arrayLength){
resultArray[i] = parseInt(response[i]);
i++;
}
In the PHP code, the array must be returned as JSON like this
echo json_encode($awayRunner);

Adding AJAX to a working PHP form

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.

Form auto submit ajax not working

I'm passing some variable from one file to another php file that contains a form via jQuery ajax. On The form page where data is being passed to have the following code in it, The values are getting passed in properly and and fields are getting populated with the correct entries, i'm able to very this with firebug response, but page is not automatically submitting. Is their anything i should be looking for that is preventing form from auto submitting. If i access the form page directly, i can see auto submit works.
<?php
$title = $_POST['title'];
$wrapper = $_POST['wrapper'];?>
<form action="test.php" method="post" id="publish">
<input type="text" value="<?php echo $title ?>" name="title">
<textarea name="wrapper"><?php echo $wrapper?></textarea>
<input type="submit" value="Submit">
</form>
<script>
window.onload = function(){
document.getElementById('publish').submit();
}
</script>
ajax code that is sending the values looks like this
$.ajax({
type: "POST",
url: "process.php",
data: {
title: 'test',
wrapper: 'testing123'
},
success: function(msg){
alert( "Data Saved: " + msg );
}
});
Spot the difference:
getElementById('publishForm')
id="publish"
From what I see the auto submit is linked to the 'publishForm'
However, your form Id is "publish"
This is probably the cause of the code not working.
Perhaps you should show us the caller code instead of the handler code. Most likely what you're dealing with is the JS not being run during the AJAX call - the PHP page processing is server side.
You could look into sending the form using PHP Curl instead of JS? That would probably address the issue where it works loaded directly, but fails when called from another page.
As far as I understood, that HTML is being loaded through AJAX, right? If so, then window.onload will not be fired since the page was already loaded (AJAX doesn't count). Just do this:
<script type="text/javascript">
document.getElementById('publish').submit();
</script>
EDIT
To break this down:
Your code on SourcePage.php(I made up this name for reference) is posting data to process.php via an AJAX request
process.php then injects "title" & "wrapper" into the html markup and returns html with some javascript to SourcePage.php
You're then expecting that displaying the resulting string (msg) of the returned html on SourcePage.php will get the javascript in that string to execute.
To get this working, you'll need to do a few things.
Parse out the incoming javascript from the html.
Inject the incoming parsed HTML into SourcePage.php's markup.
Pass the parsed out JavaScript into JavaScript's eval function.
Doing this should bring the page from the process.php and successfully execute the JavaScript code on SourcePage.php.
If you were expecting that the JavaScript would run on the server, then I'm afraid you're mistaken as the server(php runtime) will not execute the JavaScript on the server. Perhaps a redirect on the server will accomplish your goal (whatever that may be).
Original
Try this out: http://jsfiddle.net/NiceGuy4263/eJLMS/

Sending jQuery.ajax data simultaneous to a form submit

I have a bit of a conundrum. I have a form which has numerous fields. There is one field for links where you enter a link, click an add button, and the link(using jQuery) gets added to a link_array. I want this array to be sent via the jQuery.ajax method when the form is submitted. If I send the link_array using $.ajax like this:
$.ajax({
type: "POST",
url: "add_stock",
dataType: "json",
data: { "links": link_array }
});
when the add link button is selected the data goes no problem to the correct place and gets put in the db correctly. If I bind the above function to the submit form button using $(#stock_form).submit(..... then the rest of the form data is sent but not the link_array.
I can obviously pass the link array back into a hidden field in HTML but then I'd have to unpack the array into comma separate values and break the comma-separated string apart in PHP. It just seems 100X easier to unpack the Javascript array in PHP without an other fuss.
So, how is it that you can send an array from javascript using $.ajax concurrent to the rest of the $_POST data in HTML?
Please note that I'm using Kohana 3.0 framework but really that shouldn't make a difference, what I want to do is add this js array to the $_POST array that is already going.
Thanks!
If you actually want to submit the form (e.g., with page refresh and all that), your only option is to add a series of <input type='hidden'> fields to the form with the name links and fill each of them with one of the values from the array. Then what you get at the other end will be essentially what you get with your $.ajax call above.
If you just want to send the data to the server but you don't actually need to submit the form, you can use serialize on the form to get a URL-encoded string for it, then append your links to the end of the string, and send that via ajax. Something like this:
// Assuming 'link_array' is present
var data, n;
data = [$('#TheFormID').serialize()];
for (n = 0; n < link_array.length; ++n) {
data.push("links=" + encodeURIComponent(link_array[n]));
}
$.ajax({
type: "POST",
url: "add_stock",
dataType: "json",
data: data.join("&")
});
We get the beginning of the URL-encoded string from serialize, initialize an array with it, then push encoded fields for each link on it. Then we use Array#join to collect that all into one string to send with the ajax call. (You could do this with string concat instead if you like, but building these long strings with an array is faster after a certain number of elements, and makes the whole "do I put an & on it or not" just fall out naturally as well.)
You will have better luck using jQuery's serializeArray or serialize function, and then adding in the extra fields you have, and finally submit the POST data with .ajax.

Categories