I'm using jQuery Ajax function for populating my select box.
Here is the code:
$(function(){
$("#maker").change(function(){
var selected_value = $("#maker").val();
$.ajax({
type: "POST",
url: "search.php",
data: ({_maker: selected_value}),
success: function(response){
$("#models").html(response);
}
});
});
});
The problem is this replaces the div "models" by whole search.php page!!!
I only want to populate the option values within "models".
Here is the HTML:
<div id="models">
<select id="model" name="model" style="width:170px">
<option value="Any">Any</option>
<?php
foreach($current_models as $model) {
?>
<option value="<?php echo $model; ?>"><?php echo $model; ?></option>
<?php
}
?>
</select></div>
Any help is appreciated. Thanks in advance.
So it looks like you're returning the entire HTML page, and not searching through it to find the specific part of the page. Try something like this:
$(function(){
$("#maker").change(function(){
var selected_value = $("#maker").val();
$.ajax({
type: "POST",
dataType: "html",
url: "search.php",
data: ({_maker: selected_value}),
success: function(response){
$("#models").html($(response).find('#someDiv').html());
}
error: function(){
$("#models").html('Uh oh! Something went wrong and we weren't able to process your request correctly.');
}
});
});
});
You'll notice 2 things:
I specified a dataType property. This tell jQuery what to expect. Additionally the html data type, tells jQuery to execute any JavaScript on the loaded page before rendering the page into the response object.
I'm creating a jQuery object using the response, and then using jQuery's .find() method to get the inner HTML of a specific div in the response.
Here is an example JS Fiddle, with some slight modifications for proof of concept: http://jsfiddle.net/rvk44/1/
I also just wanted to note that you may want to add an error property so that if the page ever comes back as an error, the user knows that and isn't just sitting there staring at a blank screen expecting something to happen. (I've added a basic error message in the example, see the jQuery docs for further info on what the error property is returned).
Related
In my code below I want display $("#searchresults").html(data) this result to other page.
$.ajax({
type: "POST",
url: base_url + 'front/searchresult',
data: data,
success: function(data) {
alert("test");
var val = $("#searchresults").html(data);
window.location.assign("<?php echo base_url()?>front/search/" + val);
}
});
what exactly is in the data variable you receive from your post? is it a json object? is it plain text?
if it is html, I think you should consider placing the result in a div on the current page, and hide items you don't want to see after searching
relocating after ajax requests is not the way to go. Is it an option in your case, to use a form and change the action attribute of the form to your new location?
<form action="front/search/">
<input type="text" name="data">
</form>
There have been similar questions, but I have browsed them a lot and found no accurate answer or fix so please offer a solution!
I am ajaxing a form to a page, and expecting a value back - no big deal. I've done it a million times before, but now it just refuses to work for this one form.
form html:
<form class="selectClaimType" action="place.php" method="post">
<select id="claimtype" name="claimtype">
<option value="privatebuilding">Private Building</option>
<option value="communalbuilding">Communal Building</option>
<option value="outside">Stored Outside</option>
</select>
<input type="submit" id="submit2" name="submit2" class="button" value="save"/>
</form>
jQuery:
$('form.selectClaimType').on('submit',function(e) {
console.log('found');
$form = $(this);
console.log($form.serialize());
e.preventDefault();
$.ajax({
url: "place.php", //$form.attr('action'),
type: "post", //$form.attr('method'),
data: $form.serialize(),
success: function(data) {
console.log(data);
if (data == 1) {
console.log('hello');
}
else {
console.log('failure to change claim type'+data);
}
},
data: function(data) {
console.log('error ajaxing'+data);
}
});
});
The form is not dynamically created, and as you can see I have console.log(ged) nigh on everything. So I know that the form.serialize() is working (values appear as expected). I left out the preventDefault() to test, and the get values were correct.
I have tried dataTypes of script, html, text, xml and json - no success.
I have a var_dump of $_REQUEST and $_POST on the posted to page - these are both empty arrays. I have changed the page that the post is sent to - still doesn't work.
Any ideas at all?
Maybe it is failing. Have you added a fail() callback to see if you get any output from that. Maybe the error is where you are submitting.
data: $form.serialize(),
....
data: function(data) {
console.log('error ajaxing'+data);
}
Probably a conflict here...maybe meant error: ?
This does not answer you question but maybe it solves your problem.
new FormData(form)
is a new native way to send a form.(including files)
Check the pure javascript way to send forms with xhr2.
support all modern browser including mobile devices & ie10
function ajax(a,b,e,d,c){
c=new XMLHttpRequest;
c.onload=b;
c.open(e||'get',a);
c.send(d||null)
}
// Url,callback,method,formdata or {key:val},placeholder
Send the whole Form
var form=document.getElementsById('myForm');
form.onsubmit=function(e){
e.preventDefault();
ajax('submit.php',SUCCESSFunction,'post',new FormData(this));
}
More info
https://stackoverflow.com/a/20476893/2450730 with working copy & past php page.
if you have any questions just ask.
Hope someone can help me..
i made my program more simpler so that everybody will understand..
i want my program to get the value of the without submitting, i know that this can only be done by javascript or jquery so I use the onChange, but what I want is when i select an option the value should be passed immediately on the same page but using php..
<select id="id_select" name="name" onChange="name_click()">
<option value="1">one</option>
<option value="2">two</option>
</select>
<script>
function name_click(){
value_select = document.getElementById("id_select").value;
}
</script>
and then i should pass the value_select into php in post method.. i dont know how i will do it.. please help me..
You cannot do this using PHP without submitting the page. PHP code executes on the server before the page is rendered in the browser. When a user then performs any action on the page (e.g. selects an item in a dropdown list), there is no PHP any more. The only way you can get this code into PHP is by submitting the page.
What you can do however is use javascript to get the value - and then fire off an AJAX request to a php script passing the selected value and then deal with the results, e.g.
$(document).ready(function() {
$('#my_select').on('change', do_something);
});
function do_something() {
var selected = $('#my_select').val();
$.ajax({
url: '/you/php/script.php',
type: 'POST',
dataType: 'json',
data: { value: selected },
success: function(data) {
$('#some_div').html(data);
}
});
}
With this code, whenever the selected option changes in the dropdown, a POST request will be fired off to your php script, passing the selected value to it. Then the returned HTML will be set into the div with ID some_div.
not sure ..but i guess ajax is what you need..
<script>
function name_click(){
value_select = $("#id_select").val();
$.post('path/to/your/page',{"value":value_select},function(data){
alert('done')
})
}
</script>
PHP
$value=$_POST['value']; //gives you the value_select data
Post with ajax as Alex G was telling you (+1) and then handle the post with PHP. You can define a callback in Javascript which will run when the page responds.
My suggestion go with jquery. Try with this
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
<script>
$(document).ready(function(){
$("#id_select").change(function(){
var url = 'http:\\localhost\getdata.php'; //URL where you want to send data
var postData = {'value' : $(this).value};
$.ajax({
type: 'POST',
url: url,
data : postData,
dataType: 'json',
success: function(data) {
//
},
error: function(e) {
console.log(e.message);
}
});
})
})
</script>
In getdata.php
<?php
var $value = $_POST['value'];
// you can do your logic
?>
hey I am trying to populate one select dropdown on the basis of another one using ajax. I have one select populated with portfolios and the 2nd one is empty. when I select an option from the 1st select box. I call an ajax function in which I send the selected portfolio id, In the ajax method I find the groups for the selected id, how can I populate the 2nd select with the groups I found. My code is
The form which contains two selects
<form name="portfolios" action="{{ path('v2_pm_portfolio_switch') }}" method="post" >
<select id="portfolios" name="portfolio" style="width: 200px; height:25px;">
<option selected="selected" value="default">Select Portfolio</option>
{% for portfolio in portfolios %}
<option get-groups="{{ path('v2_pm_patents_getgroups') }}" value={{ portfolio.id }}>{{ portfolio.portfolioName }}</option>
{% endfor %}
</select><br/><br/>
<select id="portfolio-groups" name="portfolio-groups" style="width: 200px; height:25px;">
<option selected="selected" value="default">Select Portfolio Group</option>
</select><br/>
</form>
The JS
<script>
$(document).ready(function(){
$('#portfolios').change(function() {
var id = $("#portfolios").val();
var url = $('option:selected', this).attr("get-groups");
var data = {PID:id};
$.ajax({
type: "POST",
data: data,
url:url,
cache: false,
success: function(data) {
//want to populate the 2nd select box here
}
});
});
});
</script>
Controller method where I find the groups for the selected portfolio
public function getgroupsAction(Request $request){
if ($request->isXmlHttpRequest()) {
$id = $request->get("PID");
$em = $this->getDoctrine()->getEntityManager();
$portfolio_groups = $em->getRepository('MunichInnovationGroupPatentBundle:PmPatentgroups')
->getpatentgroups($id);
return $portfolio_groups;
}
}
Any idea how can i send the portfolio groups and populate the 2nd select
thanks in advance
Use getJson instead of ajax();
Json (JavaScript Object Notation) , is the most easiest way to send structured data between php and javascript.
I Assuming here that the controller respond directly to the ajax query and that $portfolio_groups is an associative array with "id" and "name" as keys or an object with this same properties.
In your PHP controller send json data:
public function getgroupsAction(Request $request){
if ($request->isXmlHttpRequest()) {
$id = $request->get("PID");
$em = $this->getDoctrine()->getEntityManager();
$portfolio_groups = $em->getRepository('MunichInnovationGroupPatentBundle:PmPatentgroups')
->getpatentgroups($id);
echo json_encode($portfolio_groups);
}
}
Then use getJson to retrieve data and iterate over it :
$.getJSON(url, data, function(result) {
var options = $("#portfolio-groups");
$.each(result, function(item) {
options.append($("<option />").val(item.id).text(item.name));
});
});
Have a look to the getjson documentation for more detail about it
Check out this XML tutorial (someone out there is going to flame me for linking to w3schools) it's a good start.
AJAX requests are, in VERY broad terms, calls which make a browser open a window that only it can see (not the user). A request is made to the server, the server returns a page, the script that made the request can view that page. This means that anything which can be expressed in text can be transmitted via AJAX, including XML (for which the X in AJAX stands for).
How is this helpful? Consider, if you are trying to populate a drop down list, you need to return a list of items to populate it with. You COULD make an ajax call to a page http://www.mysite.com/mypage.php?d=select1 (if you are unfamiliar with GET and POST requests, or are a little in the dark regarding the more utilitarian aspects of AJAX, another full tutorial is available here) and have it return a list of items as follows:
item1
item2
item3
...
And scan the text for line breaks. While this certainly would work for most cases, it's not ideal, and certainly won't be useful in all other cases where AJAX may be used. Instead consider formatting the return in your PHP (.NET, ASP, whatever) in XML:
<drop>
<item>item1</item>
<item>item2</item>
<item>item3</item>
</drop>
And use Javascripts built in parser (outlined here) to grab the data.
What I would do is to use the $.load() function.
To do this, your getgroupsAction should return the options html.
The JS:
<script>
$(document).ready(function(){
$('#portfolios').change(function() {
var id = $("#portfolios").val();
var url = $('option:selected', this).attr("get-groups");
var data = {PID:id};
// Perhaps you want your select to show "Loading" while loading the data?
$('#portfolio-groups').html('<option selected="selected" value="default">Loading...</option>');
$('#portfolio-groups').load(url, data);
});
});
</script>
I don't know how $portfolio_groups stores the data, but let's say you'd do something like this in your response:
<?php foreach($portfolio_groups as $p) : ?>
<option value="<?php echo $p->value ?>"><?php echo $p->name ?></option>
<?php endforeach ?>
This way, the select will be filled with the options outputted by getgroupsAction.
The easiest way would be to return json string from your controller and then process it in the 'success' call of the $.ajax.
Lets assume, that your $portfolio_groups variable is an array:
$portfolio_groups = array('1'=>'Portfolio 1', '2' => 'Portfolio 2');
then you can return it from controller as json string like this:
echo json_encode($portfolio_groups);
Then in your jQuery ajax call you can catch this string in the response (the 'success' setting of the $.ajax). Don't forget to add setting dataType: 'json'
Roughly, your $.ajax call will look like this:
$.ajax({
type: "POST",
data: data,
url:url,
cache: false,
dataType: 'json', // don't forget to add this setting
success: function(data) {
$.each(data, function(id, title){
var node = $('<option>').attr('value', id).html(title);
// this will simply add options to the existing list of options
// you might need to clear this list before adding new options
$('#portfolio-groups').append(node);
});
}
});
Of course, you will also need to add the checks if the data is not empty, etc.
Supposing that the function getgroupsAction stays in a flat php controller ( not inside a class ) you should tell the server to execute the function
so at the end of file being called by ajax you should barely call the function first ( probably you did it! )
For your patents group result set, you can generate the select by php or by javascript
In first case you should do this:
//php
$options = getgroupsAction($_REQUEST);
$return = "<select name =\"name\" id=\"id\"><option value=\"\"></option>";
foreach( $options as $option){
$return.= "<option value=\"$option\">$option</option>";
}
$return .= "</select>";
echo $return;
Then in Javascript:
// javascript
var data = {PID:id};
$.ajax({
type: "POST",
data: data,
url:url,
cache: false,
success: function(data) {
//inside data you have the select html code so just:
$('#divWhereToappend').append(data);
},
error: function(data) {
//ALWAYS print the error string when it returns error for a more easily debug
alert(data.responseText);
}
});
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.