Post data with jQuery - javascript

I'm using sortable to sort a list. Then once the user clicks the Submit button I want it to post the data to another php page. I currently can get it to display an alert with the data I want posted but can't get the JavaScript post right.
This is the submit button.
<input type='submit' value='Submit' onclick='saveOrder();'/>
This is the JavaScript part that creates an alert.
function saveOrder()
{
var wordOrder = $( "#sortable" ).sortable('toArray').toString();
alert(wordOrder);
}
This outputs a,b,c,d,e in an alert box. I want this posted instead of showing an alert.
What I would like to do is post this data so I can loop through it on another PHP page.
foreach( $_POST as $stuff )
{
echo $stuff;
}

You can do this via ajax: -> http://api.jquery.com/jQuery.post/
function saveOrder() {
var wordOrder = $( "#sortable" ).sortable('toArray').toString();
$.post( "your/file.php", {wordOrder: wordOrder}, function( data ) {
//Do nothing
});
//$.post("your/file.php", {wordOrder: wordOrder});
}
in PHP, you can:
echo $_POST['wordOrder'];

Related

Jquery ajax post only works once

I have a jquery script that posts a value:
// //Delete a product from the shopping cart
tpj('.remove').on('click', function() {
// Stop form from submitting normally
event.preventDefault();
// Get some values from elements on the page:
console.log('test');
var $remove = tpj(this).attr('id');
url = 'includes/shoppingcart.php';
// Send the data using post
var posting = tpj.post( url, { remove: $remove} );
// Put the results in a div
posting.done(function( data ) {
var content = tpj( data );
tpj( "#result" ).empty().append( content );
});
});
This works the first time, but when I click a second time I redirect to my homepage, which makes sense since the anchor tag the .remove class is in has nothing in its href. However this means the preventdefault() is not working, the entire on click is not working.
Why is that? I googled and found out I should use .on instead of .click but this didn't change anything for me.
The following html line (which fires the jquery):
×
is in my header.php and shoppingcart.php, when the ajax post is made and the result of shoppingcart.php is loaded in my shopping cart, the link stops working like it should.
What do I need to do?
function(EVENT) foggoten in
tpj('.remove').on('click', function() {
//...
}
must be:
tpj('.remove').on('click', function(event) {
//...
}

Can't echo POST data after onSelect event

I am adding a onSelect function on datepicker to Post the selected value using ajax and echo post data using load function
My jquery code is
$('#merchant_datepicker').datepicker({
onSelect: function (formattedDate,date,inst) {
var merchant_datepicker = $('#merchant_datepicker').val();
{
$.ajax({
url:'../calendar.php',
method:"POST",
data:{merchant_datepicker:merchant_datepicker},
success:function(data){
$('#order_wrap').load("../calendar.php");
alert(data);
}
});
}
}
});
and my calendar.php is
<?php
$new_date=$_POST["merchant_datepicker"];
echo $new_date;
?>
<p>Hello</p>
I am getting the data in alert and also div#order_wrap shows "Hello" after selecting a date but I can't echo the $_POST["merchant_datepicker"]
Please help. Thanks
You are currently making two requests to calendar.php (one is the ajax POST, the other is the .load() call). If you just want to take the response of the POST and put it in to #order_wrap, use the data var that you already have.
$('#order_wrap').html(data);
Or instead of .html maybe .append or .prepend depending on what exactly you're wanting to do.

Send a JSON object to AJAX of jQuery Tabs using WordPress

I am using jQuery Tabs to program a messaging system using WordPress. The point is that when the user clicks one tab, which represents one conversation, an AJAX call is performed automatically with the functionality of jQuery Tabs.
I programmed the jQuery Tab to call an action (that I programmed as well). The action is programmed in PHP using WordPress and I can call it through localhost/mywebpage/wp-admin/admin-ajax.php?action=my_action.
The problem is the following: The default functionality of the jQuery tabs expects the raw output of the PHP file (the ajax action). This means I have to code HTML on the PHP file so I just put the response on the tabs panel (ui.panel.html). However I think this is inefficient and I would like to create a JSON object using WordPres function wp_send_json_success( jsonObject ) which is received on the ui.ajaxSettings.dataFilter function.
When I send HTML to the ui.ajaxSettings.dataFilter function, everything is correctly displayed on the jQuery tabs panel. But when I send a json success, I can see it on the console but I can't display it on the jQuery tabs panel. It appears for a millisecond and then disappears. So the JSON object is being received but for some reason can't be displayed. The only way something is displayed at the jQuery tabs panel is by sending raw HTML by my PHP function. Here is a very simple code example:
This is the JS function:
$( selector ).tabs( {
beforeLoad: function( event, ui ) {
ui.ajaxSettings.dataFilter = function( response ) {
console.log( response );
ui.panel.html( response );
}
} );
This is the PHP function that works good:
<?php
echo 'Hello World!';
This is the PHP function that displays on the panel por a millisecond and then disappears.
<?php
wp_send_json_success( 'Hello World! );
In my opinion, I think something else is executing and erasing what I have displayed on the ui.panel.html but I'm not that expert in jQuery tabs so if there is anyone out there with more experience that can tell me what it's going on I would really appreciate it.
I got it working and the fix was obvious but I am still unsure if this is the best way to do it. This is what I did:
var html = $( '<div>' ).addClass( 'wrapper' );
$( selector ).tabs( {
beforeLoad: function( event, ui ) {
ui.ajaxSettings.dataFilter = function( response ) {
// Do whatever you want with the JSON object (obviously validations)
// In my case I want to create HTML elements with info from the response
var response_js_array = JSON.parse( response );
html.append( $( '<div>' ).text( response_js_array['message'] ) );
},
load: function( event, ui ) {
ui.panel.html( html );
// Do also whatever you want after the messages have been loaded. In my case,
// I scroll down to the last message
scrollDown(); // This is also a function I programmed
}
} );

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
})

.post() return ID not being affected by pages Jquery [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 8 years ago.
This question is directly related to the question I asked here:
stop click() from happening on a ajax created input
I figured out the answer to that one by simply adding if (e.target === this), but now my returned response wont do anything when I check the box.
The new code that is being returned by my .post is:
$output .= "<table><tr><td>";
$output .= "<input id=\"toedit\" type=\"text\" placeholder=\"$item_to_edit\" size=20>";
$output .= "</td><td>";
$output .= "<input id=\"test_editing_check\" type=\"checkbox\" name=\"test_editing_check\" value=\"test_editing_check\" \>";
$output .= "</td></tr></table>";
But my Jquery which is on the original page:
$("#testing_editing").click(function(e){
if (e.target === this) {
var testhtml = $(this).html();
var meatseafood = '<?php echo $meatseafood; ?>';
$.post('edit_order.php', {'itemtoedit':testhtml,'meatseafood':meatseafood}, function(data) { //make ajax call to check_username.php
$("#testing_editing").html(data); //dump the data received from PHP page
});
}
});
$("#test_editing_check").click(function(){
if ( this.checked ) {
var testvalue = "HI";
alert(testvalue);
}
});
Doesn't seem to work on the check box that is being returned by the .post() call.
Is there something i need to do in order to make a .post() return be recognized by the main page's jquery code?
I hope its not something wrong with my syntax but i've used this exact (very basic) code on another page (but not with a .post() call) and it works fine.
Basically, when you click the div my main page writes, it calls a .post() and returns a editable input field and a check box. When i click that checkbox, i want it to make another .post() call and update a database with the newly entered data.
however, when i check the check box nothing happens.
it would seem my ajax returned code isn't recognized by the jquery from the original/main page.
with my test code all i'm trying to do is pop up an alert box when i click the checkbox to show that it has "read" the input box and can now send that data through the .post() call to be processed.
Let me know if you need any other code.
It seems pretty cut and dry though so i'm not sure why it isn't working and that's why i'm here :)
(the idea of what i'm trying to do is, a user submits a form, on the next page, a "confirmation box" is shown saying "is this what you wanted to submit with your form? and if the answer is no, they can "click" on the data and change it w/out having to reload the page. the clicking part works but the checkbox to acknowledge "yes, i want to change my data to this newly entered data" isn't working.)
Thanks for any help.
Derek Conlon
Try to assign the event after loading the checkbox like this:
$("#testing_editing").click(function(e){
if (e.target === this) {
var testhtml = $(this).html();
var meatseafood = '<?php echo $meatseafood; ?>';
$.post('edit_order.php', {'itemtoedit':testhtml,'meatseafood':meatseafood}, function(data) { //make ajax call to check_username.php
$("#testing_editing").html(data); //dump the data received from PHP page
// This is applied after loading the data from the ajax call
$("#test_editing_check").click(function(){
if ( this.checked ) {
var testvalue = "HI";
alert(testvalue);
}
});
});
}
});

Categories

Resources