want to get to another page while i m under an ajax call - javascript

helllo i m making a quiz. i m fetching questions from database . while im using ajax to display the questions by refreshing a div tag. here is the code of ajax used.
$(document).ready(function(){
$("#button").click(function(){
var q_id=$("#h_val").val();
$("#rv").val(q_id);
$.ajax({ url: 'data.php',
type: "POST",
data: {"q_id":q_id} ,
success: function(result) {
$('#que').html(result);
var newValue = parseInt(q_id) + 1
$('#h_val').val(newValue);
}
});
});
});
now this is the data.php page code.
<?php
$qid=$_POST['q_id'];
$con = mysql_connect('localhost', 'root', '') or die(mysql_error());
$db = mysql_select_db('quiz', $con) or die(mysql_error());
$q="select * from question where qno=$qid";
$rq=mysql_query($q,$con);
if(!$rq)
{
echo " the sql query faiiled to work ";
}
else
{
if (mysql_num_rows($rq) == 0)
{
echo "database is empty.";
}
else
{
while ($sub_row=mysql_fetch_array($rq))
{
$id=$sub_row["qno"];
$question=$sub_row["question"];
$option1=$sub_row["option1"];
$option2=$sub_row["option2"];
$option3=$sub_row["option3"];
$option4=$sub_row["option4"];
echo "<h5>Q".$id." : ".$question."</br></h5>";
echo"</br><br>
<h4><input type= radio id='1' name=\"{$id}\" value=\"{$option1}\">$option1</h4>
</br>
<h4><input type= radio id='2' name=\"{$id}\" value=\"{$option2}\">$option2</h4>
</br>
<h4><input type= radio id='3' name=\"{$id}\" value=\"{$option3}\">$option3</h4>
</br>
<h4><input type= radio id='4' name=\"{$id}\" value=\"{$option4}\">$option4</h4>
</br></br>";
}
}
}
?>
i just want to go to a page when the question get over. while using header loaction whole page is coming in div . i just want a code to replace the line "databse is empty" which will redirect me to anther page .

Should be done in js. As per your current code, try this
success: function(result) {
if(result=="database is empty.") {
window.location="newurl.php";
}
$('#que').html(result);
var newValue = parseInt(q_id) + 1
$('#h_val').val(newValue);
}

Related

ajax / jquery not passing 2nd click values [duplicate]

This question already has an answer here:
Function doesn't work after appending new element
(1 answer)
Closed 5 years ago.
Extremely new to JavaScript, jquery and ajax and am having difficulties with a very basic set of scripts to load more data from a database on button clicks.
The first time I click load more, it works. But the 2nd clicks do not pass the values and does nothing.
Here is the main script that loads data once and includes the jquery, ajax stuff.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#btn1, #btn2").click(function() {
pagenum = $(this).val();
val = "Loading page " + pagenum + "...";
$(this).text(val);
$.ajax({
type: "POST",
url: "loadmore.php",
data: {page: pagenum},
success: function(response){
if(response){
$("#btn1").hide();
$("#div1").append(response);
}
}
});
});
});
</script>
</head>
<?php
// main.php contains db connection
include('main.php');
$rowsperpage = 2;
$q = "SELECT col1, col2 from mytableORDER BY col1 LIMIT $rowsperpage OFFSET 0";
$r = pg_exec($dbconnect, $q);
echo "<div id='div1' style='margin:10px;'>";
while ($row = pg_fetch_row($r) ) {
echo "<div>$row[1]</div>";
}
echo "<button id='btn1' value=2>Load More</button>";
echo "</div>";
?>
And here is the script fetched more data to display.
<?php
include('../config.php');
include('functions.php');
$rowsperpage = 2;
if(isset($_POST['page'])) {
$paged=$_POST['page'];
} else {
$paged = 1;
}
if($paged > 1) {
$rowoffset = $rowsperpage * ($paged -1);
$limit = " LIMIT $rowsperpage OFFSET $rowoffset";
} else {
$limit = " LIMIT $rowsperpage OFFSET 0 ";
}
$q = "select subindustryid, subindustry from sub_industries ORDER BY subindustry $limit";
$r = pg_exec($dbconnect, $q);
while ($row = pg_fetch_row($r) ) {
echo "<div>$row[1]</div>";
}
$nextpage = $paged + 1;
echo "<button id='btn1' value=$nextpage>Load even more </button>";
?>
The problem is the the 2nd button is displayed and nothing happens when it gets clicked.
Thank for your time!
The problem is the event binding. Change this line-
$("#btn1, #btn2").click(function() {
to this line
$("#div1").on("click","#btn1, #btn2",function(){
Also your php returns a button with id btn1 and not btn2
Read about jQuery Event bindings here: https://learn.jquery.com/events/handling-events/ and http://learn.jquery.com/events/event-delegation/
Actually id identifiers should be unique- this is general convention. You have load more button with id="#btn1" and hiding old button appearing new button from the response text form ajax by hiding and appending- but you can manage such with out sending button in response text-
Have following changes on your html page
value should be quoted <button id="btn1" value="2">Load More ... </button>
Make use of dedicated function calling in jQuery like- $(document).on('event','dom_identifiers',callbackfunction(){})
In ajax don't need to hide current button which is clicked, instead of hiding the button just add new records fetched before the load more button by using before() function of jQuery
For next page you can increase the value of current button
$(document).ready(function(){
// dedicated function calling
$(document).on('click','#btn1',function() {
pagenum = $(this).val();
val = "Loading page " + pagenum + "...";
$(this).text(val);
$.ajax({
type: "POST",
url: "loadmore.php",
data: {page: pagenum},
success: function(response){
if(response){
// increase the value load more
$("#btn1").val(parseInt($("#btn1").val())+1);
// add response data just before the loadmore button
$("#btn1").before(response);
}
}
});
});
});
button should be like
echo "<button id='btn1' value="2">Load More</button>";
Now in fetching php page please remove these two lines-
$nextpage = $paged + 1;
echo "<button id='btn1' value=$nextpage>Load even more </button>";

give a value to input when move then save it by ajax - php / jquery -php

I want to create a shopping cart and i'm almost finish. I use ajax for dynamic search and ajax for add to cart and use jquery for refresh a specific div when click but i face a problem.My problem is Quantity problem. I use session for store value
//this is my session update code
$con = mysqli_connect("localhost", "root" , "","atest");
session_start();
require("functions.php");
cart_session();
$id=$_POST['id'];
//echo $arr['cart'];
if(isset($_SESSION[$arr["cart"]][$id])){
$_SESSION[$arr["cart"]][$id][$arr["quantity"]]++;
//redirect("http://localhost/my/work/sellingcart/index.php",true);
}else{
$sql_s="SELECT * FROM product_1
WHERE p_id={$id}";
//echo $sql_s;
$query_s=mysqli_query($con,$sql_s);
if(mysqli_num_rows($query_s)!=0){
$row_s=mysqli_fetch_array($query_s);
$_SESSION[$arr['cart']][$row_s["p_id"]]=array(
"{$arr["quantity"]}" => 1
);
//redirect("http://localhost/my/work/sellingcart/index.php",true);
}else{
$message="This product id it's invalid!";
}
}
//use ajax for update cart
<script>
$("#link").click(function(e) {
e.preventDefault();
var id = $("#id").val();
var dataString = 'id='+id;
$('#loading-image').show();
$(".form :input").attr("disabled", true);
$('#remove_cart').hide();
$('#link').hide();
$(".container").css({"opacity":".3"});
$(".form :input").attr("disabled", true);
$('#remove_cart').hide();
$('#link').hide();
$.ajax({
type:'POST',
data:dataString,
url:'add_cart.php',
success:function(data) {
$('#availability').html(data);
},
complete: function(){
$('#loading-image').hide();
$(".form :input").attr("disabled", false);
$('#remove_cart').show();
$('#link').show();
$(".container").css({"opacity":"1"});
}
});
//$("#chat").load(location.href + " #chat");
//$("#chat").load(location.href+" #chat>*","");
});
</script>
Here is image and Red mark is my problem.
i want to update my cart when i give value and move it then it update my session by ajax and php.
Is there any help? I don't want to user can update there quantity every cart item singly. i want it dynamic just give quantity number and move then it save by ajax.
Assign an onchange event to your quantity input boxes:
$('input[name=quantityBox]').change(function() { ... });
In your function() above, add an AJAX POST request containing something like
var quantity = $('input[name=quantityBox]').val();
// var id = something;
$.ajax({
type:'POST',
data:"productId=" + id + "&updateQuantity=" + quantity,
url:'add_cart.php',
success:function(data) {
$('#availability').html(data);
},
complete: function(){
// anything you want to do on successful update of request
}
});
In your PHP function above, you check whether the product already exists in user's cart. At that point, change the quantity.
if(isset($_SESSION[$arr["cart"]][$id])){
$quantity = $_POST['updateQuantity'];
$id = $_POST['productId'];
$_SESSION[$arr["cart"]][$id][$arr["quantity"]] = $quantity;
}
Special Thanks To Nvj
Assign an onchange event to your quantity input boxes:
<input id="qty<?php echo $row['p_id'] ?>" value="" onchange="save_quantity(<?php echo $row['p_id'] ?>)">
function with ajax :
function save_quantity(x){
var quantity=$("#qty"+x).val();
$.ajax({
type:'POST',
data:"updateQuantity=" + quantity+ "&id="+x,
url:'update_qty.php',
success:function(data) {
$('#availability').html(data);
},
complete: function(){
// anything you want to do on successful update of request
}
});
}
php file update_qty.php
session_start();
$qty = $_POST["updateQuantity"];
$p_id = $_POST["id"];
foreach($_SESSION['cart'] as $id => $value) {
if($id==$p_id)
echo $id;
$_SESSION['cart'][$id]['quantity']=$qty;
}

Accessing JSON returned by php script using jquery ajax

Basically my program is a web page with 5 radio buttons to select from. I want my web app to be able to change the picture below the buttons every time a different button is selected.
My problem is coming in the JSON decoding stage after receiving the JSON back from my php scrip that accesses the data in mysql.
Here is my code for my ajax.js file:
$('#selection').change(function() {
var selected_value = $("input[name='kobegreat']:checked").val();
$.ajax( {
url: "kobegreat.php",
data: {"name": selected_value},
type: "GET",
dataType: "json",
success: function(json) {
var $imgEl = $("img");
if( $imgEl.length === 0) {
$imgEl = $(document.createElement("img"));
$imgEl.insertAfter('h3');
$imgEl.attr("width", "300px");
$imgEl.attr("alt", "kobepic");
}
var link = json.link + ".jpg";
$imgEl.attr('src', link);
alert("AJAX was a success");
},
cache: false
});
});
And my php file:
<?php
$db_user = 'test';
$db_pass = 'test1';
if($_SERVER['REQUEST_METHOD'] == "GET") {
$value = filter_input(INPUT_GET, "name");
}
try {
$conn = new PDO('mysql: host=localhost; dbname=kobe', $db_user, $db_pass);
$conn->setAttribute(PDO:: ATTR_ERRMODE, PDO:: ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT * FROM greatshots WHERE name = :name');
do_search($stmt, $value);
} catch (PDOException $e) {
echo 'ERROR', $e->getMessage();
}
function do_search ($stmt, $name) {
$stmt->execute(['name'=>$name]);
if($row = $stmt->fetch()) {
$return = $row;
echo json_encode($return);
} else {
echo '<p>No match found</p>;
}
}
?>
Here's my HTML code where I am trying to post the image to.
<h2>Select a Great Kobe Moment.</h2>
<form id="selection" method="get">
<input type="radio" name="kobegreat" value="kobe1" checked/>Kobe1
<input type="radio" name="kobegreat" value="kobe2"/>Kobe2
<input type="radio" name="kobegreat" value="kobe3"/>Kobe3
</form>
<div id="target">
<h3>Great Kobe Moment!</h3>
</div>
And here's is what my database looks like:
greatshots(name, link)
name link
------ --------
kobe1 images/kobe1
kobe2 images/kobe2
kobe3 images/kobe3
Whenever I run the web app right now, the rest of the images on the page disappear and the image I am trying to display won't show up. I get the alert that "AJAX was a success" though, but nothing comes of it other than the alert. Not sure where I am going wrong with this and any help would be awesome.
As mentioned you should parse the JSON response using JSON.parse(json);.
Also, you should specifically target the div element with a simpler setup:
$("#target").append('<img width="300px" src="' + link + '.png"/>');

How to define an element with a a sql row id usng JSON encoded data

I'm using jQuery AJAX to process form data, the PHP side of it should delete two files on the server and then the SQL row in the database (for the id that was sent to it). The element containing the SQL row should then change color, move up, delete and the next SQL rows move into its place. The animation stuff occurs in the beforeSend and success functions of the ajax callback.
This script is not working, when user clicks button, the page url changes to that of the php script but the item and files do not get deleted either on the server or in the database. Nor does any of the animation occur.
This is my first time using jQuery ajax, I think there is a problem with how I define the element during the call back. Any help would be great:
js
$("document").ready(function(){
$(".delform").submit(function(){
data = $(this).serialize() + "&" + $.param(data);
if (confirm("Are you sure you want to delete this listing?")) {
$.ajax({
type: "POST",
dataType: "json",
url: "delete_list.php",
data: data,
beforeSend: function() {
$( "#" + data["idc"] ).animate({'backgroundColor':'#fb6c6c'},600);
},
success: function() {
$( "#" + data["idc"] ).slideUp(600,function() {
$( "#" + data["idc"] ).remove();
});
}
});
return false;
}
});
});
php
if (isset($_POST["id"]))
{
$idc = $_POST["id"];
if (isset($_POST["ad_link"]) && !empty($_POST["ad_link"]))
{
$ad_linkd=$_POST["ad_link"];
unlink($ad_linkd);
}
if (isset($_POST["listing_img"]) && !empty($_POST["listing_img"]))
{
$listing_imgd=$_POST["listing_img"];
unlink($listing_imgd);
}
try {
require('../dbcon2.php');
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "DELETE FROM listings WHERE id = $idc";
$conn->exec($sql);
}
catch (PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
echo json_encode($idc);
}
html
<div id="record-<?php echo $id; ?>">
*bunch of stuff*
<form method="post" class="delform">
<input name="id" type="hidden" id="id" value="<?php echo $id; ?>" />
<input name="ad_link" type="hidden" id="ad_link" value="<?php echo $ad_link; ?>" />
<input name="listing_img" type="hidden" id="listing_img" value="<?php echo $listing_img; ?>" />
<button type="submit">Delete</button>
</form>
</div>
You should fix your php code like this
try {
require('../dbcon2.php');
// It's better, if you will going to use MySQL DB, use the class designed to connect with it.
$conn = mysqli_connect("Servername", "usernameDB", "PasswordDB", "NameDB");
$sql = "DELETE FROM listings WHERE id = $idc";
mysqli_query($conn, $sql);
// you have to create a asociative array for a better control
$data = array("success" => true, "idc" => $idc);
// and you have to encode the data and also exit the code.
exit(json_encode($data));
} catch (Exception $e) {
// you have to create a asociative array for a better control
$data = array("success" => false, "sentence" => $sql, "error" => $e.getMessage());
// and you have to encode the data and also exit the code.
exit(json_encode($data));
}
Now in you JS code Ajax change to this.
$.ajax({
type: "POST",
dataType: "json",
url: "delete_list.php",
data: data,
beforeSend: function() {
$( "#" + data["idc"] ).animate({'backgroundColor':'#fb6c6c'},600);
},
success: function(response) {
// the variable response is the data returned from 'delete_list.php' the JSON
// now validate if the data returned run well
if (response.success) {
$( "#" + response.idc ).slideUp(600,function() {
$( "#" + response.idc ).remove();
});
} else {
console.log("An error has ocurred: sentence: " + response.sentence + "error: " + response.error);
}
},
// add a handler to error cases.
error: function() {
alert("An Error has ocurred contacting with the server. Sorry");
}
});

AJAX form submission with php and jquery

I have looked at everything on here that I can find and I just can't figure out why I cannot perfect this code. What I am trying to do is allow users to delete something that they posted on my site without doing a page refresh. The form is going to be passed to a php file that will modify my MySQL DB. I am new to ajax and have only messed around with PHP for a short time as well.
form:
<form class='status_feedback' id='delete_status' onsubmit='delete_status()' action=''>
<input type='hidden' name='status_id' id='status_id' value='$status_id'/>
<input type='submit' value='X'/>
</form>
delete_status()
function delete_status(){
$.ajax({
type: "POST",
url: "/scripts/home/php/delete_status.php/",
data: status_id,
success: function() {
//display message back to user here
}
});
return false;
}
delete_status.php
<?php
$con=mysqli_connect("localhost","USER","PASSWORD","DB");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$status_id = $_POST['status_id'];
mysqli_query($con,"UPDATE status SET visibility = 'hidden' WHERE id = $status_id");
?>
at this point, all that happens when I strike the delete_status() function is my page refreshes and adds ?status_id=194 (when I click on status #194) to the end or my url.
Any help would be awesome. I have been researching for several days.
Change your HTML, Ajax and php a little.
HTML
Add this code:
<body>
<form class='status_feedback' id='delete_status' >
<input type='hidden' name='status_id' id='status_id' value='$status_id'/>
<input type='button' id='x_submit' value='X' />
</form>
<script>
$('#x_submit').on("click",function(){
var status_id= $('#status_id').val();
//Delete the alert message if you want.
alert("Check your status id :"+status_id);
$.ajax({
type: "GET",
url: "/scripts/home/php/delete_status.php?",
data: {status_id:status_id},
dataType:'JSON',
success: function(json) {
//display message back to user here
alert(json[0].response);
}
});
});
</script>
PHP:
<?php
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Methods: GET, POST');
header('Content-type: application/json');
$con=mysql_connect("localhost","USER","PASSWORD","DB");
// Check connection
if (mysql_connect_errno())
{
echo "Failed to connect to MySQL: " . mysql_connect_error();
}
$status_id = $_GET['status_id'];
$result = mysql_query("UPDATE status SET visibility = 'hidden'
WHERE id = '$status_id'");
if(! $result )
{
$data[]=array('response'=>"Unable to insert!");
}
else
{
$data[]=array('response'=>"Data successfully inserted into the database!");
}
$json_encode = json_encode($data);
print("$json_encode");
?>
Hope it will work.
You are not cancelling the form submission
onsubmit='delete_status()'
needs to be
onsubmit='return delete_status()'
and data: status_id, looks wrong unless you have a variable defined somewhere else

Categories

Resources