Below filmdetails.php file i want to call on href click, how i can incorporate the same using ajax for mobile app. i mean when i click on link filmdetails.php?id=12 then below code will fetch the 12 id having data associated with it such as name and year of the film
I want to process this using ajax. please guide
<?php
include('connection.php');
$filmId = $_GET['filmId'];
$sql ="SELECT * FROM films where filmId ='$filmId'";
mysqli_query("SET NAMES utf8");
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_array($result))
{
$id = $row['filmId'];
$name = $row['filmName'];
$year = $row['filmYear'];
echo "$name, $year";
}
mysql_free_result($result);
mysqli_close($conn);
?>
suppose your a tag has id named getcountry, than use
$(document).ready(function() {
$('#getcountry').click(function() {
$.ajax({
method: "POST",
url: "filmdetails.php",
data: { filmId: <?php echo $_GET['filmId']; ?> }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
});
I think This trick will be work.
<a href="filmdetails.php?foo_id=' . $film_id . '" class="clickMe">
<span id="results"></span>
<script type="text/javascript">
$('a.clickMe').click(function(e){
// Stop default click action in browser
e.preventDefault();
// Make ajax call
$.ajax($(e.target).attr("href"), {
cache:false,
success:function(data){
$("#results").html(data);
}
});
})
</script>
Send the filmId via your AJAX request.
$.ajax({
method: "POST",
url: "filmdetails.php",
data: { filmId: <?php echo $_GET['filmId']; ?> }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
You will see your data in an alert. You can put this data in document using jQuery's .html() method.
Related
I have written code for button to send a value to php file using ajax as show below :
<script>
$(document).ready(function(){
$(".open-AddBookDialog").click(function(){
var packageid = $(this).attr("data-id");
var dataString = 'packageid='+ packageid;
$.ajax({
type: "POST",
url: "data1.php",
data: dataString,
cache: false,
success: function(result1){
var packagetype = package_type;
alert(packagetype);
}
});
});
});
</script>
This is the ajax code for the button which i have written. My button code is :
<a data-toggle="modal" id="custId" data-name="<?php echo $arr["package_name"]; ?>" data-id="<?php echo $arr["id"]; ?>" href="#myModal" class="open-AddBookDialog btn btn-submit" OnClick='change(this);'>Book / Enquiry / Pay</a>
When clicking this button in href, I want to send a id value to a php file using ajax.
data1.php
<?php
include('database.php');
$id=$_POST['packageid'];
$query1 = mysqli_query($con,"select * from ayurveda_packagetypes where package_id = '$id'");
$arr = mysqli_fetch_array($query1);
echo $arr['package_type'];
echo $arr['package_price'];
mysqli_close($con);
?>
using the id value, I want to pick multiple rows of package type and package price from the database having the same id value.After picking the multiple rows of these values i want to send it to the main php file and display all the values of all the rows picked from the database.
Can anyone suggest how to do this ?
<script>
$(document).ready(function()
{
$(".open-AddBookDialog").click(function()
{
var packageid = $(this).attr("data-id");
var dataString = 'packageid='+ packageid;
$.ajax(
{
type: "POST",
url: "data1.php",
data: dataString,
cache: false,
success: function(result)
{
resultJson=jQuery.parseJSON(result);
$.each(resultJson.packageDetails, function(i, item) {
var packagetype = item.package_type;
var package_price = item.package_price;
alert("packagetype :- "+packagetype+" ----- package_price :-"+package_price);
});
}
});
});
});
</script>
<?php
include('database.php');
$id=$_POST['packageid'];
$query1 = mysqli_query($con,"select * from ayurveda_packagetypes where package_id = '$id'");
//$arr = mysqli_fetch_array($query1);
while( $strPackageResult=mysqli_fetch_array($query1,MYSQLI_ASSOC) )
{ $ArrPackage[]=$strPackageResult; }
if( isset($strPackageResult) ){ unset($strPackageResult); }
mysqli_free_result($query1);
if( isset($query1) ){ unset($query1); }
$myResultPackageArray=array();
if( isset($ArrPackage) && is_array($ArrPackage) && count($ArrPackage)>0 ) {
$tempArray=array();
foreach( $ArrPackage as $tempPackage )
{
$tempArray['package_type']=$tempPackage['$tempPackage'];
$tempArray['package_price']=$tempPackage['package_price'];
$myResultPackageArray['packageDetails'][] =$tempArray;
}
}
mysqli_close($con);
echo json_encode($myResultPackageArray);
?>
There are some basic things you should know first then you can easily rectify your errors.
Debuging javascript
Prepared Statements
PHP Error Handling
This is not you have asked but as a programmer i will suggest you to go through it.
As going through your code
var packagetype = package_type;
package_type is undefined. If you are using chrome inspect element and check the console you will see the error.
Hope this will work.
i want to delete a row of data in my sql when delete button is pressed in xdk. i searched for some codes but still doesnt delete the data.
this is the php file (delete.php)
<?php
include('dbcon.php');
$foodid = $_POST['foodid'];
$query = "DELETE FROM menu WHERE id ='$foodid'";
$result=mysql_query($query);
if(isset($result)) {
echo "YES";
} else {
echo "NO";
}
?>
and now here is my ajax code.
$("#btn_delete").click( function(){
alert("1");
var del_id = $(this).attr('foodid');
var $ele = $(this).parent().parent();
alert("2");
$.ajax({
type: 'POST',
url: 'http://localhost/PHP/delete.php',
data: { 'del_id':del_id },
dataType: 'json',
succes: function(data){
alert("3");
if(data=="YES"){
$ele.fadeOut().remove();
} else {
alert("Cant delete row");
}
}
});
});
as you can see, i placed alerts to know if my code is processing, when i run the program in xdk. it only alerts up to alert("2"); . and not continuing to 3. so i assume that my ajax is the wrong part here. Im kind of new with ajax.
<?php
$sqli= "*select * from temp_salesorder *";
$executequery= mysqli_query($db,$sqli);
while($row = mysqli_fetch_array($executequery,MYSQLI_ASSOC))
{
?>
//"class= delbutton" is use to delete data through ajax
<button> Cancel</button>
<!-- language: lang-js -->
//Ajax Code
<script type="text/javascript">
$(function() {
$(".delbutton").click(function(){
//Save the link in a variable called element
var element = $(this);
//Find the id of the link that was clicked
var del_id = element.attr("id");
//Built a url to send
var info = 'id=' + del_id;
$.ajax({
type: "GET",
url: "deletesales.php",
data: info,
success: function(){
}
});
$(this).parents(".record").animate({ backgroundColor: "#fbc7c7" }, "fast")
.animate({ opacity: "hide" }, "slow");
return false;
});
});
</script>
//deletesales.php
<?php
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_database = 'pos';
$db = mysqli_connect($db_host,$db_user,$db_pass,$db_database);
$id=$_GET['id']; <!-- This id is get from delete button -->
$result = "DELETE FROM temp_salesorder WHERE transaction_id= '$id'";
mysqli_query($db,$result);
?>
<!-- end snippet -->
A couple of things:
You should be testing using console.log() instead of alert() (imo)
If you open up your console (F12 in Google Chrome) do you seen any console errors when your code runs?
Your code is susceptible to SQL Injection, you will likely want to look into PHP's PDO to interact with your database.
Does your PHP file execute correctly if you change:
$foodid = $_POST['foodid'];
To
$foodid = 1
If number 4 works, the problem is with your javascript. Use recommendations in numbers 1 and 2 to diagnose the problem further.
Update:
To expand. There are a few reasons your third alert() would not fire. The most likely is that the AJAX call is not successful (the success handler is only called if the AJAX call is successful). To see a response in the event of an error or failure, you can do the following:
$.ajax({
url: "http://localhost/PHP/delete.php",
method: "POST",
data: { del_id : del_id },
dataType: "json"
})
.done(function( msg ) {
console.log(msg);
})
.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
More information on AJAX and jQuery's $.ajax can be found here
My "best guess" is a badly formatted AJAX request, your request is never reaching the server, or the server responds with an error.
Ok , I am trying to get different id values through Jquery , and pass them to Jquery AJAX that will hit a PHP file so I can get some data back .... I'm not sure how to get all the multiple different ids because Jquery is only getting the first id of many of the unique id values generated by the while loop .. and I would like each unique ID to also be passed to the AJAX function in Jquery .. Your help would be so much appreciated . I'm still new to the Jquery world
<?php
require('../database/connection.php');
?>
<script type="text/javascript">
jQuery(document).ready(function() {
var ID = $('div#opposition img').attr("id"); alert(ID);
$.ajax({
type:'GET',
url :'get_users_images.php',
data:'screen_name='+ ID,
success: function(result){
$('div#opposition img').attr('src', result);
}
});
});
</script>
<?php
$select2 = "SELECT * FROM AUTHORS WHERE ID <> $id";
$result2 = mysql_query($select2);
$result_count = mysql_num_rows($result2);
echo '<div id ="opposition">';
while ($row2 = mysql_fetch_array($result2, MYSQL_ASSOC)) {
echo "<img id ='".$row2['Twitter']."' src='images/ajax-loader.gif' class ='image".$row2['Twitter']."'/>"; // echos different ids,
}
?>
</div>
You can send an stringified array of id's like this -
jQuery(document).ready(function () {
var ID = $('div#opposition img').map(function(){
return this.id;
}).get();
$.ajax({
type: 'GET',
url: 'get_users_images.php',
data: { screen_name : JSON.stringify(ID)},
success: function (result) {
$('div#opposition img').attr('src', result);
}
});
});
If I am correct, Actually , why you are placing the set of images returned by php in one
img tag, $('div#opposition img').attr('src', result); . Rather I think you must do something like $('div#opposition').innerHTML(result) .
I am trying to pass a variable from my ajax to my php script. I can't see to get it to work. It keeps on giving me NULL when I do a var_dump on the variable.
JQUERY:
$(document).ready(function() {
$('.trigger').click(function() {
var id = $(this).prev('.set-id').val();
$.ajax({
type: "POST",
url: "../modules/Slide_Show/slide_show.php",
data: id
});
LinkUpload(id);
function LinkUpload(id){
$("#link-upload").dialog();
}
});
});
</script>
PHP:
$id = $_POST['id'];
$query = mysql_query("SELECT * FROM xcart_slideshow_slides where slideid='$id'")or die(mysql_error());
$sli = mysql_fetch_array($query);
$slide_id = $sli['slideid'];
$link = $sli['link'];
var_dump($id);
I need the $id variable to post so I can dynamically change the dialog box when the click function is activated.
EDIT:
So I have changed some of my coding:
Jquery:
$(document).ready(function() {
$('.trigger').click(function() {
var id = $(this).prev('.set-id').val();
$.post(
"slide-show-link.php",
{ id: id },
function(data,status){alert("Data: " + data + "\nStatus: " + status); }
);
// alert(id);
LinkUpload(id);
});
function LinkUpload(id){
$("#link-upload").dialog();
}
});
I wanted to see if the data was in fact being passed so I threw an alert in the .post. This is the error I'm getting now:
I have tried passing plain text and echoing it back on the page but it fails. It is just not passing.
Try this -
$.ajax({
type: "POST",
url: "../modules/Slide_Show/slide_show.php",
data: { id : id }
});
http://pastebin.com/dttyN3L6
The file that processes the form is called upload.php
I have never really used jquery/js so I am unsure how I would do this or where I would put the code.
It has something to do with this setInterval (loadLog, 2500);
Also, how can I make it so the user can submit a form without the page refreshing?
$.ajax({
type: "POST",
url: "upload.php",
data: dataString,
success: function() {
}
});
return false; `
and
<?php
$conn1 = mysqli_connect('xxx') or die('Error connecting to MySQL server.');
$sql = "SELECT * from text ORDER BY id DESC LIMIT 1";
$result = mysqli_query($conn1, $sql) or die('Error querying database.');
while ($row = mysqli_fetch_array($result)) {
echo '<p>' . $row['words'] . '</p>';
}
mysqli_close($conn1);
?>
</div>
<?php
if (!isset($_SESSION["user_id"])) {
} else {
require_once('form.php');
}
?>
You can submit a form without refreshing a page something like this:
form.php:
<form action='profile.php' method='post' class='ajaxform'>
<input type='text' name='txt' value='Test Text'>
<input type='submit' value='submit'>
</form>
<div id='result'>Result comes here..</div>
profile.php:
<?php
// All form data is in $_POST
// Now perform actions on form data here and
// create an result array something like this
$arr = array( 'result' => 'This is my result' );
echo json_encode( $arr );
?>
jQuery:
jQuery(document).ready(function(){
jQuery('.ajaxform').submit( function() {
$.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
dataType: 'json',
data : $(this).serialize(),
success : function( data ) {
// loop to set the result(value)
// in required div(key)
for(var id in data) {
jQuery('#' + id).html( data[id] );
}
}
});
return false;
});
});
And If you want to call an ajax request without refreshing page after a particular time, you can try something like this:
var timer, delay = 300000;
timer = setInterval(function(){
$.ajax({
type : 'POST',
url : 'profile.php',
dataType: 'json',
data : $('.ajaxform').serialize(),
success : function(data){
for(var id in data) {
jQuery('#' + id).html( data[id] );
}
}
});
}, delay);
And you can stop the timer at any time like this:
clearInterval( timer );
Hope this will give you a direction to complete your task.
This is pretty simple.
To access elements using Jquery you use css selectors, for example, to get value of an input field with name "foo" you do the following:
var fooVal = $("input[name=foo]").val();
To send it over to the server you are to append an event listener (for example, click) to the submit button/any other element
var data = { varName : fooVal };
var url = "http://example.com";
var responseDataType = "json";
function parseResponse(JSON)
{
// your code handling server response here, it's called asynchronously, so you might want to add some indicator for the user, that your request is being processed
}
$("input[type=submit]").on('click', function(e){
e.preventDefault();
$(this).val("query processing");
$.post(url,data, parseResponse, responseDataType);
return false;
});
If you want to do constant updates, you can, of course, add timers or some other logic. But I hope you get the idea of how to proceed to such cases;
To answer part of your question, you can use ajax.
<html><head></head><body>
<div id="feed"></div>
<script type="text/javascript">
var refreshtime=10;
function tc()
{
asyncAjax("GET","upload.php",Math.random(),display,{});
setTimeout(tc,refreshtime);
}
function display(xhr,cdat)
{
if(xhr.readyState==4 && xhr.status==200)
{
document.getElementById("feed").innerHTML=xhr.responseText;
}
}
function asyncAjax(method,url,qs,callback,callbackData)
{
var xmlhttp=new XMLHttpRequest();
//xmlhttp.cdat=callbackData;
if(method=="GET")
{
url+="?"+qs;
}
var cb=callback;
callback=function()
{
var xhr=xmlhttp;
//xhr.cdat=callbackData;
var cdat2=callbackData;
cb(xhr,cdat2);
return;
}
xmlhttp.open(method,url,true);
xmlhttp.onreadystatechange=callback;
if(method=="POST"){
xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xmlhttp.send(qs);
}
else
{
xmlhttp.send(null);
}
}
tc();
</script>
</body></html>