why is my form not submiting using ajax - javascript

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.

Related

Setting PHP session variables with ajax

Want to change value of SESSION variable "fullname" without refreshing the page.
My implementation using ajax:
Page 1 html:
<input type="text" name="fullname" id="fullname" placeholder="Full name">
<button onclick="setSession()"> GO </button>
Page 1 script:
<script>
function setSession(){
var fullname = $("#fullname").val();
var dataString = 'fullname=' + fullname;
$.ajax({
type: "POST",
url: "Page2.php",
data: dataString,
cache: false,
success: function( data ) {
if(data === 'True'){
alert("<?php echo $_SESSION['fullname'];?>");
}
}
});
}
</script>
And in Page 2:
session_start();
$_SESSION["fullname"] = $_POST["fullname"];
echo 'True';
exit();
It doesn't change the value of the session variable.
Both pages have session_start().
Your code should already be changing the value in the PHP session. You just don't have your client-side script set up properly to show that.
Return some kind of indicator in your PHP script:
<?php
// Page2.php
session_start();
$_SESSION["fullname"] = $_POST["fullname"];
echo 'set session fullname to ' . $_POST['fullname'];
Then in your AJAX success function, show that response:
...
success: function( response ) {
alert(response);
}
...
When you use alert("<?php echo $_SESSION['fullname'];?>"); in your success function, PHP will fill in the $_SESSION['fullname'] value in that alert box once when the page loads, and it will never change until the page is reloaded, even if you do successfully update the session value via AJAX.
First, have you watched the AJAX request / response in the browser's developer tools? Have you included the jQuery library in the project? Are there any errors reported? Are you running this on a web-server?
Second, you're starting a session in a remote page. That session data will not be available in the current page until you reload the current page. In addition you have some wonky quoting in your alert, it should be:
alert("<?php echo $_SESSION['fullname'];?>");
Page 1 HTML
<input type="text" name="fullname" id="fullname" placeholder="Full name">
<button onclick="setSession()"> GO </button>
Page 1 Script
<script>
function setSession(){
$.ajax({
type: "POST",
url: "Page2.php",
data: { fullname: $("#fullname").val() },
dataType: "json",
cache: false,
success: function( data ) {
alert(data.fullname);
}
});
}
</script>
Page 2 PHP Script
session_start();
$_SESSION["fullname"] = $_POST["fullname"];
echo json_encode(array('fullname' => $_SESSION['fullname']));
It's generally a bad idea to mix server-side and client-side scripts together so try to separate your PHP and Javascript logic. They both execute at different times/stages of a page request life-cycle.
You are setting the variable in JS using PHP Inline coding. You could however echo the session variable in page2 if no post has been set. If you then request page two without any post you can use the response body in JS to get the current set session variable and put it in a JS variable.
Var name;
$.get(‘page2.php’, function(data){ name = data; } );
I’m using the iOS app so above code is not complete but an indication for what can be done.

"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.

sending php and js variables through ajax to php page and mysql table

I have been looking to some similar questions, but none seem to provide the specific answer I am looking for. I have a few js variables, which are being passed through ajax to a location.php, which will then put them in a mysql table. So far the ajax call looks like this:
function postLocation()
{
//var teamName = $('.team_name').val(); //Neither of the two work
var teamName = document.getElementById('team_name').value;
navigator.geolocation.getCurrentPosition(function(position)
{
pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
$.ajax(
{
url:'location.php',
type: 'POST',
datatype: 'json',
data: {
'posx':position.coords.latitude,
'posy': position.coords.longitude,
'team_name':$team_name
}, // post to location.php
success: function(data) {
alert(data);
},
error: function(data) {
alert("There may an error on uploading. Try again later"); //This is what displays on the screen every time
},
});
});
}
You'll notice as well that I have 'team_name' = $team_name -> this is essentially what I want to do, but I cannot find the best way to do this using my existing ajax structure.
EDIT using var teamName = document.getElementById('team_name').value; to get the value from a hidden field just causes the alert to give the error message. In the browser debug it tells me it's a 500 internal server error.
EDIT 2 Here is my html code on the index.php page:
<div class="titleText"><h1><?php
echo $stagerow['stage'];
echo $id;
$team_name = $_SESSION['team_name'];
echo $team_name;
?></h1>
You can logout here. <br></div>
<div id="map-canvas"></div>
</head>
<input type ="hidden" id="team_name" name="team_name" value="<?php echo $team_name?>" >
<!-- Script -->
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
And this is the error message I get from the browser POST http://testphp-olivlaytchev.rhcloud.com/location.php 500 (Internal Server Error)send
# jquery.js:9664m.extend.ajax
# jquery.js:9215(anonymous function)
# (index):259
line 259 is $.ajax(
if $team_name is a php variable, you can echo it out into a hidden input and grab its val via js
<input type ="hidden" class="team_name" name="team_name" value="<?php echo $team_name?>" >
You have an error at the section when you pass data in your ajax. 'team_name':$team_name should be team_name: teamName`.
The first arg is passed to HTTP_POST as key index, the second is the value and you don't need $ sign.
var teamName = $('.team_name').val();
data: {
'posx':position.coords.latitude,
'posy': position.coords.longitude,
team_name: teamName
}, /
in your php you can access it like below.
echo $_POST['data'];

Reload a div on AJAX request

I want to send an ajax request and reload the div from which it came. As of current I am getting the proper request but it isn't reloading the div - it just makes it blank (nothing there). And I have to refresh the page to see my data. How can I get it to display properly?
my add_amenity.php page works fine
*also, don't be suspicious of the var id = $('.editblock').find('#id').val(); It gets the value it needs and sends it to add_amenity.php just fine. My only problem is getting the div to reload on an add.
php and html on same page as JS below. (This is not add_amenity.php)
<div class="editunitamenities">
<?php
require_once('config/db.php');
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$query = 'SELECT id, unit, amenities FROM amenities WHERE unit = '.mysqli_real_escape_string($con, $_GET['id']).'';
$result = mysqli_query($con, $query);
while ($row= mysqli_fetch_assoc($result))
{
echo '<div class="checkbox"><input type="checkbox" id="'.$row['id'].'" checked
class="amenitiescheckbox" name="'.$row['amenities'].'" value="'.$row['amenities'].'" />
<label title="'.$row['unit'].'">'.$row['amenities'].'</label></div>';
}
mysqli_close($con);
?>
<div class="newamenitywrap">
<div class="button"><button class="smallbutton" id="addamenity">New</button></div>
<div><input type="text" name="amenity" style="width:120px;" id="amenity" placeholder="Amenity Name" /></div>
</div>
</div> <!-- end editunitamenities -->
Here is the AJAX request
<script>
$('#addamenity').click(function() {
var id = $('.editblock').find('#id').val();
var amenity = $( "#amenity" ).val();
var dataString ={id:id,amenity:amenity};
console.log(dataString);
if (amenity != '')
{
$.ajax({
type: "POST",
url: "classes/add_amenities.php",
data: dataString,
cache: false,
async:false,
success: function(html)
{
$('.editunitamenities').html(html);
}
});
}
});
</script>
I suggest the following changes:
(1) Remove the following line. I can't imagine it is doing what you expect it to because it will try to make an ajax call to the URL ".editunitamenities", and this may be what is blanking out the <div>.
$(".editunitamenities").load('.editunitamenities');
(2) Add the following property to the ajax options. This will prevent jQuery from converting the data value into an object if it thinks it looks like JSON.
dataType: 'html'
(3) Add the following line to the success handler to check what is getting returned.
console.log(data);
The following line also appears suspicious to me, but since you say the request is correct, I will assume it is working as it should.
var id = $('.editblock').find('#id').val();
I find the above line suspicious because there would have to be an element with an id value equal to "id". Also, since you are trying to find that element within another element, it makes me think you have multiple such elements, but id values should be unique throughout the entire page.
It would be useful to see the code for classes/add_amenities.php to see exactly what's going on, but you should check one or more of the following:
in the PHP you use $_GET['id'] and the ajax request is type: "POST"
also I see in your ajax request you do $('.editblock').find('#id').val(); but I see no element in your markup with class editblock or with id id - so either these nodes are not in the markup you posted or you should change you js call
the second line in the success function is redundant
I found a workaround. None of the other suggestions worked for me.
I made another page called display_amenities.php:
<?php
require_once('../config/db.php');
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$query = 'SELECT id, unit, amenities FROM amenities WHERE unit = '.mysqli_real_escape_string($con, $_GET['id']).'';
$result = mysqli_query($con, $query);
while ($row= mysqli_fetch_assoc($result))
{
echo '<div class="checkbox"><input type="checkbox" id="'.$row['id'].'" checked
class="amenitiescheckbox" name="'.$row['amenities'].'" value="'.$row['unit'].'" />
<label title="'.$row['unit'].'">'.$row['amenities'].'</label></div>';
}
mysqli_close($con);
?>
<div class="newamenitywrap">
<div class="button"><button class="smallbutton" id="addamenity">New</button></div>
<div><input type="text" name="amenity" style="width:120px;" id="amenity" placeholder="Amenity Name" /></div>
</div>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"> </script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$('#addamenity').click(function() {
var id = $('.editblock').find('#id').val();
var amenity = $( "#amenity" ).val();
var dataString ={id:id,amenity:amenity};
console.log(dataString);
if (amenity != '')
{
$.ajax({
type: "POST",
url: "classes/add_amenities.php",
data: dataString,
cache: false,
async:false,
success: function(html)
{
//$('.editunitamenities').html(html);
$('.editunitamenities').load('classes/display_amenities.php?id='+id);
}
});
}
});
</script>
And then called it from the main page:
$('#addamenity').click(function() {
var id = $('.editblock').find('#id').val();
var amenity = $( "#amenity" ).val();
var dataString ={id:id,amenity:amenity};
console.log(dataString);
if (amenity != '')
{
$.ajax({
type: "POST",
url: "classes/add_amenities.php",
data: dataString,
cache: false,
async:false,
success: function(html)
{
//$('.editunitamenities').html(html);
$('.editunitamenities').load('classes/display_amenities.php?id='+id);
}
});
//$('.editunitamenities').load('.editunitamenities');
}
});
Definitely not ideal, but it works.

Categories

Resources