AJAX execute php without refreshing page - javascript

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.

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.
});

How to use data from one HTML page to retrieve data to be used on another HTML page using ajax

I would like to use the 'sID' in the first HTML form to retrieve data from the database and then use the data retrieved from the database on the second HTML page. I can do this with just php, but I just can't figure out how to do it using ajax.
I'm really new to javascript/ajax so please be gentle with your answers :)
HTML 1
<div class="moreR">
<form action="moreR_2.0.php" method="GET">
<input type="hidden" name="sID[]" value="a_certain_ID"/>
<input type="image" src="Icons/PNG/greater_than.png" alt="submit"/>
</form>
</div>
PHP (moreR_2.0.php)
<?php
include ('session_start.php');
include ('db_connect_mO.php');
if (isset($_GET['sID'])) {
foreach($_GET['sID'] as $sID) {
}
}
$sql = mysqli_query($con, "SELECT * FROM mo WHERE sID=$sID");
$row = mysqli_fetch_array($sql);
while ($row = mysqli_fetch_assoc($sql))
{
$test[]= array(
'pZero'=> $row['pZero'],
'pZero_Gname'=> $row['gZero_key'],
);
}
header('Content-Type: application/json');
echo json_encode ($test);
//detailed error reporting
if (!$sql)
{
echo 'MySQL Error: ' . mysqli_error($db);
exit;
}
?>
JavaScript
$(document).ready(function() {
"use strict";
function connect2mR() {
$.ajax({
url:"moreR_2.0.php",
type: "GET",
data:'sID',
dataType:"json",
//async:false,
success:function(data)
{
$('#pZero').html('<img src="rPlanets/' + this.gZero + '.png" alt=""/>');
$('#pZero_keys').html(this.gZero_key);
}, //success
}); //end of ajax
} //end of function
if (window.attachEvent) {window.attachEvent('onload', connect2mR);}
else if (window.addEventListener) {window.addEventListener('load', connect2mR, false);}
else {document.addEventListener('load', connect2mR, false);}
});
HTML 2
<section class="moreR_section">
<div style="width:20%;"><div id="pZero"></div></div>
<div class="moreR_g" style="margin-left:26%" id="pZero_keys"></div>
</section>
What i'm trying to do is; start from HTML 1, collect sID -> then PHP/JS use sID from HTML 1 to get data from database -> then use the result from database on HTML 2. At the moment i'm struggling on how to make this process work. Can't figure out how to start from HTML 1 and end up in HTML 2.
You are not fetching the data from the input element at all.. change your ajax code to below.
$.ajax({
url:"moreR_2.0.php",
type: "GET",
data:{sID: $('input[name="sID[]"]').val()}, // this is the change
dataType:"json",
//async:false,
success:function(data)
{
$('#pZero').html('<img src="rPlanets/' + this.gZero + '.png" alt=""/>');
$('#pZero_keys').html(this.gZero_key);
}, //success
}); //end of ajax
Edit 1: you can use localstorage to save data and retrieve from there when ever required. So you can do as below
In your HTML 1 write this.
localStorage.setItem('sID', JSON.stringify( $('input[name="sID[]"]').val()));
And in HTML 2 you can access the value by reading it from the local storage like below,
var sIDofHTML1 = JSON.parse(localStorage.getItem('sID'));
You will have to update the ajax as below.
data:'sID', // this has to change to data:'sID='+sID,
$.ajax({
url:"moreR_2.0.php",
type: "GET",
data:'sID', // this has to change to data:'sID='+sID,
dataType:"json",
//async:false,
success:function(data)
{
$('#pZero').html('<img src="rPlanets/' + this.gZero + '.png" alt=""/>');
$('#pZero_keys').html(this.gZero_key);
}, //success
}); //end of ajax

Updating data with Ajax loading does not work

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).
}
});
});

why is my form not submiting using ajax

bit of a selfish question but I am really strugerling with ajax in general so I need some help. So basically Im trying to update and sql database using an 'onblur' function. heres my code:
code on index.php
function saveStatus(){
var status =document.getElementById("statusForm").value;
$.ajax({
url: 'saveStatus.php',
type: 'post',
data: 'feed_id=' + status,
success: function(result){
}
}
<form id="statusUpdate" action = "whosout.php" method="post">
<input type="text" id="statusForm" onblur="saveStatus()"
placeholder="<?php if($status!=null){ echo '‘'.$status.'’';}
else { echo 'Enter your status here.';}?>">
</form>
and code on saveStatus.php
<?
require 'core.php';
require 'connect.php';
$status = $_POST['feed_id'];
$idPerson = $_SESSION['user_id'];
$query = "UPDATE person SET status = '".mysql_real_escape_string($status)."'
WHERE idPerson = '$idPerson'";
$query_run = mysql_query($query);
?>
at the moment the sql database does not update when i click of the input box. Any help would be great!!
Answer:
You have to devide scripts and html output
You forget );.You have to close $.ajax block.
You miss } closing function saveStatus().
Code:
<script>
function saveStatus(){
var status =document.getElementById("statusForm").value;
$.ajax({
url: 'saveStatus.php',
type: 'post',
data: 'feed_id=' + status,
success: function(result){
}
}); // <-- Also, you forget `);` here
} // <-- Also, you foget closing `}` here
</script>
<form id="statusUpdate" action = "whosout.php" method="post">
<input type="text" id="statusForm" onblur="saveStatus()"
placeholder="<?php if($status!=null){ echo '‘'.$status.'’';}
else { echo 'Enter your status here.';}?>">
</form>
Not error, but advice:
Also, note this: you used jQuery ajax function, so use jQuery in other cases too (you used pure JavaScript instead).
You getting value this way:
var status = document.getElementById("statusForm").value;
Use jQuery syntax instead:
var status = $("#statusForm").val();
Additional info
As, #Utkanos noticed in comments to this answer:
...all of which would be obvious if you look in the error console.
You have to use some debug tool, like FireBug or DevTools (Chrome, also in Chrome you can use CTRL+SHIFT+J). Not have to. You MUST do it.

Call function inside CodeIgniter's controller using jquery / ajax

Can somebody please explain to me what is the right way to call a php function with jquery / ajax in Codeigniter. Right now, this code isn't working and i cant figure out whay. Note that admin.php controler is inside admin map. Thanks in advance
html code
<form action="#" method="POST" id="change">
<input type="hidden" value="<?php echo $row->id_product; ?>" id="prod" >
<input type="submit" value="switch" >
</form>
<div class="resultdiv">
<?php echo $data; ?>
</div>
my function inside admin.php controller
public function do_search(){
$id = $this->input->post('id');
return $id;
}
Jquery AJAX script
$( "#change" ).submit(function() {
alert( "Change" );
var id = $('#prod').val();
$.ajax({
type:'POST',
url:'admin321/do_search',
data:{'id':id},
success:function(data){
$('#resultdiv').html(data);
}
});
});
Config / routes.php
$route['admin/do_search'] = "admin_controller/admin/do_search";
I know that this is old post, but maybe someone will find this usefull.
I solve this problem by adding index.php in url. Even if the index.php is hidden using rewrite.
$( "#change" ).submit(function() {
alert( "Change" );
var id = $('#prod').val();
$.ajax({
type:'POST',
url:'<?php echo base_url("index.php/admin/do_search"); ?>',
data:{'id':id},
success:function(data){
$('#resultdiv').html(data);
}
});
});
Maybe like this:
$( "#change" ).submit(function() {
alert( "Change" );
var id = $('#prod').val();
$.ajax({
type:'POST',
url:'<?php echo base_url("admin/do_search"); ?>',
data:{'id':id},
success:function(data){
$('#resultdiv').html(data);
}
});
});
You have to load this helper:
$this->load->helper('url');
#edit
$route['admin/do_search'] = "admin_controller/admin/do_search";
This code is unnecessary.
In the past, I have set up a route for the ajax request. Something like this:
$route['admin/search/(:any)'] = 'admin_controller/admin/do_search/$1';
Then my ajax request would look like this:
var prod = $('#prod').val();
$.ajax({
type: 'post',
url:'admin/search/'+prod
...
});
Or, you can grab the form action via jQuery and use that as your url.
<form action="admin/search/123" method="post">
$.ajax({
type: 'post',
url: $('form').attr('action')
...
});
I know this works. My routes file is the default.
I loaded CI URL helper in my controller __construct() function
$this->load->helper('url');
Here's my ajax:
/*
*Ajax function to load confirmation page
*/
var formID=$("div form");
formID.submit(function(event){ //activated on submit event
event.preventDefault(); //stops page from reloading
$.ajax({
type:"POST",
url:'<?php echo site_url("plan/process")?>',
data:formID.serialize(),
success:function(data){
$("div #msg_area").html(data);
window.setTimeout(function(){parent.location.reload()},3000);
}
});
});
I have multiple controllers so it calls the specific one call plan and the \n the function process. The process function one looks like this:
function process (){
$json_data = strtolower(json_encode($this->input->post()));
$res = array();
//Simple Error/success display...
$res = json_decode($this->plan->process_plan($json_data ),true);
if(array_key_exists('error',$res)){
$window = "warning";
$error=explode(":",$res['error']);
$result['message']="<h2><span class='color-dark'>Submission error:</span> ".$error[0]." </h2><p>".$error[1]."</p>";
}
else{
$window = "success";
$result['message'] = "<h2>Submission was a success</h2>";
}
echo $this->load->view("common/components/".$window,$result);
}
This works great for me. Hopefully it helps.
in your routes file you have: admin321/do_search NOT: admin/do_search
You can also try using the absolute path:
`http://www.website.com/admin/do_search` or `http://localhost/admin/do_search`
in the ajax url parameter

Categories

Resources