JSON encode is not working properly in ajax function - javascript

I built an event to change product name that mix up with ajax and json encode
<div class="new-product-name"></div>
<div class="new-product-num"></div>
Then the script is
$(function(){
$.ajax({
method: "POST",
url: "fetch-product.php",
data: {keyword: 12}
}).done(function(msg){
$(".new-product-name").html(msg);
$.getJSON("fetch-product.php", function(data) {
$(".new-product-name").html(data.a);
$(".new-product-num").html(data.b);
});
});
});
in fetch-product.php
$query = "SELECT * FROM `product_details` WHERE id='". $_POST['keyword']."'";
$result = $conn->query($query);
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
$name=$row["p_name"];
$num=$row["num"];
}
echo json_encode(array("a" => $name, $num));
Here product details is fetching correctly , even in $(".new-product-name").html(msg); it showing '{"a":"Product1", "b":"22"}', it is entering in to $.getJSON("fetch-product.php", function(data) { }
But data.a , data.b showing null.
why is data.a , data.b null ?I am spending too much time . Please help to solve this error .

I see no reason to make 2 calls to the PHP script.
If you add the dataType:json parameter jQuery will expect a JSONString back from the PHP and msg will be automatically converted to a javascript object.
$(function(){
$.ajax({
method: "POST",
dataType: "json", // new param
url: "fetch-product.php",
data: {keyword: 12}
})
.done(function(msg){
if ( msg.status == 1 ) {
$(".new-product-name").html(msg.a);
$(".new-product-num").html(msg.b);
} else {
$(".new-product-name").html(msg.info);
}
});
});
The other issue with your call to $.getJSON("fetch-product.php",..... was that this would issue a GET request, and therefore fill the $_GET array with any parameters. Your PHP code is not looking for parameters passed in the $_GET array!
Your PHP code as it was, was vulnerable to SQL Injection, so I have amended it to use Parameterised & Prepared statements.
You also need to consider the possibility that nothing is found by your query and return something to let the javascript know about that.
$query = "SELECT * FROM `product_details` WHERE id=?";
$stmt = $conn->prepare($query);
$stmt->bind_param('i', $_POST['keyword']);
$result = $stmt->execute();
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
echo json_encode(array( 'status'=> 1,
'a'=>$row["p_name"],
'b'=>$row["num"]);
} else {
echo json_encode(array('status'=>0,
'info'=>'No data found');
}

$.ajax({
method: "POST",
url: "fetch-product.php",
data: {keyword: 12}
}).done(function(msg){
$(".new-product-name").html(msg);
makes a POST to fetch-product and writes the value of msg into the product name element. Except that it should probably be msg.a since your code returns an object with the data inside the a property. You also need to set the dataType:json option so that jQuery knows the returned value from the server is an object and not a string.
However, you then make another request to the same URL, but using a GET request and without passing any parameters. Since your PHP tries to read values from POST requests only, this causes your query to return nothing, and thus your output of $name is empty. You then overwrite your product name element with this empty value.
Why you are making this second request to the same resource, but with the wrong settings, is a complete mystery. It is totally unnecessary. This code should do what you need in a single request:
$(function(){
$.ajax({
method: "POST",
url: "fetch-product.php",
data: {keyword: 12},
dataType: "json"
}).done(function(msg){
$(".new-product-name").html(msg.a);
$(".new-product-num").html(msg.b);
});
});
P.S. Your SQL is incredibly vulnerable to SQL Injection attacks. You should switch to using parameterised queries and prepared statements. Otherwise someone could send a malicious value in the "keyword" parameter and steal, destroy or otherwise corrupt your data. See http://bobby-tables.com/ for a humorous but very clear example of this sort of problem. Both the PDO and mysqli libraries for PHP provide easy ways to create prepared statements, and there are hundreds of examples of the syntax available online for you to follow.

As #Sirko already said, you are sending two requests:
$(function(){
$.ajax({ // First request, as planned
method: "POST",
url: "fetch-product.php",
data: {keyword: 12}
}).done(function(msg){
$(".new-product-name").html(msg);
// This will send an additional GET request to fetch-product.php without any parameters
$.getJSON("fetch-product.php", function(data) {
$(".new-product-name").html(data.a);
});
});
});
Remove the second request or replace the first with the second, if GET method is applicable it should work fine. Because the second request returns null the html of everything with the class .new-product-name will be empty ("").

If You want to make two php calls , then try This:
fetch-product.php
<?php
if($_SERVER['REQUEST_METHOD'] == 'GET' ){
$keyword = $_GET['keyword'];
}else{
$keyword = $_POST['keyword'];
}
$query = "SELECT * FROM `product_details` WHERE id='". $keyword."'";
$result = $conn->query($query);
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
$name=$row["p_name"];
$num=$row["num"];
}
echo json_encode(array("a" => $name, $num));
?>
Then the Script is
$(function(){
var data = {keyword: 12};
$.ajax({
method: "POST",
url: "fetch-product.php",
data: data
}).done(function(msg){
$(".new-product-name").html(msg);
$.getJSON("fetch-product.php",{keyword: 12}).done(function(data1) {
$(".new-product-name").html(data1.a);
});
});
});

Related

load a file using variable from client side

I need to load a file inside a container, but using an argument - to get some data from database firstly:
$('#story').load('test.php');
test.php
$st = $db->query("select * from users where id = " . $id);
... processing variables... load the finished content
Here I need $id from client side. Is it possible?
yes ..you could pass with url query
$('#story').load('test.php?id=1');
test.php
$id = isset($_REQUEST['id'])?$_REQUEST['id']):'';
$st = $db->query("select * from users where id = " . $id);
You can use ajax request and on success you load your file something like:
$.ajax({
type: 'POST',
url: "test.php", //make sure you put the right path there
data: {id: id},
dataType: "json",
success: function (resultData) {
$('#story').load('test.php');
}
})
Just make sure that your php function returns/echos the id you want.
That way you make a call to your php file and when it's successful you will load your file and you can put extra logic there if you want to return more data to use it of course.
resultData holds the output of your php function so it's up to you what info you want to be there.
You could use Ajax to post the ID to your php code.
$.ajax({
type: "POST",
url: "test.php",
data: { 'id': foo },
cache: false,
success: function(){
alert("Order Submitted");
}
});
php:
<?php
$id = $_POST['id'];

Passing data with POST with AJAX

I'm trying to POST some data to another page with AJAX but no info is going, i'm trying to pass the values of two SELECT (Dropdown menus).
My AJAX code is the following:
$('#CreateHTMLReport').click(function()
{
var DeLista = document.getElementById('ClienteDeLista').value;
var AteLista = document.getElementById('ClienteParaLista').value;
$.ajax(
{
url: "main.php",
type: "POST",
data:{ DeLista : DeLista , AteLista : AteLista },
success: function(data)
{
window.location = 'phppage.php';
}
});
});
Once I click the button with ID CreateHTMLReport it runs the code above, but it's not sending the variables to my phppage.php
I'm getting the variables like this:
$t1 = $_POST['DeLista'];
$t2 = $_POST['ParaLista'];
echo $t1;
echo $t2;
And got this error: Notice: Undefined index: DeLista in...
Can someone help me passing the values, I really need to be made like this because I have two buttons, they are not inside one form, and when I click one of them it should redirect to one page and the other one to another page, that's why I can't use the same form to both, I think. I would be great if someone can help me with this, on how to POST those two values DeLista and ParaLista.
EDIT
This is my main.php
$('#CreateHTMLReport').on('click',function() {
$.ajax({
// MAKE SURE YOU HAVE THIS PAGE CREATED!!
url: "main.php",
type: "POST",
data:{
// You may as well use jQuery method for fetching values
DeLista : $('#ClienteDeLista').val(),
AteLista : $('#ClienteParaLista').val()
},
success: function(data) {
// Use this to redirect on success, this won't get your post
// because you are sending the post to "main.php"
window.location = 'phppage.php';
// This should write whatever you have sent to "main.php"
//alert(data);
}
});
});
And my phppage.php
if(!empty($_POST['DeLista'])) {
$t1 = $_POST['DeLista'];
# You should be retrieving "AteLista" not "ParaLista"
$t2 = $_POST['AteLista'];
echo $t1.$t2;
# Stop so you don't write the default text.
exit;
}
echo "Nothing sent!";
And I'm still getting "Nothing Sent".
I think you have a destination confusion and you are not retrieving what you are sending in terms of keys. You have two different destinations in your script. You have main.php which is where the Ajax is sending the post/data to, then you have phppage.php where your success is redirecting to but this is where you are seemingly trying to get the post values from.
/main.php
// I would use the .on() instead of .click()
$('#CreateHTMLReport').on('click',function() {
$.ajax({
// MAKE SURE YOU HAVE THIS PAGE CREATED!!
url: "phppage.php",
type: "POST",
data:{
// You may as well use jQuery method for fetching values
DeLista : $('#ClienteDeLista').val(),
AteLista : $('#ClienteParaLista').val()
},
success: function(data) {
// This should write whatever you have sent to "main.php"
alert(data);
}
});
});
/phppage.php
<?php
# It is prudent to at least check here
if(!empty($_POST['DeLista'])) {
$t1 = $_POST['DeLista'];
# You should be retrieving "AteLista" not "ParaLista"
$t2 = $_POST['AteLista'];
echo $t1.$t2;
# Stop so you don't write the default text.
exit;
}
# Write a default message for testing
echo "Nothing sent!";
You have to urlencode the data and send it as application/x-www-form-urlencoded.

AJAX not coming up a success even though its updating the database

My php is updating the table but not refreshing in javascript have tried several different ways of doing this and nothing is working.
PHP
$sql = "UPDATE INTOXDM.ASTP_FORM SET SUPERVISOR_EID = '".$newSuper."' WHERE FORMID = '".$formId."'";
$row = $xdm->fetch($sql);
$return["color"] = $row['APPRENTICE_SIGNATURE'];
$return["json"] = json_encode($return);
echo json_encode($return);
?>
Javascipt
var data = {
"formId": formID,
"newSuper": newSuper
};
data = $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "src/GetInfo.php",
data: data,
success: function() {
location.reload();
}
});
I'd start by modifing the code like this:
var data = {
"formId": formID,
"newSuper": newSuper
};
// No need for serialization here,
// the 'data' parameter of jQuery.ajax accepts JS object
// data = $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "src/GetInfo.php",
data: data,
// As suggested by Rocket Hazmat, try to add an error callback here
error: function(jQueryXHR, textStatus, errorMessage) {
console.log("Something went wrong " + errorMessage);
},
success: function(jsonResponse) {
// Try to reference the location object from document/window
// wd = document or window as seen here http://stackoverflow.com/questions/2624111/preferred-method-to-reload-page-with-javascript
// Also watch out, usually browsers require a user confirmation before reloading if the page contains POST data
// One of these should be fine
wd.location.assign(wd.location.href) : go to the URL
wd.location.replace(wd.location.href) : go to the URL and replace previous page in history
wd.location.reload(<true/false/blank>) : reload page from server/cache/cache
}
});
Also, this might be a shot in the dark but the parameter dataType gave me problems sometime in the past, so if you are sure about the json returned by your php script, you could use the eval function to jsonify the response
$.ajax({
...
// Remove data type
// dataType: "json",
...
success: function(plainTextResponse) {
// Eval response, NOT SAFE! But working
var jsonResponse = eval('('+ plainTextResponse +')');
...
}
});
Your ajax is expecting json data and your php is sending malformed json string. Send a correct json string and your script will work fine.
Your php json_encode should be like this:
$data = json_encode($return);
echo $data;

How to send an ID through AJAX to another file and use the ID in thus file

I have an HTML file which contains various fields as follows(I will only show one example since the rest are the same):
<map name="parcerlas">
<area shape="poly" coords="618,4,618,74,681,76,683,56,684,39,684,27,683,14,682,4" href="#" alt="Parcela 9" title="Parcela 9" onclick="getdata('9');">
</map>
Using the functiong getdata() I retrieve the ID inside and I need to pass this ID using AJAX to another PHP file and use it in the new file. How can I achieve this?
Here is my getdata() function:
<script type="text/javascript">
function getdata(id){
alert(id);
$.ajax({
type: "POST",
url: "activations.php",
data:
{
id;
}
}
</script>
You need to specify the key of the data:
data: { 'id': id }
Also there are syntax errors in your snippet:
function getdata(id){
alert(id);
$.ajax({
type: "POST",
url: "activations.php",
data: {
'id': id // < no need for semi-colon, properties are key->value based, 'key': value
}
}); // << no closing bracket and semi-colon
} // << close your function
So you can access it in your activations.php:
$_POST["id"]
Always check if it is isset or not:
if (isset($_POST["id"])) $id = $_POST["id"]; else exit;
Answering OP's particular questions:
You need to open a PDO connection to your SQL server (example with MySQL)
if (isset($_POST["id"])) $id = $_POST["id"]; else exit;
$db = new PDO('mysql:host=localhost;dbname=yourdb;charset=utf8',
'username',
'password'); // Open a connection to your database
$q = $db->prepare("SELECT * FROM achievements WHERE id=?"); // Get all achievements where id=$id
$q->execute(array($id)); // Run the query
$rows = $q->fetchAll(); // Fetch the query, associated array
echo json_encode($rows); // Convert the $rows to json, so javascript can read it
You will have to set the datatype of your ajax request to JSON or parse the data on your own with $.parseJSON(data);
You can use the returned data with adding a success function to your ajax:
function getdata(id){
alert(id);
$.ajax({
type: "POST",
url: "activations.php",
data: {
'id': id // < no need for semi-colon, properties are key->value based, 'key': value
},
success: function(data) {
var achievements = $.parseJSON(data);
// use achievements variable
}
}); // << no closing bracket and semi-colon
} // << close your function
You have a few typos (no closing brackets on Ajax call, unwanted semi-colon etc), but mainly need to provide the data as a key value pair. Note: the quotes are only required in a key name if it is not a single word (no spaces or hyphen/- etc):
<script type="text/javascript">
function getdata(id){
alert(id);
$.ajax({
type: "POST",
url: "activations.php",
data:
{
id: id
}
});
}
</script>
Change id; to 'id':id and no semicolon(;)

Array from javascript to php with Ajax - Mootools

Actually i'm developing a timetable selector. Well now i'mt trying to send the values to the miscrosoft sql server database.
I'm using mootools, and i'm doing a request as Ajax to pass all values from javascript to php. My problem is that if i send each value individually, it is very slow. So i'm trying to send every values in a javascript object.
var myRequest = new Request.HTML({
url: "index.php?pagina=2087&",
method: "post",
data: 'transfer='+artigos_sessao,
onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript){
<?php saveData(); ?>
},
}).send();
artigos_sessao is my object with this format {'key':{'id':value,'sessao':value},...}.
And in PHP side i'm doing this
$array= $_POST['transfer'];
echo $array;
But always my $array variable is empty.
What i'm doing wrong?
Thanks.
You can pass a object into the data field of the Request. So my suggestion is to remove parameters from the url and just pass everything as a object in the data:
var myRequest = new Request.HTML({
url: "index.php",
method: "post",
data: {
'pagina': 2087,
'transfer': artigos_sessao
},
onSuccess: function (responseTree, responseElements, responseHTML, responseJavaScript) {
<? php saveData(); ?> // this code is not in your question, i supose you have javascript here hopefully :)
},
}).send();

Categories

Resources