jquery Post value to PHP webpage - javascript

I have made a web page with a dropdown menu. The idea is when we click any option of the dropdown menu it open produccion.php with a POST parameter 'edicion'. This parameter I use to do a query in a Database.
At moment the problem is that it's open the produccion.php but I think that doesn't POST the value of the variable
Jquery code:
$('#drEdicion a').click(function(event){
alert($(this).text());
var ed = $(this).text();
$.ajax({
url:"produccio.php",
type:"POST",
data:{edicion: ed},
dataType:"text",
success:function(data){
window.location.href = 'produccio.php'
}
});
});
Is it possible that the problem is when it's send via ajax?
Thanks in advance.

Your code is currently POSTing the content of the hyperlink over to produccio.php via AJAX. When that call completes it is then redirecting the user to the same page but without the POSTed value. Based on your comment:
I want to open produccion.php after selection option in dropdown button. With this option I do a query
it appears you actually want to open produccio.php with the POSTed value in the browser.
By far the easiest solution to the problem would be to alter the PHP code to accept the value of edicion from $_GET["edicion"] instead, and output your hyperlink as:
...
This will also provide a better experience for users, especially if they have issues with JavaScript (or, for example, happen to be a search engine). However, if you're set on only using $_POST, the following code may - I've not tested this myself - allow this:
$('#drEdicion a').click(function(event){
event.preventDefault();
var ed = $(this).text();
$('<form action="produccio.php" method="POST">' +
'<input type="hidden" name="edicion" value="' + ed + '" />' +
'</form>').appendTo('body').submit();
});
(with credit to the top answer on Dynamically create and submit form)

Follow bellow code :
$('#drEdicion a').click(function(event){
//alert($(this).text());
event.preventDefault();
var ed = $(this).text();
$.ajax({
url:"produccio.php",
type:"POST",
data:{edicion: ed},
dataType:"html",
success:function(data){
//#dropdown-menu id show all produccio.php data
$("#dropdown-menu").html(data);
}
});
});
produccio.php
<?php
$edicion = $_POST['edicion'];
//now you can able to access edicion post param
?>
HTML like this :
<div id="dropdown-menu"></div>

Related

AJAX call to differrent page in same domain works, but does not load everything

So, a little context: I'm trying to do an ajax call to a webpage in the same domain to get a telephone number to show up as soon as I specify the client on the first page. I do get the data but it seems like not the whole page is loaded in.
I need this:
<div id="1">
<div id="2">
<a id="ineedthis"></a>
</div>
</div>
but instead it's giving me this:
<div id="1">
</div>
This is a website that I'm writing a script for, since I can't edit the source code. This is managed from our ERP program and is pretty limited in customizability.
My best guess is that the target webpage is also still loading in the information from the database, but my ajax call returns the webpage before that happens.
Here is my js code:
function updateClasses(){
var link = $('a[href^="/organisatie-beknopt-prs?BcId="]');
var href = "https://52134.afasinsite.nl" + link.attr("href");
console.log(href);
if(href !== "https://52134.afasinsite.nlundefined"){
$.ajax({
url:href,
type:'GET',
success: function(data){
var tel = $(data).find("#P_C_W_Title_Content");
console.log(tel);
}
});
}
}
setInterval(updateClasses, 1000);
I'm running this once per second to check for a change in the input field on the first page, I don't know if there is a better way for this?
Firstly, you could try running the script/function once a change has been detected.
Something along the lines of :
$('input[name="{inputFieldName}"]').on('change',function(){
updateClasses();
});
//You can also use "keyup" instead of "change", depending on the type of action that you are looking for.
For the Ajax, you could try using Promises. Basically, set up the ajax call and then set a ".done" case for the ajax call has been completed and received some result. A ".fail" can also be used to catch non-code related issues.
function updateClasses(){
var link = $('a[href^="/organisatie-beknopt-prs?BcId="]');
var href = "https://52134.afasinsite.nl" + link.attr("href");
var getPhonePromise = $.ajax({
url: href
});
getPhonePromise.done(function(data) {
var tel = $(data).find("#P_C_W_Title_Content");
console.log(tel);
});
getPhonePromise.fail(function(errRes) { console.log(errRes);});
}

Ajax is not working (don't know why)

Hi and thanks to everybody in advance!
I want to do a simple thing with Ajax but is not working: push the button and change the html with another one from the same folder. Is something with the javascript but I can't identify the problem. I'm quite a novice with web design.
$(".about .ajax").on("click",function(e){
var section = $(this).closest("section");
var href = $(this).attr("href");
$.ajax({
url:href,
dataType:"html",
success:function(data){
var contenido = $("#about",data);
section.html(contenido);
}
});
e.preventDefault();
});
jsfiddle
I don't think you are binding it back properly.
I think you want something like this:
success:function(data){
$("#about").html(data);
}
Passing data as the 2nd argument will restrict jquery to find the right element.

Using jquery to submit one form on page that shares element names with other forms

To give you the most basic view of my question, I'm trying to create a page that is very similar to how facebook and twitter's dashboards and comment systems work. You have one page that will continuously create form elements (posts) from database rows in a loop as the user scrolls down. Users will then be able to comment on each of these posts. I want to be able to use ajax to submit comments on each post individually without reloading the page.
I run into a problem where when I try to submit a comment on any form other than the first one that is loaded on the page. In addition the ajax only posts the first form elements on submit (due to each form and elements having the same name I'm guessing).
Below is my comment loading script: [forgive the old php, I know I need to update it to mysqli or PDO]
php
<?php ...
$query = mysql_query("SELECT * FROM `posts`");
while ($row = mysql_fetch_array($query)) {
echo "
<div name='comment_body'>
<form name='comment_form'>
<td>User: ".$row['user']."</td>
<td>Post: ".$row['post']."</td>
<textarea name='comment'></textarea>
<p name='post_id' style='display:none;'>".$row['post_id']."</p>
<input type='submit' name='submit'>
</form>
";
$query2 = mysql_query("SELECT * FROM `comments` WHERE `post_id` = $row['post_id']");
while ($row2 = mysql_fetch_array($query2)) {
echo "
<td>User: ".$row2['user']."</td>
<td>Comment: ".$row2['comment']."</td>
</div>
";
}
... ?>
jscript
<script>
$('.comment_form').on('submit', function (e) {
e.preventDefault();
$.ajax ({
type: 'post',
url: 'submit_comment.php',
data: {comment : $('#comment').val(), post_id : $('#post_id').text()}
success: function() {
$("#comment_body").load("load_comments.php #comment_body");
}
});
});
</script>
The script works to a point because when I comment on the first post, it works as expected. I just can't seem to figure out how to target the forms further down the page individually. Here's an example:
The very top post has a post_id value of 40. If I comment on post_id = 38, ajax will submit the empty comment field and post_id = 40 into the database.
Any help with the script form targeting would be great. If I need to rebuild my php query to give each echoed form element an individual name, that's fine as well. Thanks in advance!
The data you're trying to send to in the ajax call is using:
$('#comment').val(), post_id : $('#post_id').text()
But your HTML doesn't have anything with an ID="comment" and ID="post_id". (the '#' in your selector means getElementById.) So you aren't sending any data to your php page. You need to use the correct selectors to get that data. (see below)
Get rid of the 'form' tags you don't need them. Change your
<input type="submit">
to a:
<input type="button" class="comment-submit">
Then your script can be:
<script>
$('.comment-submit').on('click', function (e) {
e.preventDefault();
// get a referenct to this particular comment_body div
var $commentbody = $(this).closest('.comment_body');
// find the textarea within this particular comment_body
var commenttext = $commentbody.find('textarea[name="comment"]').val();
// find the post_id paragraph within this particular comment_body
var postId = $commentbody.find('p[name="post_id"]').text();
$.ajax ({
type: 'post',
url: 'submit_comment.php',
data: {comment : commenttext , post_id : postId}
success: function() {
$comment_body.load("load_comments.php #comment_body");
}
});
});
</script>
Frankly I'm not sure what your success function is trying to do. But I think you need to work on it too. Normally an ajax call will return data so your success function should have a return value and that would be used to populate some part of your screen. The jQuery 'load()' function is another ajax call inside the success callback of an ajax call. I really don't think you want or need to do this.
You cannot select a unique form by class because your class is identical across all forms. Add an "id" field to the form element like this:
"<form name='comment_form' id='"+ .$row['id'] +"'>"
Then select a given form using that unique ID, and add your event handler. This must be in the same scope as you define your form. Like this:
$('#'+ .$row["id"]).on('submit', function (e) {
//Handle the event
})

Submitting a dynamic form in jQuery

I am dynamically creating a form in Jquery, and this form needs to submitted using AJAX. I'm probably doing something stupid, so your help would be greatly appreciated.
I am dynamically creating a form when a link is clicked:
$('.edit_item').click(function(){
$(this).closest('table').wrap("<form id='update_project' name='update_project' method='POST'>");
var input_name = $(this).closest('tr').find("td:eq(0)");
var input_submit = $(this).closest('tr').find("td:eq(1)");
input_name.html("<input type='text' id='update_name' name='update[]' value='"+input_name.text()+"' />");
input_submit.html("<input type='submit' value='update' id='update_submit' name='update_submit' />");
});
When the form is submitted:
$('#update_project').live("submit", function(e){
e.preventDefault();
$.post('project/update', $(this).serialize(), function(data){
$('#complete_msg').html(data);
});
$('.update_submit').css('background', '#c9c9c9');
});
Unfortunately, the page is refreshing (it shouldn't), and there is no return.
Thank you!
I would change the submit to a button:
input_submit.html("<input type='button' value='update' id='update_submit' name='update_submit' />
and the event, live is depreciated (http://api.jquery.com/live/):
$('#update_submit').click(function(e){
$.post('project/update', $('#update_project').serialize(), function(data){
$('#complete_msg').html(data);
});
$('.update_submit').css('background', '#c9c9c9');
});
Forgive me if my answer is too basic - your coding is quite advanced but you missed a couple of things. Better for me to be too pedantic rather than not provide enough info to immediately resolve your problem.
The page is refreshing when user clicks the update button because you are using the .submit method. If you do not want the form to refresh, use Stephen King's answer above to:
change the <input> type to type="button", then
use the ("#yourbuttonID").click() event to $.post your form data.
Also as SK said above, note the .live() is deprecated, so simply switch for .on()
Try this:
$('.edit_item').click(function(){
$(this).closest('table').wrap("<form id='update_project' name='update_project' method='POST'>");
var input_name = $(this).closest('tr').find("td:eq(0)");
var input_submit = $(this).closest('tr').find("td:eq(1)");
input_name.html("<input type='text' id='update_name' name='update[]' value='"+input_name.text()+"' />");
input_submit.html("<input type='button' value='update' id='update_submit' name='update_submit' />");
});
$(document).on("click", "#update_submit", function(e){
$.post('your_processor_filename.php', $(this).closest('form').serialize(), function(data){
$('#complete_msg').html(data);
});
$('.update_submit').css('background', '#c9c9c9');
});
Note that you need the .closest('form') selector to get your form data serialized.
I would also use $(document).on('click'... to ensure your injected button is found.
I am unfamiliar with the type of file to which you are sending the form data for processing, but project/update is not a familiar file type to me. Ensure that it is a page of code that can process your data, such as a .PHP file. See my example above -- or, better yet...
By way of example, create a .PHP file named 'your_processor_filename.php' (i.e. the filename I am referencing in the code I typed above). Put it in the same folder and type the following at the top:
//echo 'Got to the PHP side';
echo '<pre>';
print_r($_POST);
echo '</pre>';
die();
That will echo back what you sent and allow you both to see the data going through and confirm that the AJAX is working.
Note that your HTML must contain a div with the ID complete_msg to see the return message, such as:
<div id="complete_msg"></div>

Popup using jQuery?

I'm trying to do a pretty simple thing, I believe. I need to popup a success confirmation dialog after a user clicks to add someone to his friends list. Simply there's an add link on the page with the url (mysite.com/add/friendname). I needed to make issue this request asynchronously so I used jQuery.ajax built-in function to send the request. Take a look at the following code:
$(document).ready(function() {
$('.track_links').click(function() {
if (confirm("are you sure you want to track <firstname lastname>?")) {
$.ajax({
type: "GET",
url: this.href,
success: function() {
alert("Congratulation! you're now tracking <firstname lastname>");
},
error: function() {
alert("Oops! An error occured, plz try again later!");
}
});
return false;
}
else {
return false;
}
});
});
Now, here's what I need to do in short:
1- I need to use an already designed Html form as the success or failure confirmation message, instead of just alerting!
2- I also need to replace a placeholder (###username###) on that html page with the actual user name (firstname space lastname) which is the value of another field on the document. How to manipulate this html before poping it up on the client?
p.s: My Html/Javascript skills is totally awesome ;) (well, not really)!
For the first part
You can use the
show
function to show a div in the ajax success function.
$("#divResult").show();
if divResult is the id of the div to be shown
For the second part
you can get the value of first name and last name using
$("#txtFirstname" ).val();
and
$("#txtLastname" ).val();
if your first name text box id is txtFirstname and last name text box id is txtLastName
This is how I setup an Acknowledgement dialog, which could quickly be modified to be a confirmation for an action like yours.
http://professionalaspnet.com/archive/2009/06/02/Displaying-a-Confirmation-Dialog-with-the-JQuery-UI-Dialog.aspx
For the Form, I would suggest the html() Method, which injects raw HTML you have to provide. Since you already have it, you can give it to the Method via parameters.
For the Placeholder Part, I would suggest the val() Methods, coupled with Javascript's built-in regex functions.
If your placeholder is "###firstname###", then you should try something like
var firstname = jQuery('input#firstname').val();
var lastname = jQuery('input#lastname').val();
var text = jQuery('span#ThePlaceMyPlaceholderIsAt').text();
text = text.replace(/\#\#\#firstname\#\#\#/,firstname);
text = text.replace(/\#\#\#lastname\#\#\#/,lastname);
jQuery('span#ThePlaceMyPlaceholderIsAt').text(text);

Categories

Resources