I'm trying to take values from a dropdown two boxes and send them to a PHP file which will draw an appropriate field from a mySQL database depending on the combination chosen and display it in a div without refreshing the page using AJAX. I have the second part sorted, but I'm stuck on the first part.
Here is the HTML: http://jsfiddle.net/SYrpC/
Here is my Javascript code in the head of the main document:
var mode = $('#mode');
function get() {$.post ('data.php', {name: form.him.value, the_key: #mode.val()},
function(output) {$('#dare').html(output).show();
});
}
My PHP (for testing purposes) is:
$the_key = $_POST['the_key'];
echo $the_key;
After I have it in PHP as a variable I can manipulate it, but I'm having trouble getting it there. Where am I going wrong? Thanks for your replies!
You need a callback function as well to have the server response to the POST.
$.post('ajax/test.html', function(data) {
$('.result').html(data);
});
This snippet will post to ajax/test.html and the anonymous function will be called upon its reply with the parameter data having the response. It then in this anonymous function sets the class with result to have the value of the server response.
Help ? Let me know and we can work through this if you need more information.
Additionally, $.post in jQuery is a short form of
$.ajax({
type: 'POST',
url: url,
data: data,
success: success
dataType: dataType
});
your jquery selectors are wrong:
html:
<select id="mode">
jquery selector:
$("#mode").val();
html:
<select name="player">
jquery selector:
$("select[name=player]").val();
You want to add a callback to your ajax request, its not too hard to do, here ill even give you an example:
$.ajax({
url: "http://stackoverflow.com/users/flair/353790.json", //Location of file
dataType: "josn",//Type of data file holds, text,html,xml,json,jsonp
success : function(json_data) //What to do when the request is complete
{
//use json_data how you wish to.;
},
error : function(_XMLHttpRequest,textStatus, errorThrown)
{
//You fail
},
beforeSend : function(_XMLHttpRequest)
{
//Real custom options here.
}
});
Most of the above callbacks are optional, and in your case i would do the following:
$.ajax({
url: "data.php",
dataType: "text",
data : {name: ('#myform .myinput').val(),the_key: $('#mode').val()},
success : function(value)
{
alert('data.php sent back: ' + value);
}
});
the ones you should always set are url,success and data if needed, please read The Documentation for more information.
Related
I'm not sure if there is any way to do this or not, but this would solve so many of my problems if there is a simple solution to this.
What I need/want to be able to do is return HTML and JSON in my success of ajax request. The reason being, I want to request a file and return all of that page, but I also want to be able to return a specified set of information from the page in json, so I can use it for other things.
This is what I'm doing now:
$.ajax({
type: "POST",
url: "inc/"+page+".php",
data: "id="+encodeURIComponent(pageID),
success: function(html){
$("body > .container").html(html);
}
});
This is what I'd like to be able to do:
$.ajax({
type: "POST",
url: "inc/"+page+".php",
data: "id="+encodeURIComponent(pageID),
success: function(html){
$("body > .container").html(html);
$("title").html(json.PageTitle)
}
});
on the page that is being returned, I would specify what I want the title to be. (For instance, if it's a profile, I would return the user's name)
HTML and data wrapped in JSON
You can do it by returning a 2 element JSON array.
The first element contains HTML and the second element contains another JSON array with the data inside. You just need to unwrap it carefully without breaking anything.
Serverside
$html = '<div>This is Html</div>';
$data = json_encode(array('page_title'=>'My Page'));
$response = array('html'=>$html, 'data'=>$data);
echo json_encode($response);
Clientside
//Ajax success function...
success: function(serverResponse){
$("body > .container").html(serverResponse.html);
var data = JSON.parse(serverResponse.data);
$("title").html(data.page_title)
}
Note 1: I think this is what #hakre meant in his comment on your question.
Note 2: This method works, but I would agree with #jheddings that its probably a good idea to avoid mixing presentation and data. Coding karma will come back to bite.
Trying to mix the retun value to contain presentation and data seems like a potential for confusion. Why not split it into two calls and fetch the data on success of the other?
Something like:
$.ajax({
type: "POST",
url: "inc/"+view_page+".php",
data: "id="+encodeURIComponent(pageID),
success: function(html) {
$("body > .container").html(html);
$.ajax({
type: "POST",
url: "inc/"+data_page+".php",
data: "id="+encodeURIComponent(pageID),
success: function(json) {
$("title").html(json.PageTitle);
}
});
});
You also have the option of including the data in html5 data attributes
For instance, if you're returning a list of Animals
<ul id="ZeAnimals" data-total-animals="500" data-page="2">
<li>Cat</li>
<li>Dog</li>
...
</ul>
You can then collect the data you require using
$('#ZeAnimals').data('total-animals')
Sometimes separating your request into two different ajax calls makes sense also.
You may use a library that does that automatically, like http://phery-php-ajax.net. Using
Phery::instance()->set(array(
'load' => function(){
/* mount your $html and $json_data */
return
PheryResponse::factory()
->json($json_data)
->this() // points to the container
->html($html);
}
))->process();
$(function(){
var $container = $('body > .container');
$container.phery('make', 'load'); // or $container.phery().make('load')
$container.bind('phery:json', function(event, data){
// deal with data from PHP here
});
$container.phery('remote');
});
You may, as well, use phery.views to automatically load a portion of the site automatically, without having to worry about client-side specific code. You would have to put a unique ID on the container, container in this example:
$(function(){
phery.view({
'#container': {}
});
});
Phery::instance()->views(array(
'#container' => function($data, $params){
/* do the load part in here */
return
PheryResponse::factory()
->render_view($html)
->jquery('.title')->text($title);
}
))->process();
I have a simple load more style script that works fine on the index page, where only one parameter is sent via ajax
$(function() {//When the Dom is ready
$('.load_more').live("click",function() {//If user clicks on hyperlink with class name = load_more
var last_msg_id = $(this).attr("id");//Get the id of this hyperlink this id indicate the row id in the database
if(last_msg_id!='end'){//if the hyperlink id is not equal to "end"
$.ajax({//Make the Ajax Request
type: "POST",
url: "index_more.php",
data: "lastmsg="+ last_msg_id,
beforeSend: function() {
$('a.load_more').html('<img src="loading.gif" />');//Loading image during the Ajax Request
},
success: function(html){//html = the server response html code
$("#more").remove();//Remove the div with id=more
$("ul#updates").append(html);//Append the html returned by the server .
}
});
}
return false;
});
});
With this HTML/PHP
<div id="more">
<a id="<?php echo $msg_id; ?>" class="load_more" href="#">more</a>
</div>
However, I want to add another php variable so that it can also work with particular categories, I have no problems writing the HTML and PHP but I am new to Jquery and struggling to edit the script to include the additional parameter if it is set. This is the HTML that I am thinking of using, just struggling with editing the JQuery
<div id="more"class="<?php echo $cat_id;?>">
<a id="<?php echo $msg_id;?>" class="load_more2" href="#">more</a>
</div>
As always any help is much appreciated!
You can set
data = {onevar:'oneval', twovar:'twoval'}
And both key/value pairs will be sent.
See Jquery ajax docs
If you look under the data section, you can see that you can pass a query string like you are, an array, or an object. If you were to use the same method you already are using then your data value would be like "lastmsg="+ last_msg_id + "&otherthing=" + otherthing,
You can pass multiple URL params in the data portion of your ajax call.
data: "lastmsg="+ last_msg_id +"&otherparam="+ other_param
On the PHP side, you'd just process these as you already are.
You can use this code:
$.ajax({//Make the Ajax Request
type: "POST",
url: "index_more.php",
data: {var1: "value1", var2: "value2"},
beforeSend: function() {
$('a.load_more').html('<img src="loading.gif" />');//Loading image during the Ajax Request
},
success: function(html){//html = the server response html code
$("#more").remove();//Remove the div with id=more
$("ul#updates").append(html);//Append the html returned by the server .
}
});
Try It:
data: JSON.stringify({ lastmsg: last_msg_id, secondparam: second_param_value});
You can add more parameters separating them by comma (,).
I have this for loop in jquery
$(document).ready(function() {
for(i=0; i<counter; i++)
{
dataCounter = i;
$.ajax({
url: 'file.php',
dataType: 'json',
data: dataCounter,
error: function(){
alert('Error loading XML document');
},
success: function(data){
$("#contents").html(data);
}
});
}
});
And then I want to bring in my dataCounter into the file.php as a variable and have it change each time so I can get different records in mysql in file.php, am I doing this right? How would the php portion look like? I know how pass variables to a php file with this method if I had a form, but I don't have a get or a post form to work with. Also, my variables are going to change.
Can someone help me? Thank you!
While I don't recommend running an ajax query inside of a loop, I am wiling to explain the data option for $.ajax(). Ideally, you pass an object as the data option, and it is translated by jQuery into a query string where each object property name is a key and its value is the value:
data: {
count: dataCounter
}
becomes
?count=1
in the query string of the ajax request if datacounter is equal to 1.
In PHP you would access it as $_GET['count'].
data needs to be a key-value pair, not just a value as you have it here. Try something like: (not tested)
$.ajax({
url: 'file.php',
dataType: 'json',
data: ({dataCounter : dataCounter}),
error: function(){
alert('Error loading XML document');
},
success: function(data){
$("#contents").html(data);
}
});
ok, i have these two input fields where a user puts in two twitter names. When the submit button is pressed, both names should be send to a .php file with the POST method that checks if both usernames exsist on twitter.
Sending and receiving the answer for one value already works, but how can i also add the second? I already have this:
<script type="text/javascript">
function checkUsername()
{
$.ajax({
type: 'POST',
url: 'tu.php',
**data: {'user1' : $('#user1').val() },** //how to append user2?
dataType: "json",
success: function(data){
$('#uitslag').html(JSON.stringify(data));
$('#user1text').html(data['user1']);
$('#user2text').html(data['user2']);
}
});
}
</script>
the fields in the form:
<td><input type="text" name="user1" id="user1"/></td>
<td><input type="text" name="user2" id="user2" /></td>
and this is how the values should be able to be cathed in the .php:
$user1 = $_POST['user1'];
$user2 = $_POST['user2'];
So the question really is: how can I append the second username to the above jQuery POST function?
p.s. I am starting with javascript and jQuery, how do you guys work with this as no error messages are shown ever.. is there an environment/programm where I get debugging help with javascript?
data: {
'user1' : $('#user1').val(),
'user2' : $('#user2').val()
},
It's a simple enough extension-- just follow the same pattern.
<script type="text/javascript">
function checkUsername()
{
$.ajax({
type: 'POST',
url: 'tu.php',
data: {
'user1' : $('#user1').val(),
'user2' : $('#user2').val()
},
dataType: "json",
success: function(data){
$('#uitslag').html(JSON.stringify(data));
$('#user1text').html(data['user1']);
$('#user2text').html(data['user2']);
}
});
}
</script>
That said, jQuery does also have a .serialize() function that you could apply on the containing form, which automatically serializes the whole form. This could prove useful for you.
EDIT: It's worth mentioning that the jQuery selectors above look on the id for the name "user1" (etc.), whereas the PHP script expects the form elements' name to be "user1" (etc.). Here you have them as the same thing.
A more reliable jQuery selector that would allow you to always use the name in both jQuery and PHP is simply to use an attribute selector in jQuery:
$('input[name="user1"]').val()
This will catch any <input> element with the name attribute set to "user1".
You're probably looking for serialize. Your code would look something like this:
function checkUsername()
{
$.ajax({
type: 'POST',
url: 'tu.php',
data: $("#your_form").serialize(),
dataType: "json",
success: function(data){
$('#uitslag').html(JSON.stringify(data));
$('#user1text').html(data['user1']);
$('#user2text').html(data['user2']);
}
});
}
If you're sure you don't want serialize you could try this:
data: {'user1' : $('#user1').val(), 'user2' : $('#user2').val() }
As for your PS, check out Firebug and Webkit developer tools.
You actually don't even need the serialize function. If you just select your form, all form elements will be passed. This way if you just add another form element, like another textbox, it will all be passed in your ajax call.
function checkUsername()
{
$.ajax({
type: 'POST',
url: 'tu.php',
data: $("#your_form"),
dataType: "json",
success: function(data){
$('#uitslag').html(JSON.stringify(data));
$('#user1text').html(data['user1']);
$('#user2text').html(data['user2']);
}
});
}
i have a set of php function that i want to call on different events mostly onclick with jquery async (ajax).
The first function is called on load
$(document).ready(function()
{
$("#div2").hide('slow');
$("#div1").empty().html('<img src="ajax-loader.gif" />');
$.ajax(
{
type: "POST",
url: "WebFunctions.php",
data: {'func':'1'},
success: function(html)
{
$("#div1").show('slow').html(html)
}
});
The Data: {'func':'1'} --> is a switch statement on the php side
switch($_POST['func'])
{
case '1':
getParents();
break;
case '2':
getChilds(params);
break;
case '3':
getChildObjects(params);
break;
default:
}
"This functions are calls to a soap server" <-- irrelevant.
So when that function finishes i get an array which contains IDs and Names. I echo the names but i want the ID for reference so when i click on the echoed name i can call an other php function with parameter the ID of the name...
How do i get rid of the switch statement?? How do i call properly php functions and pass params to it??? How can i save this IDs so when i click on an item with that id an other php function is called??
Plz feel free to ask any question, any answer is welcome :)
``````````````````````````````EDIT``````````````````````````````````````````
$(document).ready(function()
{
$("#div2").hide('slow');
$("#div1").empty().html('<img src="ajax-loader.gif" />');
$.ajax(
{
type: 'post',
async: true,
url: "Parents.php",
data: {'id' : 12200},
dataType: "json",
cache: false,
success: function(json_data)
{
$("#div1").empty();
$.each(json_data, function(key, value)
{
$("#div1").append('<p class="node"><b>['+key+']</b> => '+value+'</p>');
$(this).data('id', key);
});
}
});
$("p.node").click(function()
{
var id = $(this).data('id');
alert('The ID is: ' + id);
});
});
I got json communication working but my problem is the data stuff,
when i click on a node the id is undefined... it gets printed but when i click on it oupsss.. so the problem is how can i properly attach the ID to each corresponding .. .
You can avoid the switch statement by using an MVC framework that routes your request to the proper function. For example, using CodeIgniter REST Server, you might have the following URL's to your functions:
http://myserver/my_api/parents
http://myserver/my_api/children
http://myserver/my_api/childObjects
You can then POST the parameters along with each AJAX request.
You would probably also want to return the ID you pass as part of the response, so it will be available when you make a request for the next function.
One solution for managing your ID's would be to encode your data as JSON. This will allow you to pass the whole PHP array to Javascript, and have it natively understand and read the ID's and Names.
To encode your PHP array as JSON, try this:
echo json_encode($my_array);
(You'll need PHP 5.2+ for this to work)
This will print out JSON data when the page is requested. Next, in your JavaScript add a "dataType" argument to your Ajax function call. Something like this:
// Get JSON Data and Save
$.ajax({
type: "POST",
url: "WebFunctions.php",
data: {'func':'1'},
dataType: "json",
success: function(json_data) {
$("#div1").data(json_data);
}
});
// Display the ID when clicked
$("#div1").click(function(){
var id = $(this).data('id');
alert('The ID is: ' + id);
});
This tells the Ajax function to expect JSON back.
When the success function is called you can access the "json_data" variable and find all the ID's and Names just as you had them in PHP. You'd then need to write some code to appropriately save those ID's and Names. They can then be used later on (ie. when you click on the button etc).
EDIT: I've updated the code above. The JSON data is now associated with the HTML element "#div1", so you can refer back to it in the future. I've also added a simple click event. Whenever the element is clicked, it's ID will be displayed.