SQL query without refresh - php

I've read all the related posted, watched videos, and read tutorials... But I still can't figure this out. I just want to run a mysqli_query insert without a refresh.
No inputs, no variables, just a pre-defined sql insert without a refresh.
Here is the main doc:
<html>
<head>
<script src="inc/scripts/jquery-1.11.3.min.js"></script>
<script>
$("#click").click( function()
{
$.ajax({
url: "click.php",
type: 'POST',
success: function(result) {
//finished
}
});
});
</script>
</head>
<body>
<input type="button" id="click" value="Click">
</body>
</html>
Click.php (Has been tested standalone):
<?php
$db = mysqli_connect("localhost","root","","mytable")
or die("Error " . mysqli_error($db));
mysqli_query($db,"INSERT INTO items VALUES
('','test','test','total test','test','test','test','test')");
?>
This has been driving me crazy... I've read tutorials and watched many videos about ajax... but I can't figure this out.
Thank you for any advice.

To refresh a part of a page you got to bind the success function to a div in the html so add a div with an Id
<div id="myDiv"></div>
And then
$('#like$id').click(function()
{
$.ajax({
url: 'inc/scripts/liker_ajax.php?like=$id',
type: 'GET',
success:function(result){
$('#like$id').addClass('green');
$('#dislike$id').removeClass('red');
$('#myDiv').html(result);
}
});
});

You're binding the event $('#click').click() before there is an element to bind to (since $('#click') isn't loaded yet).
Just move your <script> tag with the click binding event into the <body> underneath the input button and it will work as expected.
You might also want to wrap in a jQuery document ready enclosure like:
$(function() {
});
to make sure it runs when DOM ready.

Try this.
<html>
<head>
<script src="inc/scripts/jquery-1.11.3.min.js"></script>
<script>
function runAjax()
{
$.ajax({
url: "click.php",
type: 'POST',
success: function(result) {
//finished
}
});
</script>
</head>
<body>
<input type="button" id="click" onclick="runAjax()" value="Click">
</body>
</html>

You are binding the event to the element when the element is not exixting yet.
You have 2 options here.
Either move your script block to just below the end of body tag after the element.
Encase your code inside the script block under $(document).ready(function() {
// your code here
});
Also use the console tab under your developer tools to find the root cause if any errors are present.

Related

Problems in submitting form data using ajax

i am new in ajax. i am aware to html,php. i want to do the CRUD operation in ajax. i have created a two file
index.php
insert.php as below.
when i click on submit button it submit data and inserted in database. But it resfresh the page. please suggest me that where i made mistake.
my code as below:
index.php
<!DOCTYPE html>
<html>
<head>
<title>Ajax test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
<script type="text/javascript">
var frm = $('#contactForm1');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert('ok');
}
});
ev.preventDefault();
});
</script>
</head>
<body>
<form id="contactForm1" action="insert.php" method="post">
<label>Name</label><input type="text" name="user_name"><br>
<label>Age</label><input type="number" name="user_age"><br>
<label>Course</label><input type="text" name="user_course">
<br>
<input type="submit" name="sumit" value="submit">
</form>
</body>
</html>
insert.php
<?php
$conn = mysqli_connect("localhost", "root", "" ,"aj");
$name = $_POST['user_name'];
$age = $_POST['user_age'];
$course = $_POST['user_course'];
$insertdata=" INSERT INTO test3 (name,age,course) VALUES( '$name','$age','$course' ) ";
mysqli_query($conn,$insertdata);
?>
Close the script tag
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
Use when document is ready
$( document ).ready(function() {
var frm = $('#contactForm1');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
frm[0].reset();
alert('ok');
}
});
ev.preventDefault();
});
});
The ready event occurs when the DOM (document object model) has been
loaded. Because this event occurs after the document is ready, it is a
good place to have all other jQuery events and functions. Like in the
example above. The ready() method specifies what happens when a ready
event occurs.
The JavaScript code, binding the event handler, is executed too early. The DOM is not fully loaded yet so the form can't be found. jQuery doesn't warn about this.
Either wrap your code in jQuery's on doc loaded method $(function(){ /* code here */ } ).
Or/and move your JavaScript to the bottom of your HTML. This is a preferred method. See Benefits of loading JS at the bottom as opposed to the top of the document for more details
There is no mistake. Technically, its correct. It's just not fitting in your use-case.
It's default behaviour that page refreshes when user submits form.
You have two options:
Stop further execution when your ajax call is completed. You can do this by javascript by using preventDefault method. Then, use return false.
Change the submit button to normal button. In other words, don't submit form normal way. Give an id to normal button and call javascript function upon its click.

PHP not capture $_POST data send by ajax jquery on same page

I am using ajax to post data on the same page and trying to echo posted data with php with following script.
$('button').click(function(){
$.ajax({
type: "post",
data: $("form").serialize(),
beforeSend: function(){},
success: function(data){alert(data)},
error: function(err) {alert(err.responseText);}
})
})
and php script is :
<?php echo isset($_POST['data']) ? $_POST['data'] :''; ?>
my html is:
<form>
<input type="hidden" name="data" value="to_success"/>
<button type="button">Click Me</button>
</form>
My problem is php does not echo posted data on page, but when i post form data on another php file which is same php script; php is able to echo posted data and ajax is alert that. please help me to resolve this issue. thanks
It's difficult to tell without seeing your entire PHP page as one listing, but from your description it sounds like your issue is either because of the way you are declaring your .click() event or the way you are posting to the page. The former is more likely.
The $.ajax() request will use an XMLHttpRequest object to POST to your PHP script. The PHP script should then take those values and generate the return string from the combination of the plain text in the script and the inserted echo'd values. This should then be received by the success method's callback function and alerted to your page as a blob of HTML text in the alert box.
Indeed, this is exactly what happens if I use the following code:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$(document).ready(function() {
$('button').click(function() {
$.ajax({
type: "post",
data: $("form").serialize(),
beforeSend: function() {},
success: function(data) {
alert(data);
},
error: function(err) {
alert(err.responseText);
}
});
});
});
</script>
</head>
<body>
<?php echo isset($_POST['data']) ? $_POST['data'] :''; ?>
<form>
<input type="hidden" name="data" value="to_success"/>
<button type="button">Click Me</button>
</form>
</body>
</html>
However, if I comment out the lines for $(document).ready(function(){ and its corresponding end });, then nothing happens when I click.
So, try wrapping your .click() event definition in a $(document).ready().

Form submit supposed to refresh only Div, but instead refreshes Page

I have a PHP page included called 'leaguestatus.php'. This page allows the user to post a message/status update and the intent is to have only this part of the div refreshed; however, on submit, the entire page is reloaded.
In the current implementation I'm simply printing all the $_POST variables to the div so I can see what's coming through. The MsgText textarea DOES get posted, however, it's only after the whole page loads. I'm trying to get just the div and that included file to reload.
div id="statusupdates"><? include 'leaguestatus.php'; ?></div>
leaguestatus.php
<form id="statusform" method="POST">
<textarea name=MsgText rows=5 cols=40></textarea><BR>
<input type=submit value=Post id=uhsbutton>
</form>
<BR>
<BR>
<div id='formbox'>
<? print "<pre>POST Variables:<BR>";
print_r ($_POST);
print "</pre>";
$MsgText = $_POST["MsgText"];
?>
</div>
The jQuery I'm running in the header is:
$(document).ready(function() {
$("#statusform").submit(function(e) {
e.preventDefault();
var formData=$(this).serialize();
var pUrl="leaguestatus.php";
submitFormSave(formData, pUrl);
});
function submitFormSave(formData, pUrl) {
$.ajax({
url: pUrl,
type: 'POST',
data:formData,
success: function(response) {
$("#formbox").html(response);
}
}).success(function(){
});
}
});
Here are my includes:
html header
<link rel="stylesheet" href="css/jquery-ui.css">
<script src="js/jquery-1.9.1.js"></script>
<script src="js/jquery-ui.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
Edit: updated code to reflect use of #sazedul's response. Only issue now is on first click page acts as expected (no page refresh). On second click the entire page reloads. On third click we're back to normal.
Use this following code for ajax submit hope it will work.
$("#statusform").submit(function(e) {
e.preventDefault();
var formData=$(this).serialize();
var pUrl="leaguestatus.php";
submitFormSave(formData, pUrl);
});
function submitFormSave(formData, pUrl)
{
$.ajax({
url: pUrl,
type: 'POST',
data:formData,
success: function(response)
{
$("#formbox").html(response);
}
});
}
Made the following changes in your leaguestatus.php remembar to put double quote in the name="MsgText" in text area.
<form id="statusform" method="POST">
<textarea name="MsgText" rows=5 cols=40></textarea><BR>
<input type=submit value=Post id=uhsbutton>
</form>
<BR>
<BR>
<div id='formbox'>
</div>
<?php
if(isset($_POST['MsgText'])){
$message=$_POST['MsgText'];
echo $message;
}
?>
check for .load() like the code below....
$(document).ready(function() {
$("#statusform").submit(function() {
$("div").load();
});
});
You have to preventDefault of submit then other thing
so,you have to use e.preventDefault() to prevent submit.then do what ever you want
$("#statusform").submit(function(e) {
e.preventDefault();
......

jquery is resetting my div content

I'm trying to change the content of div using jquery. but the content flashes and resets the div. i cannot use return false; because there is another button for post text field value. i want to keep the changes of div. here is my code:
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<div>
<form id="form" method="POST">
<input type="text" name="gname" id="gname"/></br>
<button id="btn">Set</button>
<button id="nbtn">View</button>
</form>
</div>
<div id="outp">
</div>
</body>
<script>
$("#btn").click(function(event) {
$.post("send.php", {
named: $("#gname").val()}, function(data) {
alert(data);
});
});
</script>
<script>
$("#nbtn").click(function(e) {
$("#outp").html("<?php include './view.php'; ?>");
});
</script>
It's not jQuery; it's that your form is being posted. So your change is made, but then the form is posted and the page is refreshed from the server.
The default type of button elements is "submit". To make one or both of those buttons just a button, use type="button".
Alternately, if you want to allow the form to be used when JavaScript is disabled (e.g., allow it to be posted normally), leave the buttons as submit buttons but prevent form submission using JavaScript. E.g.:
$("#form").submit(false); // Prevents the form being submitted in the normal way.
Any buttons inside a form are considered submit buttons.
So you need to add event.preventDefault() to your .click code.
Also, why are your scripts outside body section?
You can try with ajax and catch success and error:
$("#btn").click(function() {
var named: $("#gname").val();
$.ajax({
url: 'send.php',
type: 'POST',
data: {param1: 'value1'},
})
.done(function(data) {
console.log("Post success"+data);
})
.fail(function() {
console.log("Post error"+data);
});
});

jQuery PHP passing values within functions vs live clicking?

I'm trying to pass some values through onclick which to me is so much faster. But I need to use some kind of "live" clicking and I was looking into .on() or .delegate(). However, if I do any of those, passing those values within followme() seems a little harder to get. Is there some kind of method that I'm not seeing?
<div class='btn btn-mini follow-btn'
data-status='follow'
onclick="followme(<?php echo $_SESSION['user_auth'].','.$randId;?>)">
Follow
</div>
function followme(iduser_follower,iduser_following)
{
$.ajax({
url: '../follow.php',
type: 'post',
data: 'iduser_follower='+iduser_follower+'&iduser_following='+iduser_following+'&unfollow=1',
success: function(data){
$('.follow-btn').attr("data-status",'follow');
$('.follow-btn').text('Follow');
}
});
}
As you can see, its easier to just pass values from PHP to jQuery... Is there another way?
You can assign more data values, and you know what use is logged in, all you need is to pass who to follow:
<div class='btn btn-mini follow-btn'
data-status='follow'
data-who='<?php echo $randId; ?>'
id='followBTN'>
Follow
</div>
<script>
$('#followBTN').on('click', function(){
$.ajax({
url: '../follow.php',
type: 'post',
data: {
iduser_following: $(this).attr('data-who')
},
success: function(data){
$('.follow-btn').attr("data-status",'follow');
$('.follow-btn').text(data.text);
}
});
});
</script>
You can process $_SESSION['user_auth'] and the status directly from PHP, there is no need for you to pass them in jQuery. Make sure document is ready when you insert on click event.
just use the jquery 'on' event. Attach a new attribute called data-session to the div and then retrieve it using .attr method. You have the example bellow to show you an alert with the data, you just have to substitute it with your code
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(document).on('click', '#follow-me-button', function(){
alert($(this).attr('data-session'));
})
})
</script>
</head>
<body>
<div id="follow-me-button" class='btn btn-mini follow-btn' data-status='follow' data-session ="MY-SESSION-DATA-FROM-PHP">
Follow
</div>
</body>
</html>

Categories