JQuery receive value in php - javascript

I've tried to get some values with button through jquery into php. Which i've done like this.
HTML
<button class="button" name="reject" value="<?php echo $row['mail']; ?>" type="submit">reject</button>
Jquery
$(document).ready(function(){
$('.button').click(function(){
var url = window.location.href;
var whichBtn = $(this).attr("name");
var mail = $(this).attr("value");
var ajaxurl = url,
data = {'mail': mail, 'whichBtn' : whichBtn};
$.post(ajaxurl, data, function (response) {
// Response div goes here.
alert(whichBtn);
alert("action performed successfully");
});
});
});
PHP
if(isset($_POST['mail']))
echo $_POST['mail'];
Well, the thing is that POST[mail] is not set and I don't have clue why.. Could you help?

You need to add event.preventDefault() to your click handler. Since it is a submit button it is navigating away from the page before your Javascript gets executed. Try this:
$(document).ready(function(){
$('.button').click(function(event){
event.preventDefault();
var url = window.location.href;
var whichBtn = $(this).attr("name");
var mail = $(this).attr("value");
var ajaxurl = url,
data = {'mail': mail, 'whichBtn' : whichBtn};
$.post(ajaxurl, data, function (response) {
// Response div goes here.
alert(whichBtn);
alert("action performed successfully");
});
});
});

Related

How to pass javascript variable in .html() to php

I am adding a text area on click of a particular div. It has <form> with textarea. I want to send the jquery variable to my php page when this submit button is pressed. How can this be achievable. I am confused alot with this . Being new to jquery dizzes me for now. Here is my code,
`
<script type="text/javascript">
$(document).ready(function(){
$('.click_notes').on('click',function(){
var tid = $(this).data('question-id');
$(this).closest('ul').find('.demo').html("<div class='comment_form'><form action='submit.php' method='post'><textarea cols ='50' class='span10' name='notes' rows='6'></textarea><br><input class='btn btn-primary' name= 'submit_notes' type='submit' value='Add Notes'><input type='hidden' name='submitValue' value='"+tid+"' /></form><br></div>");
});
});
</script>`
Your code works fine in the fiddle I created here -> https://jsfiddle.net/xe2Lhkpc/
use the name of the inputs as key of $_POST array to get their values.
if(isset($_POST['submitValue'])) { $qid = $_POST['submitValue']; }
if(isset($_POST['notes'])) { $notes = $_POST['notes']; }
You should send your data after form submitted, something like this
:
$(".comment_form form").submit(function(e) {
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: url,
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
you can assign event after insert your form.
// handling with the promise
$(this).closest('ul').find('.demo').html("<div class='comment_form'><form action='submit.php' method='post'></form><br></div>").promise().done(function () {
// your ajax call
});;

Submit a Form Using Jquery Ajax

Fiddle And Code:
$("form.signupform").submit(function(e) {
var data = $(this).serialize();
var url = $(this).attr("action");
var form = $(this); // Add this line
$.post(url, data, function(data) {
try {
data = JSON.parse(data);
$(.result).html(data.result + " Watchlist");
} catch (e) {
console.log("json encoding failed");
return false;
}
});
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="result"></p>
<form class="signupform" method="post" action="admin/signupinsert.php" onsubmit="this.onsubmit=function(){return false;}">
<input type="text" name="firstname" />
<input type="submit" value="Sign Up"/>
</form>
admin/signupinsert.php code:
// Insert into DB code in PHP
$response = new \stdClass();
$response->result = "".$result."";
die(json_encode($response));
I am trying to submit this form using My Jquery Ajax Code. And the signupinsert.php file will return a value in $result variable. I am trying to print it inside <p class="result"></p>
But, the code re-directs users to signupinsert.php page.
What's wrong?
you must prevent the default action of submitting the form
$("form.signupform").submit(function(e) {
e.preventDefault(); // <-- add this
var data = $(this).serialize();
var url = $(this).attr("action");
also, in your php file return proper JSON and avoid parsing the response in javascript with JSON.parse(data);
the output in your php file should look like this
$response = new \stdClass();
$response->result = $result;
header('Content-Type: application/json');
print json_encode($response);
and in your success handler just process the data parameter as a normal json object
$.post(url, data, function(data) {
$(.result).html(data.result + " Watchlist");
}
Also, just a curiosity, what is this supposed to do?
$response->result = "".$result."";
Update:
I just realized why you had most of the issues:
$('.result').html(data.result + " Watchlist");
^ ^
see the missing quotes
you are redirecting because of action:
action="admin/signupinsert.php"
var url = $(this).attr("action");
got me?

Trouble with jQuery Script for On click event

My code seems to not run the jQuery at all for some reason, I have spent lots of time attempting to figure out what's wrong and have tested my delete PHP file separately
jQuery script:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
$.ajaxSetup({ cache: false });
$(document).ready(function(){
$('#button').on('click', '#btn',function()) {
var clickBtnName = $(this).attr('name');
var ajaxurl = 'http://127.0.0.1/SQLDeleteHandler.php';
var data = {'id': clickBtnName};
$.post(ajaxurl, data, function(response) {
window.location.href="http://localhost/store.php";
});
});
});
</script>
Php:
$query = "SELECT * FROM accounts";
$resultset= mysqli_query($connection,$query);
while($row = mysqli_fetch_array($resultset,MYSQLI_NUM)){
echo $row[0]." ".$row[1]." ".$row[2]." ".'<input type="submit" class="btn" name="".$row[0]."" value="delete" />';
echo "</br>";
}
use this :
$(document).ready(function(){
$('.btn').click(function(e){
e.preventDefault();
alert('Button is pressed');
var clickBtnName = $(this).attr('name');
var ajaxurl = 'http://127.0.0.1/SQLDeleteHandler.php';
var data = {'id': clickBtnName};
$.post(ajaxurl, data, function(response) {
window.location.href="http://localhost/store.php";
});
});
});

Issues with jQuery sending value from PHP controller $this->input->post('id', TRUE);

view.php
$(document).ready(function() {
$('.buttons > a').livequery("click",function(e){
var parent = $(this).parent();
var getID = parent.attr('id').replace('button_','');
var url = '<?php echo site_url('cart/price');?>';
$.post(url+"?id="+getID, {}, function(response){
$('#button_'+getID).html($(response).fadeIn('slow'));
});
});
});
<span class="buttons" id="button_5"><a class="btn-following" href="javascript: void(0)"></a></span>
controller:
$gid = $this->input->post('id', TRUE);
$this->Product_model->following($gid);
model:
function following($gid){
mysql_query("INSERT INTO tf_followers (following_id) VALUES('".$gid."')");
}
from this I am getting empty value to database and this is correct way to pass value through jQuery.
If you want to properly pass data to $.post, use its 3 parameter overload:
$.post(url, {id: getID}, function(response){
$('#button_'+getID).html($(response).fadeIn('slow'));
});
If you want to pass it with GET (like you were), you can't get it in the collection of POST variables on the server.

Form variable does not refresh with ajax call

I'm building a simple email sending form and wanted to make it with ajax. The form submits correctly the first time but if you make any subsequent changes to the text in the form and then submit again then jquery does not pick up on the changes and posts the old data. Whats going on?
<script type="text/javascript">
var $j = jQuery.noConflict();
$j(document).ready(function() {
var submit_url = "mail_submit.php";
var send_email = $j("#sendemail");
send_email.click(function() {
var form = $j("#post");
$j.post(submit_url, form.serialize(), function(data) {
alert(data);
});
});
});
It's working just fine.
Now I would prefer calling the submit event on the form itself, but if you are using a submit input type, remember to return false;
I ran into this problem again.
To solve it you need to use tinyMCE.triggerSave();
The method is outlined here http://maestric.com/doc/javascript/tinymce_jquery_ajax_form
My final code is:
<script type="text/javascript">
var $j = jQuery.noConflict();
$j(document).ready(function() {
var submit_url = "mail_submit.php?action=";
var actions = $j("#sendEmail, a#previewEmail, a#saveEmail, a#updateEmail");
var loading = $j("img#ajax-loading");
var status = $j("span#post-status-display");
actions.click(function() {
tinyMCE.triggerSave();
var form = $j("#post");
var action = $j(this).attr("id");
var update_div = $j("#update-div");
loading.show();
$j.post(submit_url + action, form.serialize(), function(data){
update_div.html(data);
update_div.fadeIn();
loading.hide();
});
});
});

Categories