Updating data with Ajax loading does not work - javascript

I have an admin page which can insert, update and delete data. I want to display a simple loading gif while doing any of these operations. All of the 3 operations work perfectly, but when I try to make some Ajax with it, it stops working.
Below is my Ajax code. This code simply shows a div which has the loading gif within it, right after submitting the form, and if it's successfully accomplished, hides it again. That easy.
$("#form").submit(function(e) {
e.preventDefault();
$("#loading").show();
$.ajax({
url: "Operations.php",
dataType: "HTML",
success: function() {
$("#loading").hide();
}
});
});
Now, the Operations.php, that is executed by every form, contains the 3 database operations. It stores the name of the class sent by a hidden field, receives the value from the button of the submitted form and depending on its value, it instantiates the ServiceDatabase passing the class and perform one action.
$class = filter_input(INPUT_POST, "class");
$id = filter_input(INPUT_POST, "id");
#require_once "../../php/Connection.php";
#require_once "../../php/ServiceDatabase.php";
#require_once "../../php/" . $class . ".php";
$Operation = new ServiceDatabase($connection, new $class);
switch ($_REQUEST["submit"]) {
case "insert":
$Operation->setPostVariables();
$Operation->insert();
break;
case "update":
$Operation->setPostVariables();
$Operation->update($id);
break;
case "delete":
$Operation->delete($id);
break;
}
And finally, just the form.
<form id="form" class="center-block" action="Operations.php" method="post">
<h3>Alterar - <small><?php echo $class ?></small></h3>
<input type="hidden" value="<?php echo $class ?>" name="class"/>
<input type="hidden" value="<?php echo $id ?>" name="id"/>
<?php echo $Table->generateAdminTables($id); ?>
<button type="submit" name="submit" value="update" class="btn btn-success btn-update">Atualizar</button>
</form>
What happens is that the database operation, in this case, the update, doesn't work, like if it is not reaching the Operations.php file.

You need to set the POST data which you get from the form.
$.ajax({
url: "Operations.php",
method: "POST", // defaults to get
data: $(this).serialize(), // get the form data and send it
dataType: "HTML",
success: function() {
$("#loading").hide();
}
});

It seems $_REQUEST doesn't work with Ajax. What a surprise.
My solution is: I created a new hidden in the forms to receive via jQuery the value of the clicked button:
btnValue = "";
$("#form button").click(function() {
btnValue = $(this).attr("value");
});
Then right before the $.ajax, I set the hidden value:
$(this).find("#action").attr("value", btnValue);
In my Operations.php, a new $_POST value is received
$action = filter_input(INPUT_POST, "action");
And in the switch block, I just check $action
switch ($action) {
case "insert": ...
case "update": ...
case "delete": ...
}
Worked perfectly.

Try this one. I have not tested but it will work.
$("#form").submit(function (e) {
e.preventDefault();
$("#loading").show();
$.ajax({
url: "Operations.php",
dataType: "HTML",
success: function () {
$("#loading").hide();
},
error: function (data) {
},
complete: function (data) {
$("#loading").hide();
//A function to be called when the request finishes
// (after success and error callbacks are executed).
}
});
});

Related

"Like" system PHP, using AJAX

i want to make like/unlike system with PHP and jQuery/AJAX..
Here is my form in PHP foreach... Here i have own id's for every form;
<?php foreach ($vid as $var) { ?>
<form class="classform" action="functions/videolike.php" method="post">
<input type="text" name="id" value="<?php echo $var['video_id'];?>">
<button class="submitbuttonclass"type="submit">Like</button>
</form>
<?php } ?>
Here is my Ajax script;
<script>
// this is the id of the submit button
$(".submitbuttonclass").click(function() {
$.ajax({
type: 'post',
url: "functions/videolike.php",
data: $(".classform").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
</script>
the codes are working but not correctly;
When i click "like" button is working good, i cheked the database, caunting, inserting, deleting , working good...
But I want to make this with AJAX becouse, refreshing page is stopping the video when user watching video if he click the like button. Video is preloading becouse page refresh...
After i add my ajax script its working. But when i am clicking the like button, AJAX is posting to PHP, only the last id in the foreach loop,
THE Question?
How to make AJAX to get all of the id's in PHP foreach loop ??
And this is my videolike.php if you want to check;
<?php
session_start();
if($_POST['id'] && #$_SESSION["userid"]){
require_once "connectdb.php";
$id = $_POST["id"];
$VLcheck = "SELECT count(*) FROM `videolikes` WHERE user_id = ? AND liked_vid_id=?";
$reslike = $conn->prepare($VLcheck);
$reslike->execute(array($_SESSION["userid"],$id));
$VLrow = $reslike->fetchColumn();
echo $VLrow;
if ($VLrow > 0){
$VLcheck = "DELETE FROM `videolikes` WHERE user_id = ? AND liked_vid_id=?";
$reslike = $conn->prepare($VLcheck);
$reslike->execute(array($_SESSION["userid"],$id));
} else {
$curentsess= $_SESSION["userid"];
$INSlike = $conn->prepare("INSERT INTO videolikes(user_id, liked_vid_id)
VALUES('$curentsess','$id')");
$INSlike->execute();
}} else {die;}
?>
As you have a lot forms with class .classform, so how do you think your script should select the proper one?
The asnwer is - script can't, you should help it). Use .closest function to find closest <form> for a clicked button:
$(".submitbuttonclass").click(function() {
var form = $(this).closest("form");
// or find closest element with class `classform`
//var form = $(this).closest(".classform");
$.ajax({
type: 'post',
url: "functions/videolike.php",
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});

AJAX execute php without refreshing page

I don't understand javascript,AJAX very well and need to do this code fast, so if you guys can help, it would be great !
I have a like button on my webpage that allows users to like content:
The html code is as follows:
<form action=\"\" method=\"post\" enctype=\"multipart/form-data\"><button name=\"like$i\">like</button></form>
And the php code:
for ($i = 100; $i >= 0; $i-=1) {
$primid = latest1($i);
$id = $user_data['id'];
if(isset($_POST["like" . $i]) && already_liked($id, $primid)===false) {
add_like($id,$primid);
}
if(isset($_POST["like" . $i]) && already_liked($id, $primid)===true){
echo "you have already liked this art";
}
}
All of the code works fine, but when I click the like button; the page refreshes wich is not ideal ...
I know you can use AJAX to fix this problem; i have looked for answers but they all seem to be for forms with content to insert ect ...
I'm sorry if i seem lazy but i have to finish this fast and don't have time to learn ajax properly for the moment :S
Thanks in advance =)
Observe the following code:
jQuery.ajax({
url: '/some/file.php', //link to your php
method: 'POST', // Method, you can use GET too
data: $('#the-form').serialize() //get form values
}).done(function (response) { //works if response is success
// Do something with the response
}).fail(function () { //works if response is fail
// Whoops; show an error.
});
You can do something like this:
HTML
<form action="" method="post" id="likeForm" onsubmit="return false;">
<input type="submit" name="like<?php echo $id; ?>" value="Like" />
</form>
Sidenote: onsubmit="return false;" is used to prevent uncaught exception: out of memory error in ajax.
jQuery
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#likeForm').submit(function(){
var value = $(this).children().attr('name');
var param = {value: value};
$.ajax({
type: 'POST',
url: 'yourpage.php', // change this yourpage.php to point to a page where you want to process your ajax request
cache: 'false',
data: param,
beforeSend: function(){
// before send
},
success: function(data){
// success
},
error: function(){
// error
}
});
});
});
</script>
yourpage.php
<?php
for($i = 100; $i >= 0; $i-=1) {
$primid = latest1($i);
$id = $user_data['id'];
if(isset($_POST['value']) && $_POST['value'] == "like" . $i && already_liked($id, $primid)===false) {
add_like($id,$primid);
}
if(isset($_POST['value']) && $_POST['value'] == "like" . $i && already_liked($id, $primid)===true){
echo "you have already liked this art";
}
}
?>
Just to compile the all things that you need:
JavaScript code:
function submitFormData(inputForm) {
jQuery.ajax({
url: '/some/file.php', //link to your php
method: 'POST', // Method, you can use GET too
data: $(inputForm).serialize() //get form values
}).done(function (response) { //works if response is success
// Do something with the response
}).fail(function () { //works if response is fail
// Whoops; show an error.
});
}
Html code:
<form action="" method="post" enctype="multipart/form-data">
<button type="button" onclick="submitFormData(this.form);" name="like$i">like</button>
</form>
Good luck with task implementation.

Ajax form submit on current page

I want to submit a form by ajax and send it to my current page to prevent a refresh.
This my HTML:
<form id="suchForm" method="post" action="<?=$PHP_SELF?>">
<input type="text" id="suche" name="suche" placeholder="Suchen"/>
<input type="submit style="display:none;" />
</form>
By the way the submit button is hidden, so I am submitting the form by pressing return on my keyboard.
This is my PHP Script:
if ( $_SERVER["REQUEST_METHOD"] == 'POST' ) {
$suche = $_POST['suche'];
if (!empty($suche)) {
<?php echo $suche ?>
}
}
And finally, this is my current Ajax script:
var frm = $('#suchForm');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert('ok');
}
});
ev.preventDefault();
});
The form is submitting by Ajax successfully. The Problem: The Ajax Script prevents a refresh of the site, so nothing is shown by the PHP script (<?php echo $suche ?>). Do you have any solution to send the form with Ajax, preventing the refresh (cause some javascript should happen after the submit) and show the PHP echo?
Try replacing alert('ok'); with the code to display the ajax response. Something like this should work -
var frm = $('#suchForm');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
$('<NAME_OF_YOUR_CONTAINER_TO_DISPLAY_RESPONSE>').html(data);
}
});
ev.preventDefault();
});
If $suche is not empty, php will echo it. So if you could view the page at the time, you would see what you expect, but in this case, you have AJAX doing the submit for you, so AJAX is the one who can "see" that. If you want to display what AJAX can "see", then simply do whatever you want inside success: function()... that received the data.
You could alert(data) instead of alert("OK") to get more clues.

jQuery ajax form doesn't work

I tried many ways to create a simple jquery ajax form but don't know why it is not submitting and/or returning the notification.
Here is my code:
Javascript
...
<script type="text/javascript" src="assets/js/jquery1.11/jquery-1.11.0.min.js"></script>
...
$('#form_signup').submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'signup.php',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
console.log(data);
$('#form_signup_text').html(data.msg);
},
error: function (data) {
console.log(data);
$('#form_signup_text').html(data.msg);
}
});
});
HTML
<form id="form_signup" name="form_signup" method="POST">
<div>
<input type="email" id="inputEmail1" name="inputEmail1" placeholder="your#email.com">
</div>
<div>
<a type="submit">Sign up!</a>
</div>
<div id="form_signup_text">
<!-- A fantastic notice will be placed here =D -->
</div>
</form>
PHP
<?php
$our_mail = "our#email.com";
$subject = "Wohoo! A new signup!";
$email = $_POST['inputEmail1'];
$return = array();
$return['msg'] = 'Thank you!';
$return['error'] = false;
if(preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)){
$message = "Yesss!! We receive a new signup!
E-mail: $email
";
mail($our_mail, $subject, $message);
}
else {
$return['error'] = true;
$return['msg'] .= 'Something is wrong... snifff...';
}
return json_encode($return);
Solved:
There were three problems. And different users solve each of these problems.
In PHP, you must "echo" the return array instead of "return"
At first, you should use a submit button instead of an anchor in the form
In the input, you must set both "id" and "name"
If any of these users want, you can edit or add a new answer with these details, and the points are yours.
You need to do 3 things.
First, wrap your jQuery codes inside $(document).ready() function,
<script type="text/javascript">
$(document).ready(function()
{
$('#form_signup').submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'signup.php',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
console.log(data);
$('#form_signup_text').html(data.msg);
},
error: function (data) {
console.log(data);
$('#form_signup_text').html(data.msg);
}
});
});
});
</script>
Second, Add a submit button to your form. Also you are missing the name attribute for the email input field. That causes the error in the php file.
<form id="form_signup" name="form_signup" method="POST">
<div>
<input type="email" id="inputEmail1" name="inputEmail1" placeholder="your#email.com">
</div>
<div>
<input type="submit" name="signup" value="Sign Up!"/>
</div>
<div id="form_signup_text">
<!-- A fantastic notice will be placed here =D -->
</div>
</form>
Third, echo the results since you are using AJAX to submit the form. return will not have any effects.
<?php
$our_mail = "our#email.com";
$subject = "Wohoo! A new signup!";
$email = $_POST['inputEmail1'];
$return = array();
$return['msg'] = 'Thank you!';
$return['error'] = false;
if(preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)){
$message = "Yesss!! We receive a new signup!
E-mail: $email
";
mail($our_mail, $subject, $message);
}
else {
$return['error'] = true;
$return['msg'] .= 'Something is wrong... snifff...';
}
echo json_encode($return);exit;
I checked and it's working fine.
Hope this helps :)
The problem is in your form.
<form id="form_signup" name="form_signup" method="POST">
<div>
<input type="email" id="inputEmail1" name="inputEmail1" placeholder="your#email.com">
</div>
<div>
<input type="submit" name="submit" value="Submit">
</div>
<div id="form_signup_text">
<!-- A fantastic notice will be placed here =D -->
</div>
</form>
The php code needs to echo instead of return.
just like this:
echo json_encode($return);
Also, your form needs a submit button - type="submit" on an <a> tag doesn't trigger the browser's functionality for handling <form>s
Finally, you need to ensure that your special submit handler is loaded at just the right time -- which, if it is included at the bottom of the page, right before the footer, it should be just fine. However, you can ensure this by wrapping it in
$(document).ready(function(){
//[...]
});
doesn't your a type="submit" need to be an input instead? or a button
I am trying to call webmethod in a ajax using jquery in asp.net, but sometimes it works well and sometimes it doesn't.
Here is my ajax code :
$.ajax({
type: "POST",
url: "frmTest.aspx/fncSave",
data: "{}"
contentType: "application/json; charset=utf-8",
dataType: "json",
async: "false",
cache: "false", //True or False
success: function (response)
result = response.d;
if (result != "") {
alert(response);
}
},
Error: function (x, e) {
alert("err");
return false;
}
});
Here My Server Side Code :
<WebMethod()>
Public Shared Function fncSave() As String
Dim sResult As Int16
Try
Dim obj As New ClsCommon()
sResult = obj.Save()
Catch ex As Exception
ex.Message.ToString()
End Try
Return sResult
End Function
$(this) in the "ajax" function is not the form.
So just try:
$('#form_signup').submit(function(event) {
event.preventDefault();
var $this = $(this);
$.ajax({
type: 'POST',
url: 'signup.php',
data: $this.serialize(),
dataType: 'json',
success: function (data) {
console.log(data);
$('#form_signup_text').html(data.msg);
},
error: function (data) {
console.log(data);
$('#form_signup_text').html(data.msg);
}
});
});
I admit i didn't check the rest of the code, im pretty sure thats the problem.
Of course if the problem still goes, just "f12" and check console and network for server request and headers, make sure all the params are there.
Hope that helped

Is there an error in this jquery file?

$(document).ready(function(){
/* fetch elements and stop form event */
var submitData = $("form.follow-form").submit(function (e) {
/* stop event */
e.preventDefault();
/* "on request" */
$(this).find('i').addClass('active');
/* send ajax request */
$.ajax({
type: "POST",
url: "recycle.php",
data: submitData,
dataType: "html",
success: function(msg){
if(parseInt(msg)!=0)
{
/* find and hide button, create element */
$(e.currentTarget)
.find('button').hide()
.after('<span class="following"><span></span>Recycled!</span>');
}
}
});
});
});
I think there is an error in this jquery syntax and or it could be my php code, I cant seem to find it!!
this is the recycle.php
<?php session_start();
include_once ('includes/connect.php');
$id = $_POST['id'];
$tweet =$_POST['tweet'];
mysql_query("INSERT INTO notes SET user_note='".$_POST['tweet']."',dt=NOW(),recycle_id='".$id."', user_id = '".$_SESSION['user_id']."' ");
?>
and this is the html code
<form class="follow-form" method="post" action="recycle.php">
<input name="id" value="$id" type="hidden">
<input name="tweet" value="$tweet" type="hidden">
<button type="submit" value="Actions" class="btn follow" title="123456">
<i></i><span>recyle</span>
</button>
</form>
Your use of submitData looks strange to me. You don't have to declare that variable and it will not contain the data of the form (I think submit() returns nothing, so submitData would be undefined).
I think you have to do:
$("form.follow-form").submit(function (e) {
//...
$.ajax({
type: "POST",
url: "recycle.php",
data: $(this).serialize(), // gets form data
dataType: "html",
success: function(msg){/*...*/}
});
});
Reference: .serialize()
If you're using jQuery you probably already know this, but if you use Firebug it should show you any syntax errors. Just a thought.

Categories

Resources