I am trying to show loading image until php excutes, the query works on the second page but the results aren't showing on the first page, I know I am missing something here, can someone help me out? I am new to jquery or ajax thing.
home.php
<html>
<head>
<!--Javascript-->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
$('#loading_spinner').show();
var post_data = "items=" + items;
$.ajax({
url: 'list.php',
type: 'POST',
data: post_data,
dataType: 'html',
success: function(data) {
$('.my_update_panel').html(data);
},
error: function() {
alert("Something went wrong!");
}
});
$('#loading_spinner').hide();
</script>
<style>
#loading_spinner { display:none; }
</style>
</head>
<body>
<img id="loading_spinner" src="image/ajax-loader.gif">
<div class="my_update_panel">
<!--I am not sure what to put here, so the results can show here-->
</div>
list.php I tested the query and it prints the rows.
<?php
include_once("models/config.php");
// if this page was not called by AJAX, die
if (!$_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') die('Invalid request');
// get variable sent from client-side page
$my_variable = isset($_POST['items']) ? strip_tags($_POST['items']) :null;
//run some queries, printing some kind of result
$mydb = new mysqli("localhost", "root", "", "db");
$username = $_SESSION["userCakeUser"];
$stmt = $mydb->prepare("SELECT * FROM products where username = ?");
$stmt->bind_param('s', $username->username);
$stmt->execute();
// echo results
$max = $stmt->get_result();
while ($row = $max->fetch_assoc()) {
echo $row['title'];
echo $row['price'];
echo $row['condition'];
}
?>
The HTML. Put the img inside of the .my_update_panel div
<div class="my_update_panel">
<img id="loading_spinner" src="image/ajax-loader.gif">
</div>
The JS
var url = 'list.php';
var post_data = "items=" + items;
$('.my_update_panel').load(url, post_data, function() {
$(this +' #loading_spinner').fadeOut('slow');
});
You can find a good selection of loading images that are readily available for download here.
There is a issue with
var post_data = "items=" + items;
Make it
$(document).ready(function(){
$('#loading_spinner').show();
$.ajax({
url: 'list.php',
type: 'POST',
data: {"items":items},
dataType: 'html',
success: function(data) {
$('.my_update_panel').html(data);
$('#loading_spinner').hide();
},
error: function() {
alert("Something went wrong!");
}
});
});
let me know if works for you.
Try To add complete event in the ajax , I hope it will work. Refer
http://api.jquery.com/jQuery.ajax/
<html>
<head>
<!--Javascript-->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
$('#loading_spinner').show();
var post_data = "items=" + items;
$.ajax({
url: 'list.php',
type: 'POST',
data: post_data,
dataType: 'html',
success: function(data) {
$('.my_update_panel').html(data);
},
error: function() {
alert("Something went wrong!");
},
complete:function(){
$('#loading_spinner').fadeOut(500);
});
//$('#loading_spinner').hide();
</script>
<style>
#loading_spinner { display:none; }
</style>
</head>
<body>
<img id="loading_spinner" src="image/ajax-loader.gif">
<div class="my_update_panel">
<!--I am not sure what to put here, so the results can show here-->
</div>
It is better to chain the ajax callback functions. adding callbacks as options will be removed from jquery in the future.
http://api.jquery.com/jQuery.ajax/
Deprecation Notice: The jqXHR.success(), jqXHR.error(), and
jqXHR.complete() callbacks are deprecated as of jQuery 1.8. To prepare
your code for their eventual removal, use jqXHR.done(), jqXHR.fail(),
and jqXHR.always() instead.
var post_data = items;
$('#loading_spinner').show();
$.ajax({
url: 'list.php',
type: 'POST',
dataType: 'html',
data: {"items":post_data},
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
})
.always(function() {
$('#loading_spinner').hide();
});
I hide the loading_spinner in the always() callback, that way the spinner also disappears when the ajax call throws an error. if this is not working you have to search in your server side code to solve the problem. First of, are you sure the response is html? you might have to set the dataType to text in the ajax call.
Related
I'm trying to dynamically change a modal's content with the result of a query using PHP.
So far, I've managed to reach the ajax call, but I'm not getting a success nor error message
PHP: get_user.php
<?php
include ("session-connection.php");
session_start();
$result = $_POST['param'];
echo $result;
?>
HTML
<script type="text/javascript">
function view_progress(row){
console.log("id: " + row);
var param = row;
$.ajax({
data: param,
url: 'get_user.php',
type: 'post',
beforeSend: function(){
$("#progressModal").modal('show');
$("#alert_name").html("...");
},
error: function (){
$("#alert_name").html("Error");
},
success: function(resultado){
$("#alert_name").html(resultado);
}
});
}
</script>
If the code is successfull it should change the label alert_name with the id the javascript function recieves.
As i'm building an website that needs Ajax for sending POST methods without refreshing the entire page.
I tried using ajax to send data from an onclick event on an LINK-tag, but the ajax code does seem to send an EMPTY post.
This is the php/jquery/ajax code:
<p id="school_content">
</p>
<script src="js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".toggleThis").click(function(){
var Id = $(this).attr('id');
$.ajax({
contentType: "application/json; charset=utf-8",
url: "id_script.php",
type: "POST",
data: {
'school_name': Id,
},
success: function(data){
alert(Id);
},
});
$("#school_content").load("id_script.php");
});
});
</script>
The LINK-tag has the 'id' of the school of wich the information needs to be shown in the PARAGRAPH with 'id' "school_content" by this jquery part: $("#school_content").load("id_script.php"); .
The var Id = $(this).attr('id'); part works, because he's giving me the right school_name in an alert(); if I ask it to.
The id_script.php needs to get this POST in the usual way, but is does not..
The id_script.php code:
<?php
include('connect.php');
header('Content-Type: application/json');
if(isset($_POST['school_name'])){
$Id = $_POST['school_name'];
$extract = mysqli_query($con, "SELECT * FROM school_kaart WHERE school_name='$Id'");
$numro=mysqli_num_rows($extract);
if(mysqli_num_rows($extract) == '1'){
$row = mysqli_fetch_assoc($extract);
echo 'Yes it works!';
}
else{
echo 'Nope, didnt work!';
}
}
else{
echo 'Not posted!';
}
?>
I'm still getting "Not posted!" in the PARAGRAPH I mentioned earlier. What seems to be the problem?
.load is shorthand for an ajax request so you are actually doing 2 request.
The latter isn't sending any data and so it returns 'Not Posted!';
http://api.jquery.com/load/
try
<script src="js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".toggleThis").click(function(){
var Id = $(this).attr('id');
$.ajax({
url: "id_script.php",
type: "POST",
data: {
'school_name': Id,
},
success: function(data){
alert(Id);
$("#school_content").html(data);
},
});
//remove this
//$("#school_content").load("id_script.php");
});
});
</script>
I'm trying to create a simple AJAX call for testing, but have encountered a problem. I have nested in my AJAX call a success function which should pop an alert message but it doesn't. Checking firebug, the POST is successful and responds with "A20" (without quotations). Is there something wrong in my code?
index.php (view)
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="init.js"></script>
<script src="jquery-1.10.2.min.js"></script>
</head>
<body>
<button id="your_button">Push me</button>
</body>
</html>
init.js
$(function() {
$('#your_button').bind("click", function() {
var json_data = {"category": "A", "size": "20"};
$.ajax({
url: "posted.php",
dataType: "json",
type: "POST",
cache: false,
data: {"data": json_data},
success: function (data) {
if (!data.error) {
alert('k');
} else {
alert('error!');
}
}
});
});
});
posted.php
$category = $_POST['data']['category'];
$tsize = $_POST['data']['size'];
echo ($category);
echo ($size);
Try this -
$(function() {
$('#your_button').bind("click", function() {
var json_data = {"category": "A", "size": "20"};
$.ajax({
url: "posted.php",
dataType: "json",
type: "POST",
cache: false,
data: json_data,
success: function (data) {
if (!data.error) {
alert('k');
} else {
alert('error!');
}
}
});
});
});
Posted.php
$category = $_POST['category'];
$tsize = $_POST['size'];
//echo ($category);
//echo ($tsize);
echo json_encode($_POST);
Your want json data but you were not echoing json data
this is not right:
data: {"data": json_data}
do like this:
data: {data: json_data}
You need to set proper headers in your PHP and send a valid json response from PHP file. Add these lines to your PHP
header('Access-Control-Allow-Origin: *');
header('Content-type: application/json');
and echo back some valid json from it like echo '{"auth":"true","error":"false"}';
First you are using two jquery libraries, remove any one of them.
Second replace data: {"data": json_data}, with data: json_data,.
Third on posted.php use $category = $_POST['category'] and $tsize = $_POST['size'];.
Hope it will help you.
I have a button which calls a modal box to fade into the screen saying a value posted from the button then fade off, this works fine using jquery, but I also want on the same click for value sent from the button to be posted to a php function, that to run and the modal box to still fade in and out.
I only have this to let my site know what js to use:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" ></script>
I'm still new so sorry for a rookie question, but will that allow ajax to run, or is it only for jquery?
The current script I'm trying is: (Edited to be correctly formed, based on replies, but now nothing happens at all)
<script>
$('button').click(function()
{
var book_id = $(this).parent().data('id'),
result = "Book #" + book_id + " has been reserved.";
$.ajax
({
url: 'reservebook.php',
data: "book_id="+book_id,
type: 'post',
success: function()
{
$('.modal-box').text(result).fadeIn(700, function()
{
setTimeout(function()
{
$('.modal-box').fadeOut();
}, 2000);
});
}
});
});
</script>
Though with this the modal box doesn't even happen.
The php is, resersebook.php:
<?php
session_start();
$conn = mysql_connect('localhost', 'root', '');
mysql_select_db('library', $conn);
if(isset($_POST['jqbookID']))
{
$bookID = $_POST['jqbookID'];
mysql_query("INSERT INTO borrowing (UserID, BookID, Returned) VALUES ('".$_SESSION['userID']."', '".$bookID."', '3')", $conn);
}
?>
and to be thorough, the button is:
<div class= "obutton feature2" data-id="<?php echo $bookID;?>"><button>Reserve Book</button></div>
I'm new to this and I've looked at dozens of other similar questions on here, which is how I got my current script, but it just doesn't work.
Not sure if it matters, but the script with just the modal box that works has to be at the bottom of the html body to work, not sure if for some reason ajax needs to be at the top, but then the modal box wouldn't work, just a thought.
Try this. Edited to the final answer.
button:
<div class= "obutton feature2" data-id="<?php echo $bookID;?>">
<button class="reserve-button">Reserve Book</button>
</div>
script:
<script>
$('.reserve-button').click(function(){
var book_id = $(this).parent().data('id');
$.ajax
({
url: 'reservebook.php',
data: {"bookID": book_id},
type: 'post',
success: function(result)
{
$('.modal-box').text(result).fadeIn(700, function()
{
setTimeout(function()
{
$('.modal-box').fadeOut();
}, 2000);
});
}
});
});
</script>
reservebook.php:
<?php
session_start();
$conn = mysql_connect('localhost', 'root', '');
mysql_select_db('library', $conn);
if(isset($_POST['bookID']))
{
$bookID = $_POST['bookID'];
$result = mysql_query("INSERT INTO borrowing (UserID, BookID, Returned) VALUES ('".$_SESSION['userID']."', '".$bookID."', '3')", $conn);
if ($result)
echo "Book #" + $bookId + " has been reserved.";
else
echo "An error message!";
}
?>
PS#1: The change to mysqli is minimal to your code, but strongly recommended.
PS#2: The success on Ajax call doesn't mean the query was successful. Only means that the Ajax transaction went correctly and got a satisfatory response. That means, it sent to the url the correct data, but not always the url did the correct thing.
You have an error in your ajax definitions. It should be:
$.ajax
({
url: 'reserbook.php',
data: "book_id="+book_id,
type: 'post',
success: function()
{
$('.modal-box').text(result).fadeIn(700, function()
{
setTimeout(function()
{
$('.modal-box').fadeOut();
}, 2000);
});
}
});
You Ajax is bad formed, you need the sucsses event. With that when you invoke the ajax and it's success it will show the response.
$.ajax
({
url: 'reserbook.php',
data: {"book_id":book_id},
type: 'post',
success: function(data) {
$('.modal-box').text(result).fadeIn(700, function()
{
setTimeout(function()
{
$('.modal-box').fadeOut();
}, 2000);
});
}
}
Edit:
Another important point is data: "book_id="+book_id, that should be data: {"book_id":book_id},
$.ajax
({
url: 'reservebook.php',
data: {
jqbookID : book_id,
},
type: 'post',
success: function()
{
$('.modal-box').text(result).fadeIn(700, function()
{
setTimeout(function()
{
$('.modal-box').fadeOut();
}, 2000);
});
}
});
});
Try this
I am using Twitter Bootstrap Typeahead for an autocomplete field.
End state goal: The user first enters details into field 1. When they enter details in field 2, ajax passes the query as it is written to a PHP file which queries a database based on what was also entered into field 1.
How do I pass both the query from field 2 and the contents of field 1 to the PHP file and access them.
Here is what I have so far:
HTML FILE:
<div class="field1">
<input type="text" id="field1" data-provide="typeahead" name="field1">
</div>
<div class="field2">
<input type="text" id="field2" data-provide="typeahead">
</div>
<script src="js/jquery-1.9.1.min.js"></script>
<script src="js/bootstrap.js"></script>
<script>
$(function() {
$("#field2").typeahead({
source: function(query, process) {
var textVal=$("#field1").val();
$.ajax({
url: 'field2.php',
type: 'POST',
data: 'query=' + query,
dataType: 'JSON',
async: true,
success: function(data) {
process(data);
console.log(textVal);
}
});
}
});
});
</script>
PHP FILE:
if (isset($_POST['query'])) {
$db_server = mysql_connect("localhost", "root", "root");
mysql_select_db("db_test");
$query = $_POST['query'];
$other = '**This needs to be field 1**';
$sql = mysql_query("SELECT * FROM table WHERE row1 LIKE '%{$query}%' AND row2 = '$other'");
$array = array();
while ($row = mysql_fetch_assoc($sql)) {
$array[] = $row['row1'];
}
echo json_encode($array);}
At the moment, the query part works perfectly and the results are returned (the console also displays the value from 'Field1'. Just need to get that value into the php file at the same time!
Any help would be great
If I understood this correctly, you want to parse both the values of field 1 and 2 to the same AJAX call. This is how you do it.
<script>
$(function() {
$("#field2").typeahead({
source: function(query, process) {
var textVal=$("#field1").val();
$.ajax({
url: 'field2.php',
type: 'POST',
data: 'query=' + query + '&field1=' + textVal,
dataType: 'JSON',
async: true,
success: function(data) {
process(data);
console.log(textVal);
}
});
}
});
});
</script>
Now you just make another $_POST['field1'] in your PHP file.
var userQuery = $('#ID of query input element').val();
var field1 = $('#ID of input 1 element').val();
$.ajax({
type: "POST",
url: '',
data: {query: QueryVariable, input1: input1variable},
success: function(data) {
// code within this block
},
error: function() {
alert('System Error! Please try again.');
},
complete: function() {
console.log('completed')
}
}); // ***END $.ajax call