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.
Related
i am trying to use toggle buttons to save response in db as yes or no. for some reason the only response i am getting is 'on'. even when i switch off the button. i tried searching for problem and got a match but the problem was asked for android platform.now i am stuck with no answer there where similar questions but none of them is useful for me at this moment. sharing the code down below.Thanks in advance for those who are going to suggest or provide a solution.i am using class handicap to save data into variable inside JQUERY and then send that variable to AJAX page to perform db operation.i am not sharing CSS for toggle as i don't think that is required right now. if u need any additional info, do inform me.this input is inside a form with method POST. i am using a submit button with id that is calling this JQUERY.
html part
<div class="switch">
<input id="cmn-toggle-4" class="cmn-toggle cmn-toggle-round-flat handicap" type="checkbox" name="handicap">
<label for="cmn-toggle-4"></label>
</div>
jquery
$("#save-medical-1").click(function () {
var m11 = $(".handicap").val();
alert(m11);
$.ajax({
url: "ajexupdate.php",
type: "POST",
data: {smsgs11: m11},
dataType: 'text',
cache: false,
success: function (e) {
// alert(e);
$("#user_medical_form").html(e);
$("#medidetail").modal('hide');
$('body').removeClass('modal-open');
$('.modal-backdrop').remove();
}
});
return false;
});
You can get value using ":checked" using jquery.
eg.
if($("#cmn-toggle-4").is(":checked")){
m11="yes";
}
else{
m11="no";
}
and send it through ajax.
By writing a php command you are setting the initial value of that input into m11. You have to catch the client side value of input instead:
your code:
var m11 = '<?php echo $_POST['handicap']; ?>'; // always returns the initial value
Correct clien-side code:
var m11 = $(this).val();
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
?>
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).
Sorry in advance everyone for this question as I know the cascading select boxes has been done to death but I can't seem to find any good help. I've tried various things but it all seems to fail and I'm not understanding why.
Here's the jquery I have currently:
function tester() {
$("select#type").attr('disabled', 'disabled');
$("select#cat").change(function(){
var vid = $("select#cat option:selected").attr('value');
var request = $.ajax({
url: "show_type.php",
type: "POST",
data: {id : vid}
});
request.done(function(msg) {
$("#result").html( msg );
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
});
}
Don't mind the first section of the code with the select#type and select#cat as these are for what I was trying to get the code to populate at first, however the .change is my trigger for the .ajax request. The rest of the code I'm merely trying to dump a simple return message into an empty div#result upon a successful ajax request.
I ran a test, and the var vid populates correctly.
Here's the simple PHP file I'm trying to call with the ajax:
<?php
$requ;
if (isset($_POST['id'])) {
$requ = 'Worked';
} else {
$requ = "didn't work";
}
echo $requ;
?>
I thought perhaps the problem was the id wasn't being passed properly so I altered the PHP script to give me any valid output regardless of whether the $_POST was set or not.
I won't post the HTML as I'm just trying to dump this all into a div while I test it. When I run the script I get the 'Request Failed' error message with a message of "error".
Here is the other jquery & PHP I have also tried, using the .post instead of the .ajax:
function tester() {
$("select#type").attr('disabled', 'disabled');
$("select#cat").change(function(){
$("select#type").html("<option>wait...</option>");
var vid = $("select#cat option:selected").attr('value');
$.post("show_type.php", {id:vid}, function(data){
$("#result").empty().append(data);
}, "json");
});
}
And the PHP to accompany this particular jquery:
$requ = $_POST['id'];
$ret = 'You selected: ' . $requ;
echo json_encode($ret);
Again, it all failed. I also tried the above code without using the json encoding/parameters. All I want to do is a simple (so I would think) cascading select dropboxes. The second box to be dependent of the first boxes selection. I'm beginning to think that this all just may not be worth it and just sticking strictly to PHP with links to resubmit the page with a GET and populate a new section or div with the results of the first click. Any help or suggestions you might have would be greatly appreciated, I've spent 2 solid days trying to figure this all out. Thanks in advance
Alright, I got it fixed. Thanks to Mian_Khurram_ljaz for making me take a different look at the hierarchical structure of the file. I was assuming that since the js was calling the php file, by placing the php file in the same folder as the js, I could call the php by using the url: show_type.php but that was actually wrong. The structure is considered from the actual page invoking the js and php, and therefore the url should have been js/show_type.php since I had the show_type.php file in my js folder.
It's always the little mistakes that take you days to figure. For those in the future looking to find decent code for cascading select drop boxes, here is my functioning and fully expanded code (which also includes a tri-level cascade)
jQuery:
function project() {
$("select#model2").attr('disabled', 'disabled');
$("select#brand2").attr('disabled', 'disabled');
$("select#project").change(function(){
$("select#model2").attr('disabled', 'disabled'); // if changed after last element has been selected, will reset last boxes choice to default
$("select#model2").html('<option selected="selected">Choose...</option>');
$("select#brand2").html("<option>Please wait...</option>");
var pid = $("select#project option:selected").attr('value');
$.post("handler/project.php", {id:pid}, function(data){
$("select#brand2").removeAttr("disabled");
$("select#brand2").html(data);
});
});
$("select#brand2").change(function(){
$("select#model2").html("<option>Please wait...</option>");
var bid = $("select#brand2 option:selected").attr('value');
var pid = $("select#project option:selected").attr('value');
$.post("handler/projBrand.php", {proj: pid, bran: bid}, function(data){
$("select#model2").removeAttr("disabled");
$("select#model2").html(data);
});
});
}
Just call the function in the $(document).ready of your js.
Notice the comment, having this 'redundant' call to disable and force the last box to select the default is just in case the user makes a selection in all 3 boxes but goes back to the first box and changes the selection.
Here is the php handler file:
<?php
include_once('../includes/file.inc');
$request = $opt -> getModelvBrand();
echo $request;
?>
The other handler file for the jQuery is nearly exactly the same, only invoking a different method in the class file.
And lastly, the HTML:
<form action="" method="post">
<select id="project">
<option value="0">Choose...</option>
<?php echo $opt -> getProject();?> //populates first box on page load
</select>
<select id="brand2">
<option value="0">Choose...</option>
</select>
<select id="model2">
<option value="0">Choose...</option>
</select>
<br /><br />
<input class="like-button" type="submit" title="Submit" value="" />
</form>
Thanks again Mian for making me take a different look at my file(s).
Hope this code helps someone else in the near future.
This is a very simple form that I have found on the web (as I am a jQuery beginner).
<!-- this is my jquery -->
<script>
$(document).ready(function(){
$("form#submit_wall").submit(function() {
var message_wall = $('#message_wall').attr('value');
var id = $('#id').attr('value');
$.ajax({
type: "POST",
url: "index.php?leht=pildid",
data:"message_wall="+ message_wall + "&id="+ id,
cache: false,
success: function(){
$("ul#wall").prepend(""+message_wall+"", ""+id+"");
$("ul#wall li:first").fadeIn();
alert("Thank you for your comment!");
}
});
return false;
});
});
</script>
<!-- this is my HTML+PHP -->
some PHP ...
while($row_pilt = mysql_fetch_assoc($select_pilt)){
print
<form id="submit_wall">
<label for="message_wall">Share your message on the Wall</label>
<input type="text" id="message_wall" />
<input type="hidden" id="id" value="'.(int)$row_pilt['id'].'">
<button type="submit">Post to wall</button>
</form>
and down below is my PHP script that
writes to mySQL.
It is a pretty straight forward script. However, it is getting little complicated when I submit it. Since I have more than one form on my page (per WHILE PHP LOOP), thus when I submit - only the FIRST form gets submitted. Furthermore, any other subsequent forms that I submit - data is being copied from the first form.
Is there any jQuery functions that clear the data? - or is there a better solution.
Thanks,
Nick
It's because you're giving each form the same id, and thus it is submitting the first element it finds with that id, i.e. the first form. What you should do is assign a unique id to each form, and then give each form an AJAX submit function that submits the form-specific data. You can use jQuery's $.each() function to loop through all the forms and $(this).attr('id') within the submit function to retrieve the form-specific id.
UPDATE: As revealed by the comment on this answer, you actually don't need the each() function because jQuery applies it to every form element anyway.
Here would be an example script:
$(document).ready(function(){
$("form").submit(function() {
var message_wall = $(this).children('input[type="text"]').attr('value');
var id = $(this).children('input[type="hidden"]').attr('value');
$.ajax({
type: "POST",
url: "index.php?leht=pildid",
data:"message_wall="+ message_wall + "&id="+ id,
cache: false,
success: function(){
$("ul#wall").prepend(""+message_wall+"", ""+id+"");
$("ul#wall li:first").fadeIn();
alert("Thank you for your comment!");
}
});
return false;
});
});
Because we can't see all of your forms, I'm not entirely sure, but given your question I'm going to assume that the other forms all share the same id (form#submit_wall), which is invalid an id must be unique within the document.
Given that you're going to change the id of the other forms (I'd suggest using a class name of, probably, 'submit_wall', but the specifics are up to you), the jQuery needs to be changed, too. From:
$("form#submit_wall").submit(function() {
To:
$("form.submit_wall").submit(function() { // using the class-name instead of the id.
Now, of course, you run into the same problems of duplicate ids.
So I'd suggest, again, changing the id to a class and changing:
var message_wall = $('#message_wall').attr('value');
var id = $('#id').attr('value');
to:
var message_wall = $(this).find('.#message_wall').attr('value');
var id = $(this).find('.id').attr('value');
Given the mess that you've posted, above, I find it hard to believe that this is all you need. It would definitely be worth posting the full page (or a demo at JS Fiddle or JS Bin) that fully reproduces your code.