jQuery onClick function to submit data to php "not defined" - javascript

The following button calls a jQuery function onClick. However, the Firefox dev console says "postData is not defined."
Here is the button and the jQuery script.
<div class="center_text_grid flex-item EMail_Pwd">
<button class="btn_joinnow" id="btn_joinnow" style="color:rgb(255,255,255)" onClick="postData()">Click to Submit Data</button></div>
function sendReply() {
// autoresponder
}
postData().done(sendReply);
</script>
</form><br>
<br><br><br>
<!-- ________________ -->
<script type="text/javascript">
function postData() {
return $.ajax({
var datastring = $("#echo_test").serialize();
$.ajax({
type: "POST",
url: "echo_test.php",
data: {post: datastring},
});
});
}
Why does the console say the function postData is not defined?
Thanks for any ideas.

I don't understand why you need two nested ajax calls, you really don't need them, I think. In any case, you can't declare a variable like this var datastring = $("#echo_test").serialize(); inside curly brackets, so move that line outside the ajax call.
Also take into consideration the order in which you declare/execute functions.
So, moving the script, where the function is declared, up:
<div class="center_text_grid flex-item EMail_Pwd">
<button class="btn_joinnow" id="btn_joinnow" style="color:rgb(255,255,255)" onClick="postData()">Click to Submit Data</button></div>
<script type="text/javascript">
function postData() {
var datastring = $("#echo_test").serialize();
return $.ajax({
type: "POST",
url: "echo_test.php",
data: {post: datastring},
});
}
</script>
<script>
function sendReply() {
// autoresponder
}
//also, this line is not needed for the button to work, this is just if
//you need the function to execute on page load as well
postData().done(sendReply);
</script>
HIH

you are calling postData before to implement the method, as mentioned move your function document.ready or put
<script type="text/javascript">
function postData() {
return $.ajax({
var datastring = $("#echo_test").serialize();
$.ajax({
type: "POST",
url: "echo_test.php",
data: {post: datastring},
});
});
}
</script>
in the head of the html file

Remove onclick from the button and add handler in the $(document.ready) function:
<button class="btn_joinnow" id="btn_joinnow" style="color:rgb(255,255,255)">Click to Submit Data</button></div>
...
<script type="text/javascript">
$(function(){
function postData() {
return $.ajax({
var datastring = $("#echo_test").serialize();
$.ajax({
type: "POST",
url: "echo_test.php",
data: {post: datastring},
});
});
$("#btn_joinnow").click(postData);
});
</script>

Related

Javascript functions keeps executing even after updating the DIV

I have certain content that gets updated using ajax on that Id, for example, let's suppose I have a complete main page and inside the body I have this code:
<div id="content">
<button onclick="update1()"></button>
<button onclick="update2()"></button>
</div>
<script>
function update1(){
$.ajax({
url:"Page1/index.html",
type:'GET',
success: function(data){
$('#content').html((data));
}
});
}
function update2(){
$.ajax({
url:"Page2/index.html",
type:'GET',
success: function(data){
$('#content').html((data));
}
});
}
</script>
<script src="js/script.js"></script>
And the index.html of Page1 contains some code like this:
<button onclick="update1()"></button>
<button onclick="update2()"></button>
<div id="page1"> .....</div>
And the index.html of Page2 contains some code like this:
<button onclick="update1()"></button>
<button onclick="update2()"></button>
<div id="page2"> .....</div>
And the script.js contains some code like this:
$(document).ready(
function() {
setInterval(function() {
$.ajax({
url: "someapi",
type: "POST",
dataType: "json",
success: function (result) {
console.log(result)
}
});
}, 2000);
});
What I want to do is when the button is pressed to call Ajax that gets the index.html from Page1 and puts it inside the id content, run a script.js this script only executes when the id page1 exists, I have found this trick from this answer, by using an if with jQuery for example if($('#page1').length ){my sj code} the javascript code runs only when that id exists, but unfortunately when I click the button to get the Page2 that has another id page2 that code keeps running, is there a way to stop this js code when that div is updated???
The function is not stopping because the interval will not stop firing unless you clear it, using clearInterval() function.
just put all your JS code in one file like this:
$(document).ready(function() {
var the_interval = setInterval(function() {
$.ajax({
url: "someapi",
type: "POST",
dataType: "json",
success: function (result) {
console.log(result)
}
});
}, 2000);
function stopTheInterval(){
clearInterval(the_interval);
}
function update1(){
$.ajax({
url:"Page1/index.html",
type:'GET',
success: function(data){
$('#content').html((data));
}
});
}
function update2(){
$.ajax({
url:"Page2/index.html",
type:'GET',
success: function(data){
$('#content').html((data));
stopTheInterval(); // we stop the first interval
}
});
}});
what I did here is saved the interval number in a variable, and created a new function to clear it.
next, all I did was put my new function in your update2() function, so once I get the data back I clear the interval and stop the repeating function.
script.js
dont use setInterval.
function some_function(){
$.ajax({
url: "someapi",
type: "POST",
dataType: "json",
success: function (result) {
console.log(result)
}
});
}
And call above function in update1.because you want it only when page1 updated
<script>
function update1(){
$.ajax({
url:"Page1/index.html",
type:'GET',
success: function(data){
$('#content').html((data));
some_function() // call function here
}
});
}
function update2(){
$.ajax({
url:"Page2/index.html",
type:'GET',
success: function(data){
$('#content').html((data));
}
});
}
</script>
Try using update1().stop()
in starting of update2 function

how to update a value in database using jquery when a link is clicked in php

I want to increment count field in database when a link is clicked in php file.
So, I've added the following jquery part to my .php file. But still, it doesn't work. Please help!
<body>
click here
<script>
$(function ()
{
$('#click').click(function()
{
var request = $.ajax(
{
type: "POST",
url: "code.php"
});
});
}
</script>
</body>
code.php:
<?php
$conn=mysqli_connect("localhost","root","","sample");
mysqli_query($conn,"UPDATE e set count=(count+1) WHERE sid='1'");
mysqli_close($connection);
?>
You made a several mistakes in your code.
Update
You can send your SID input type text from ajax with data and you can get the value in your php file with the $sid = $_POST['sid'].
<body>
click here
<input type="text" value="" name="sid" id="sid">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(e){
$('#click').click(function(event)
{
var sidvalue = $("#sid").val(); /*from here you get value of your sid input box*/
event.preventDefault();
var request = $.ajax(
{
type: "POST",
url: "code.php",
data: 'sid='+sidvalue ,
success: function() {
window.location.href = 'https://www.google.com/';
}
});
});
});
</script>
After the ajax success response you can make redirect to your desire location.
Code.php
<?php
$conn=mysqli_connect("localhost","root","","sample");
$sid = $_POST['sid']; // use this variable at anywhere you want.
mysqli_query($conn,"UPDATE e set count=(count+1) WHERE sid='1'");
mysqli_close($conn);
?>
in code.php in mysqli_close you should use $conn not $connection.
Go with this code. It might help you. I have just tested all the things in localhost. This is working perfect.
use preventDefault() when click event is called.check jquery :
<body>
click here
<script>
$(function ()
{
$('#click').click(function(e)
{
e.preventDefault();
var request = $.ajax(
{
type: "POST",
url: "code.php"
});
});
}
</script>
</body>
Redirect your link on ajax success. Like this -
<body>
click here
<script>
$(function ()
{
$('#click').click(function()
{
var request = $.ajax(
{
type: "POST",
url: "code.php",
success: function(response){
window.location="http://www.google.com";
}
});
});
}
</script>

LARAVEL: Use a javascript variable in php

I would like to get an id from a button. I need this id in my ajax request. This is my button:
<form>
<div class="form-group">
<button class="btn btn-primary" name="deletecar" id="{{$car->id}}">Delete</button>
</div>
</form>
I'm getting the id of the button this way:
<script type="text/javascript">var JcarID = this.id;</script>
Finally my Ajax Request.
$('[name="deletecar"]').click(function (e)
{
var JcarId = this.id;
e.preventDefault();
$.ajax({
type: "POST",
url: '{{ action('CarController#delete', [$user->id, $car->id])}}',
success: function (data)
{
// alert(data);
}
});
});
Thx for reading!
SOLUTION
Changed some bits in my code. I changed the url of my request.
$('[name="deletecar"]').click(function (e)
{
e.preventDefault();
$.ajax({
type: "POST",
url: '/users/{{$user->id}}/deletecar/'+this.id,
success: function (data)
{
// alert(data);
}
});
});
Hard to guess what is your requirement yet either if you want to get the button id value
this.attr('id'); or this.prop('id');
Or if you want to set the id value of button
$('[name="deletecar"]').attr('id', yourvalue)
I think you want to use JcarId rather $car->id in ajax request. Here what you can do rather than directly using PHP code in ajax call.
$('[name="deletecar"]').click(function (e)
{
var JcarId = this.id;
e.preventDefault();
$.ajax({
type: "POST",
url: '/CarController/delete',
data: {'carId':JcarId}
success: function (data)
{
// alert(data);
}
});
});

jQuery is not getting applied

I am working on notification system and loading html notification body from database to views which populate as follows:
<form id="acceptInviteForm" method="POST">
<input type="hidden" name="accountId" value="6">
<input type="hidden" name="operation" value="acceptinvite">
<button class="acceptinvite btn btn-primary" href="/acceptinvite" onclick="acceptingRequest();">Accept Invitation</button>
</form>
and applying jQuery function which I already defined on same page is like this:
// Accept invitation button click
jQuery(document).ready(function() {
function acceptingRequest() {
var formData = jQuery("#acceptInviteForm").serialize();
alert(formData);
jQuery.ajax({
type: "POST",
url: "/acceptinvite",
data: formData,
dataType: "json",
beforeSubmit: function() {
jQuery(this).attr({"disabled":"disabled"});
},
success: function(data) {
alert("Success");
},
error: function() {
alert("Got error while accepting invitation, reload or contact administrator!");
}
});
}
});
So when user click on button it's not work even not showing alert.
But things gets more interesting when I inject above jquery function from chrome console while view is loaded and button start working fine and shows alert too!
I am not getting the point which not letting things work!
It's because your acceptingRequest function is visible only inside anonymous jQuery(document).ready callback.
So when you click the button acceptingRequest is not visible.
Solutions keeping jQuery(document).ready(function() {})
To solve this bind the handler inside the callback using $('button.acceptinvite').on('click',acceptingRequest)
or use an anonymous callback (something like this):
$('button.acceptinvite').on('click',function(){
var formData = jQuery("#acceptInviteForm").serialize();
alert(formData);
//Etc.
});
In both cases remove onclick="acceptingRequest();" since it's no longer needed.
Another option is to make acceptingRequest visible outside using a global variable (it's not a good practice anyway):
acceptingRequest = function () {
var formData = jQuery("#acceptInviteForm").serialize();
alert(formData);
//Etc.
}
Now acceptingRequest is visible outside jQuery().ready and you can do onclick="acceptingRequest();"
Solutions without jQuery(document).ready(function() {})
If you don't need the DOM to be completely loaded (like in this case) you can remove
jQuery(document).ready(function() {}) and just write your function from in head, so they are visible to the button.
<script>
function acceptingRequest() {
var formData = jQuery("#acceptInviteForm").serialize();
alert(formData);
//Etc.
}
</script>
Let me know if this was useful.
I think you are defining the function acceptingRequest() on document ready, but you are not really calling it. Try adding:
acceptingRequest();
just after the definition of the acceptingRequest() function. The result would be:
// Accept invitation button click
jQuery(document).ready(function() {
function acceptingRequest() {
var formData = jQuery("#acceptInviteForm").serialize();
alert(formData);
jQuery.ajax({
type: "POST",
url: "/acceptinvite",
data: formData,
dataType: "json",
beforeSubmit: function() {
jQuery(this).attr({"disabled":"disabled"});
},
success: function(data) {
alert("Success");
},
error: function() {
alert("Got error while accepting invitation, reload or contact administrator!");
}
});
}
acceptingRequest();
});
It is because this string
<button class="acceptinvite btn btn-primary" href="/acceptinvite" onclick="acceptingRequest();">Accept Invitation</button>
will be proceded by the browser earlier than the definition of your acceptingRequest function. 'acceptingRequest' in your code will be defined asynchronously when document ready fired. So browser can't assign it with the click listener. Try to put your script exactly before </body>(and after jQuery script) and without jQuery(document).ready
<script>
function acceptingRequest() {
var formData = jQuery("#acceptInviteForm").serialize();
alert(formData);
jQuery.ajax({
type: "POST",
url: "/acceptinvite",
data: formData,
dataType: "json",
beforeSubmit: function() {
jQuery(this).attr({"disabled":"disabled"});
},
success: function(data) {
alert("Success");
},
error: function() {
alert("Got error while accepting invitation, reload or contact administrator!");
}
});
}
</script>
</body>
Function defined in ready state can be used in it's own scope.So you can use acceptingRequest() method in ready state.
in my view below code is bestpractice in event binding:
<form id="acceptInviteForm" method="POST">
<input type="hidden" name="accountId" value="6">
<input type="hidden" name="operation" value="acceptinvite">
<button class="acceptinvite btn btn-primary" id="acceptInviteButton" href="/acceptinvite" onclick="acceptingRequest();">Accept Invitation</button>
</form>
and in ready state:
jQuery(document).ready(function() {
function acceptingRequest() {
var formData = jQuery("#acceptInviteForm").serialize();
alert(formData);
jQuery.ajax({
type: "POST",
url: "/acceptinvite",
data: formData,
dataType: "json",
beforeSubmit: function() {
jQuery(this).attr({"disabled":"disabled"});
},
success: function(data) {
alert("Success");
},
error: function() {
alert("Got error while accepting invitation, reload or contact administrator!");
}
});
}
$("#acceptInviteButton").on("click",acceptingRequest);
});

Updating div content after form submit without page reload

alright, I have a popup which displays some notes added about a customer. The content (notes) are shown via ajax (getting data via ajax). I also have a add new button to add a new note. The note is added with ajax as well. Now, the question arises, after the note is added into the database.
How do I refresh the div which is displaying the notes?
I have read multiple questions but couldn't get an answer.
My Code to get data.
<script type="text/javascript">
var cid = $('#cid').val();
$(document).ready(function() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "ajax.php?requestid=1&cid="+cid,
dataType: "html", //expect html to be returned
success: function(response){
$("#notes").html(response);
//alert(response);
}
});
});
</script>
DIV
<div id="notes">
</div>
My code to submit the form (adding new note).
<script type="text/javascript">
$("#submit").click(function() {
var note = $("#note").val();
var cid = $("#cid").val();
$.ajax({
type: "POST",
url: "ajax.php?requestid=2",
data: { note: note, cid: cid }
}).done(function( msg ) {
alert(msg);
$("#make_new_note").hide();
$("#add").show();
$("#cancel").hide();
//$("#notes").load();
});
});
</script>
I tried load, but it doesn't work.
Please guide me in the correct direction.
Create a function to call the ajax and get the data from ajax.php then just call the function whenever you need to update the div:
<script type="text/javascript">
$(document).ready(function() {
// create a function to call the ajax and get the response
function getResponse() {
var cid = $('#cid').val();
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "ajax.php?requestid=1&cid=" + cid,
dataType: "html", //expect html to be returned
success: function(response) {
$("#notes").html(response);
//alert(response);
}
});
}
getResponse(); // call the function on load
$("#submit").click(function() {
var note = $("#note").val();
var cid = $("#cid").val();
$.ajax({
type: "POST",
url: "ajax.php?requestid=2",
data: {
note: note,
cid: cid
}
}).done(function(msg) {
alert(msg);
$("#make_new_note").hide();
$("#add").show();
$("#cancel").hide();}
getResponse(); // call the function to reload the div
});
});
});
</script>
You need to provide a URL to jQuery load() function to tell where you get the content.
So to load the note you could try this:
$("#notes").load("ajax.php?requestid=1&cid="+cid);

Categories