reload a div again without using load() - javascript

I have a form through which I want to upload a user's name which works fine but want to display it right after he uploads it by clicking "Save" button(of submit type) without reloading the page.Right now, the name is getting uploaded but appears only when I reload the page.Any suggestions?Please dont suggest using load() as it has compatibility problem with different browsers.
<div id="nameform">
//contains code to upload name via form
</div>
<div id="name">
<?php
$query1=mysqli_query($dbc,"select * from users where Email='".$_SESSION['Email']."'");
$row=mysqli_fetch_assoc($query1);
$name=$row['name'];
if ($name!="")
echo "$name";
else echo "Your name please....";
?>
</div>
$("#btn").click(function() {//#btn is a submit button in the form
document.getElementById("name").style.display="block";
document.getElementById("nameform").style.display="none";
});
$("#formname").submit(function () {
$.ajax({
url:"formname.php",
data:$("#formname").serialize(),
type:"POST",
success:function(data){
console.log(data);
if(data=="xyz"){
$("#formname")[0].reset();
$("#formname").on("click",".sframe",f(0));
}
},
error:function(data){
alert("Network error");
}
})
return false;
});

I am assuming that you have written insertion code in ajax page formname.php. On Ajax call if the name successfully inserted in database you fetch the name using your select query
$query1=mysqli_query($dbc,"select * from users where Email='".$_SESSION['Email']."'");
$row=mysqli_fetch_assoc($query1);
$name=$row['name'];
and echo the user name.
else
echo "0" for error handling .
now in your ajax call script instead of
if(data=="xyz"){
$("#formname")[0].reset();
$("#formname").on("click",".sframe",f(0));
}
put
if(data!=0){
$("#name").text(data); // It will put the name in the div
$("#formname").on("click",".sframe",f(0));
}
else
{
alert("Data insertion error");
}

Related

How to save JSON data to new JSON file through iterating using AJAX and PHP?

I have simple movies editor with the sidebar in which user just drag and drop the element to the right side user can edit this element as they wish and save data to JSON, I want when the user clicks to save it should create a new file and save to it new data.
so far here is what I have
HTML
<div class="col-2 save-details">
<div id="save-block">
<button type="button" class="btn btn-success btn-save">Save</button>
</div>
</div>
here is js to save the file
var moviesblocks =null;
$(document).ready(function(){
$.getJSON('moviesblocks.json', function (data) {
moviesblocks = data.moviesblocks;
console.log(moviesblocks);
});
$("#main-btn-save").on("click", function () {
var moviesparams = JSON.stringify({
moviesblocks: moviesblocks
});
$.ajax({
type: 'POST',
data: {
moviesparams: moviesparams
},
url: 'save_movies_block.php',
success: function (data) {
$('#msg').html(data).fadeIn('slow');
$('#msg').delay(2000).fadeOut('slow');
},
error: function () {
$('#error-msg').html(data).fadeIn('slow');
$('#error-msg').delay(2000).fadeOut('slow');
}
});
console.log(moviesparams);
});
})
Here is php file to handle the process
<?php
if(isset($_POST['moviesparams'])){
$moviesparams = json_decode($_POST['moviesparams']);
// do whatever checks you need on $moviesparams to verify valid data
$success = file_put_contents("moviesblocks.json", json_encode($moviesparams));
if($success === false){
echo "sorry , something is wrong";
die();
}else{
echo "Data successfully saved";
die();
}
} else {
echo "nic";
}
$data=file_get_contents("data.json");
$result=json_decode($data);
?>
As you can see now after user clicks save it save to this file
moviesblocks.json
Now I want when a user clicks save, it should save to new file
something like moviesblocks1.json instead of moviesblocks.json
Here is a live demo live demo
How can I achieve what I want?
If you dont wanna use database, you need to create one more file to maintain file version numbers. Each time you wanna create new file, get the latest version number from this version.txt file and append it to filename. Eg : moviesblocks1.json, moviesblocks2.json.
After creating new file, update the version from version.txt. This will help you to create new version number next time.

I can't delete specific row in my database?

Following is the code I used to print the delete button for each data echoed.
<?php
$sno=1;
while($row=mysqli_fetch_assoc($datas)){
echo('<b><tr><td>'.$sno.'</td><td>' .$row['id'].'</td>
<td>'.$row['name'].'</td>
<td>'.$row['address'].'</td>
<td>'.$row['faculty'].
"</td><td>
<button onclick=deletee(); name='del_user' value='<?= $row['id']; ?>'> Delete </button><br>
</td></tr>");
++$row;
$sno++;
}
?>
In script;
function deletee() {
<?php
$datas="";
$sql="";
$idd=$row['id'];
$datas=mysqli_query($database,"SELECT*FROM data");
if(isset($_POST['delete_user'])){
$newrow=mysqli_fetch_assoc($datas);
if($newrow['id']==$idd)
{
$sql = "DELETE FROM data WHERE id='$idd' ";
mysqli_query($database,$sql);
header("Location: main.php");
}
}
?>
}
Yet I'm not able to delete a specified tuple. Whats the problem?
I'm trying to delete a row.
"After every data row is a delete button which deletes a specific row."
A better option to your above would be to create your button as
<button onclick=deletee(<?=Row['id'] ?>)
From there your function would be
function deletee(int id){
var url = "/Url/Where/PHP/is/run"
$.ajax({
url: url,
type: "post",
data: { id = id },
success: function (response) {
// Redirect to a page, or update whats displayed on the page here
},
error: function(jqXHR, textStatus, errorThrown) {
// do your error logging / display to page here
}
});
Now you just create a page to run the delete via your php and make sure the url in the ajax function points to that page, and it accepts a field called "id" (Note, this is using as a "POST", you can change to get etc. just make sure you do some checking on the data sent through.
If you don't want to use jquery at all, an alternative would be to make every lineitem a form pointing to the same url with a different value i.e.
//line item details Here
// where the submit button is use the code below instead
<form action="url/with/php/code" method="post">
<input type="hidden" name="id" value="<?= $row['id']?>" />
<input type="submit" value="delete">
</form>
Then have the php form it directs to check for post values, and redirect on success / do what it needs to do on failure

HTML Javascript $_post response shows the PHP header location page and not forwarding

I have a html code which sends the input to the PHP where the php redirect to a login page.
But when i do the post request as bellow, it gives a response back to the javascript; with the forwarding index.html code without redirect to the index.html.
<script>
function Sendmeaway() {
var item_i = document.getElementById("item_select").value;
if (item_i == "Initial_Value") {
alert("Please Select the Correct Option or Enter the Comment");
} else {
$.post("./back_p/add_change_req.php", {
item : item_i
},
function(data, textStatus) {
alert("Response from server: " + data);
document.getElementById("item_select").selectedIndex = 0;
location.reload();
});
}
};
</script>
PHP code (it works fine when i go directly to the php)
<?php echo $_POST["item"]; header('location: ../index.html'); ?>
You can't redirect users like that. AJAX calls can only send and recieve data.
Instead redirect the user using window.location.href = '' in the success function of your AJAX call.
So instead of
<?php echo $_POST["item"]; header('location: ../index.html'); ?>
Do
<?php echo $_POST["item"]; return '../index.html'; ?>
Then use that returned value inside your script like:
function(data, textStatus) {
alert("Response from server: " + data);
document.getElementById("item_select").selectedIndex = 0;
window.location.href = data;
});
When you make an ajax call you need to change the page on javascript side like that. You can send 0 or 1 from php to decide redirecting or not.
Instead of using php header, use a <meta> tag outside the PHP tag
Such as:
<?php
echo($_POST["item"]);
?>
<meta http-equiv="refresh" content="5;URL='../Index.html'" />
replacing the 5 after content=" to however many seconds you want until the redirect executes

"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 call not working - PHP, MySQL, jQuery/Ajax

I have the following problem:
What i'm trying to accomplish is:
User clicks on a submit/image type button
Ajax call handles the submit, calls another PHP script to update a record in a MySQL table, all without reloading the page ( obviously )
My PHP code is working fine without the AJAX, as it will reload and update the record. but somehow the ajax call is not working and/or returning any error.
My code:
$(function() {
$('#like_form').submit(function(event) {
event.preventDefault(); // Preventing default submit button
var formEl = $('#like_form');
var submitButton = $('input[type=submit]', formEl);
$.ajax({
async: true,
type: 'POST',
url: formEl.prop('action'),
accept: {
javascript: 'application/javascript'
},
beforeSend: function() {
submitButton.prop('disabled', 'disabled');
}
}).done(function(data) {
submitButton.prop('disabled', false);
$("#like").fadeOut();
$("#like").fadeIn();
});
});
});
<!-- LIKE een gebruiker -->
<form action="" id="like_form" method='POST' enctype="multipart/form-data">
<input onmouseover="this.src='img/heart2.png'" onmouseout="this.src='img/heart.png'" name='like' id="like" src='img/heart.png' type="image" />
</form>
my PHP (just in case):
<?php
include_once "dbconnection.php";
//if like button (submit button) clicked
if ($_POST){
$conn = DatabaseConnection::getConnection();
$sql = "UPDATE dating_members
SET likes = likes + 1
WHERE member_id = 3";
$stmt = $conn->prepare($sql);
$stmt->execute();
}
?>
I figured out what the problem is, Kind of silly I didn't notice but better late than never.
I had to 'include' the JS script at the end of my PHP page in order to catch my onsubmit function and therefore disable the default event a.k.a submit button submitting my form and page reload / POSTs to the other PHP file.
Everything is working fine now

Categories

Resources