can getJSON() be used for php? - php

This is the JQuery code loaded over click but the callback function isn't working:
$.getJSON("load_img.php", {"id":"start"} , function(json){
alert(json);
});
PHP code gives me this output:
[
{"img_name":"shiva.jpg","img_id":"1"},
{"img_name":"shiva.jpg","img_id":"2"},
{"img_name":"Recoverd_jpg_file(4).jpg","img_id":"3"},
{"img_name":"Recoverd_jpg_file(542).jpg","img_id":"4"}
]
I cannot load any PHP pages from getJSON() function...i downloaded sample source code from [here][1]
[1]: http://www.sitepoint.com/ajaxjquery-getjson-simple/ and have run it on browser but it doesnt work still...
any help would be much appreciated!!!Thank you

I got my answer today...no <html> tags should be included in the code to be outputted... it should only contain starting and ending php tags i.e.
<?php
//your code or codes
?>

$.getJSON("path to php file", {method: "*", "id":"start"})
.done(function (data) {
console.log(data)
});
//================in php=================================
if($_REQUEST['method'] == "your method" AND $_REQUEST['id'] ) {
//call your php function
}
//-------------------
//and put your php code in function
//.. i hope this help you

<button id="try" type="button">Try</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
$.getJSON("load_img.php", {"id":"start"}, function(result){
$.each(result, function(i, field){
alert(field.img_name);
});
});
i is the field name and field is value. Please check and post me back. For further details :-http://www.w3schools.com/jquery/ajax_getjson.asp
Page Two:-
<?php
// ini_set("display_errors", "On");
//header('content-type:application/json');
$id = $_GET["id"];
if ($id == "start")
{
$con=new mysqli("localhost", "root", "rootwdp", "try");
$numbers = array();
$img_arr = array();
$res = $con->query("select img_name, img_id from img");
while ($row = $res->fetch_assoc())
// mysql_fetch_array() passes parameters from 0
{ $numbers[]=$row; }
echo json_encode($numbers);
}
?>

Related

PHP file not picking up $POST parameter from JQuery

Thank you very much for your help. I have the following file. The two alerts in the jquery event listener both work, but not the one inside the if (isset) block, as it is posting to itself. Thank you very much! I have abbreviated the code, everything is inside its proper tag.
<?php session_start();
include("config.php");
$myID = $_POST['chatid'];
$_SESSION['chateeID'] = $myID;
if(isset($_POST['inputmessage'])) {
echo '<script type="text/javascript">alert("got in here");</script>';
$sMessage = mysqli_real_escape_string($_POST['inputmessage']);
if ($sMessage != '') {
$sql = "INSERT INTO chatmessages (user_one_id, user_two_id, mymessage, action_user_id)
VALUES ('$user1', '$user2', '$sMessage', '$action_user_id')";
// Perform a query, check for error
if (!mysqli_query($con,$sql)){
echo '<script type="text/javascript">alert("'.mysqli_error($con).'");</script>';
}
}
}
<script>
$('#ChatInputBox').keydown(function (e) {
var keyCode = e.keyCode || e.which;
var txt = $("#ChatInputBox").val();
if (keyCode == 13 && txt!="") {
alert("txt is: "+txt);
$.post("inserttochat.php", { inputmessage: txt }, function(result){
alert("got to callback!");
});
}
});
</script>
I did this exactly the same way on another page but cannot find the discrepancy here.
After setting up your code on my development system I discovered that the short piece of script your PHP code is sending is being sent correctly, and being received correctly but not being executed by the jQuery AJAX code.
If you want that alert to show up in your page you need to place it in an HTML element
<div id="response"></div>
then
$.post("inserttochat.php", { inputmessage: txt }, function(result){
alert("got to callback!");
$("response").html(result);
});
A better way to do this is to echo some sort of status as a JSON object, then unpack that into an alert in Javascript.
echo json_encode((object)['status'=>'ok', 'msg'=>'All good']);
then
$.post("inserttochat.php", { inputmessage: txt }, function(result){
alert("Response: "+result.status+', '+result.msg);
},'json');
Note the json datatype added to the POST request*.
A better approach here is to standardise all your responses as JSON, and then add header("Content-type: application/json"); at the top of your PHP files. This will tell jQuery what the data is, rather than you having to force the issue in the browser.

Send variable from PHP to JQUERY to other PHP file

I have an image and after clicking this image I take this game id by JQuery code and then a new PHP tap opens this PHP take should display this image id
Here is the JQuery code:
$(".selected").click(function(){
$.post("bookinfo.php", { id: $(this).attr('id') }, function (response) {
alert(response);
});
});
and here is the PHP code
<?php
$id = $_POST['id'];
echo $id;
?>
and here is the error that i get
Notice: Undefined index: id in C:\xampp\htdocs\bookstore\bookinfo.php on line 2
I have tried AJax request and get but the same error happens..
I have been trying for this error for about 2 hours so please help me!
You can do something like this:
Edited:
jQuery
<script>
$(document).ready(function(){
$(document).on('click','.selected',function(){
var id = $(this).attr('id');
window.location.replace("bookinfo.php?id=" + id);
});
});
</script>
PHP
<?php
if(isset($_GET['id']) && !empty($_GET['id'])){
$id = $_GET['id'];
echo $id;
}
?>
in your php you have to return a json to get it from AJAX. just try changing your php code like this.
<?php
header('Content-Type: application/json');
if(isset($_POST['id']))
{
$data = array($_POST['id']);
echo json_encode($data);
}

I have encountered a really weird thing while Inserting jquery var in mysql table from a php page

I have a php page where i have used a jquery function to get the dynamic value according to the values of checkboxes and radio buttons and text boxes. Whats' happening is i have used two alerts
1.) alert(data);
2.)alert(grand_total);
in the ajax part of my Jquery function just to ensure what value i'm getting in "grand_total". And everything worked fine, alerts were good and data was being inserted in the table properly.
Then i removed the alerts from the function, and after sometime i started testing the whole site again and i found value of grand_total in not being inserted in mysql table.
I again put those alerts to check what went wrong, again everything started working fine. Removed again and problem started again. Any idea folks what went wrong?
here is the code snippet of JQUERY func from "xyz.php":
<script type="text/javascript">
$(document).ready(function() {
var grand_total = 0;
$("input").live("change keyup", function() {
$("#Totalcost").val(function() {
var total = 0;
$("input:checked").each(function() {
total += parseInt($(this).val(), 10);
});
var textVal = parseInt($("#min").val(), 10) || 0;
grand_total = total + textVal;
return grand_total;
});
});
$("#next").live('click', function() {
$.ajax({
url: 'xyz_sql.php',
type: 'POST',
data: {
grand_total: grand_total
},
success: function(data) {
// do something;
}
});
});
});
Corresponding HTML code:
<form method="post" id="logoform3" action="xyz_sql.php">
<input type="text" name="Totalcost" id="Totalcost" disabled/>
<input type="submit" id="Next" name="next"/>
This the code from *"xyz_sql.php"*:
<?php
session_start();
include ("config.php");
$uid = $_SESSION['uid'];
$total= mysql_real_escape_string($_POST['grand_total']);
$sql="INSERT INTO form2 (total,uid)VALUES('$total','$uid');";
if($total > 0){
$res = mysql_query($sql);
}
if($res)
{
echo "<script> window.location.replace('abc.php') </script>";
}
else {
echo "<script> window.location.replace('xyz.php') </script>";
}
?>
And last but not the least: echo " window.location.replace('abc.php') ";
never gets executed no matter data gets inserted in table or not.
First you submit form like form, not like ajax - cause there is no preventDefault action on clicking submit button. That's why it looks like it goes right. But in that form there is no input named "grand_total". So your php script fails.
Second - you bind ajax to element with id "next" - but there is no such element with that id in your html that's why ajax is never called.
Solutions of Роман Савуляк is good but weren't enough.
You should casting your $total variable to integer in php file and also use if and isset() to power your code, so I'll rewrite your php code:
<?php
session_start();
include ("config.php");
if(isset($_SESSION['uid']))
{
$uid = $_SESSION['uid'];
if(isset($_POST['grand_total']))
{
$total= mysql_real_escape_string($_POST['grand_total']);
$sql="INSERT INTO form2(total,uid) VALUES('".$total."','".$uid."')";
if((int)$total > 0)
{
if(mysql_query($sql))
{
echo "your output that will pass to ajax done() function as data";
}
else
{
echo "your output that will pass to ajax done() function as data";
}
}
}
}
and also you can pass outputs after every if statement, and complete js ajax function like:
$.ajax({
url: 'xyz_sql.php',
type: 'POST',
data: {
grand_total: grand_total
}
}).done(function(data) {
console.log(data); //or everything
});

Set JS var with PHP var with AJAX

I have a php script that watches for the newest json file in a directory (below). Then in a javascript I parse and display the data from that file. The javascript reloads the data every x minutes.
I won't have the name of the file just that it will contain json data and to use the newest one.
The PHP script stores the most recent file stored in array fileList[0]. I want to pass that to the javascript without a full page refresh so I checked this stackoverflow post and found that an ajax call can be made to a php script but the example updates an element on the page.
Is there a way to update a javascript variable? I thought of maybe placing the filename as a hidden element and the grabbing before I refresh the data, but that seemed crude.
<?php
date_default_timezone_set('America/New_York');
$files = glob('json/*.*', GLOB_BRACE);
usort($files, 'filemtime_compare');
function filemtime_compare($a, $b)
{
return filemtime($b) - filemtime($a); // Order newest to oldest
}
$i = 0;
$show = 1; // Number of new files to show.
$fileList = array();
foreach($files as $file)
{
if($i == $show) break; else ++$i;
array_push($fileList, $file);
}
//echo $fileList[0] // DEBUG: Make sure I have the right file.
?>
AJAX:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
// This will send a request to a PHP page
$.ajax({
var jsonURL = "";
url: "phpDir.php",
dataType: "html",
success: function(data){
// Place the returned data into your content
}
jsonURL = $fileList[0];
});
</script>
</head>
<body>
To answer your question "Is there a way to update a javascript variable?"
You would do this:
var jsonURL = '';
function loadXMLDoc() {
// This will send a request to a PHP page
$.ajax({
url: "phpDir.php",
dataType: "JSON",
success: function(data){
jsonURL = data.url;
}
});
}
For ease of communication I have set the dataType to JSON. So PHP output would need to be json_encoded()ed:
<?php
$output = array('url' => $fileList[0]); // or whatever URL you want to return
echo json_encode($output);
?>

Jquery not connecting to .php

I am having some trouble with my jquery. I am not sure if it is connecting to doc.php but I am not getting anything inserted into my database.
I have an insert command in doc.php which I know is working.
I'm trying to create a way to update prices in a database, from doc.php, that searches out items one at a time.
The doc.php is searching by var, then updating in the same page.
The foreach loop function then, takes the var one by one, sends them to the doc.php page that then searches by var and updates into the database.
<?php
mysql_connect("", "", "") or die(mysql_error());
mysql_select_db("") or die (mysql_error());
$sql = "SELECT var FROM table";
$query = mysql_query($sql) or die (mysql_error());
while ($result = mysql_fetch_array($query)) {
$variable = array($result['var']);
foreach ($variable as $variable1) {
?>
<script src="jquery-1.7.2.min.js" type="text/javascript">
$(function() {
var valueToSend = '<?php echo $variable1; ?>';
$.ajax({
url: "doc.php",
dataType: "json",
type: "POST",
data: { Variable: valueToSend },
success: function (m) {
alert(m);
},
error: function (e) {
alert("Something went wrong ...: "+e.message);
},
}); /* end ajax*/
e.preventDefault();
});
</script>
<?php
}
}
?>
First of all, what do you want to do with this code? If you want to read & write to db using php, ajax call is unnecessary. If you want to practice ajax & php you need to read some howto because your code is somewhere strange ;). This is nice collection of tutorials for jQuery and some for PHP read some and practice.

Categories