load a file using variable from client side - javascript

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'];

Related

how to use data sent with Ajax POST in PHP

I have a strange behaviour, I sent data to a PHP page using Post request, my problem is when I try to manipulate this data (echo for exemple) in PHP page I get nothing, but when I make condition on the value I sent the condition is ok.
My JS code
$.ajax({
type: "POST",
url: 'admin/page.php',
data: {
type: 'search',
date1:'2021/04/15',
date2:'2021/04/13'
},
success: function(data){
alert(data);
}
});
My PHP code
$uname = $_POST["type"];
$date1 = $_POST["date1"];
$date2 = $_POST["date2"];
if ($uname=='search') // condition OK
{
echo $date1;
echo $date2;
}

JSON encode is not working properly in ajax function

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);
});
});
});

codeigniter or PHP - how to go to a URL after a specific AJAX POST submission

I am successfully inserting data into my database in codeigniter via a an ajax post from javascript:
//JAVASCRIPT:
$.ajax({
type: "POST",
url: submissionURL,
data: submissionString,
failure: function(errMsg) {
console.error("error:",errMsg);
},
success: function(data){
$('body').append(data); //MH - want to avoid this
}
});
//PHP:
public function respond(){
$this->load->model('scenarios_model');
$responseID = $this->scenarios_model->insert_response();
//redirect('/pages/view/name/$responseID') //MH - not working, so I have to do this
$redirectURL = base_url() . 'pages/view/name/' . $responseID;
echo "<script>window.location = '$redirectURL'</script>";
}
But the problem is that I can't get codeigniter's redirect function to work, nor can I get PHP's header location method to work, as mentioned here:
Redirect to specified URL on PHP script completion?
either - I'm guessing this is because the headers are already sent? So as you can see, in order to get this to work, I have to echo out a script tag and dynamically insert it into the DOM, which seems janky. How do I do this properly?
Maybe you can 'return' the url in respond function and use it in js
PHP :
public function respond(){
// code
$redirectURL = base_url() . 'pages/view/name/' . $responseID;
return json_encode(['url' => $redirectURL]);
}
JS :
$.ajax({
type: "POST",
url: submissionURL,
data: submissionString,
dataType: 'JSON',
failure: function(errMsg) {
console.error("error:",errMsg);
},
success: function(data){
window.location = data.url
}
});
you have to concatenate the variable. That's all.
redirect('controller_name/function_name/parameter/'.$redirectURL);

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;

Javascript passing variable issue not returning

Hi All I have the following code to pass a JS variable using AJAX as seen below:
function buttonCallback(obj){
var id = $(obj).attr('id');
$.ajax({
type: "POST",
url: "/project/main/passid",
data: { 'id': id },
success: function(msg){
window.alert(msg);
}
});
}
if I put an alert box in I can see the object id is successfully getting grabbed. however if in php I want to simply return the variable - I am getting a null has anyone got any ideas:
heres my PHP function (I am using Codeigniter):
public function passid(){
$courseId = $this->input->post('id');
echo $courseId;
}
EDIT: the success alert box appears - but appears blank and that is my issue I am hoping to see the ID
1. Can you make sure id equals something by doing this:
function buttonCallback(obj){
var id = $(obj).attr('id');
alert( id ); // What does it alert?
$.ajax({
type: "POST",
url: "/project/main/passid",
dataType: "json",
data: { 'id': id },
success: function(msg){
window.alert(msg.id);
}
});
}
2. Your javascript looks good... Can you try this instead to see if it works:
JS
function buttonCallback(obj){
var id = $(obj).attr('id');
$.ajax({
type: "POST",
url: "/project/main/passid",
dataType: "json",
data: { 'id': id },
success: function(msg){
window.alert(msg.id);
}
});
}
PHP
public function passid(){
$courseId = $this->input->post('id');
$response = array( "id" => $courseId );
header('Content-Type: application/json');
echo json_encode( $response );
}
3. If this does not work, can you try and rename from id to something like poopoo, just to make sure id is not taken and being weird?
4. Can you check what the network response is of your ajax request - Go to developer toolbar and goto network section, make sure you hit the record/play button. then send your request off. When you see your request come up in the network list, check the "details" of it and goto response.

Categories

Resources