I have a drpcategory dropdown in a form. I will just paste the dropdown code below;
<div class="form-group">
<label>Category</label>
<select class="form-control bg-dark btn-dark text-white" id="drpcategory" name="drpcategory" required>
<?php
$category = ''.$dir.'/template/post/category.txt';
$category = file($category, FILE_IGNORE_NEW_LINES);
foreach($category as $category)
{
echo "<option value='".$category."'>$category</option>";
}
?>
</select>
</div>
Then I AJAX post every time I make a selection in the above drpcategory dropdown as below;
<script>
$(function(){
$('#drpcategory').on('change',function()
{
$.ajax({
method: 'post',
data: $(this).serialize(),
success: function(result) {
console.log(result);
}
});
});
});
</script>
This seems to be currently working as I'm getting outputs like below in Chrome Browser > Inspect > Network tab every time I make a selection in drpcategory. Here is the screenshot;
The question is how can I capture this AJAX post data using PHP within the same page and echo it within the same page? So far I have tried;
<?php
if(isset($_POST['drpcategory']))
{
echo 'POST Received';
}
?>
I'm looking for a solution using only PHP, JQuery and AJAX combined.
This question was later updated and answered here:
AJAX POST & PHP POST In Same Page
First of all, this line -> type: $(this).attr('post') should be type: $(this).attr('method'),. So this will give the value ** type:post** and
As far as i understand, you are asking to send ajax whenever you select options from drpcategory. Why are you submitting the entire form for this. If i where you, i should have done this problem by following way
$("#drpcategory").change(function(){
e.preventDefault();
var drpcategory=$(this).val();
$.ajax({
type: 'post',
data: drpcategory,
success: function(result) {
console.log(result);
}
});
});
On you php side, you can get your data like,
echo $_POST['drpcategory'];
I recommend you read the documentation for the ajax function, I tried to replicate it and I had to fix this:
$.ajax({
// If you don't set the url
// the request will be a GET to the same page
url: 'YOU_URL',
method: 'POST', // I replaced type by method
data: $(this).serialize(),
success: function(result) {
console.log(result);
}
});
http://api.jquery.com/jquery.ajax/
OUTPUT:
First change to $value
<div class="form-group">
<label>Category</label>
<select class="form-control bg-dark btn-dark text-white" id="drpcategory" name="drpcategory" required>
<?php
$category = ''.$dir.'/template/post/category.txt';
$category2 = file($category, FILE_IGNORE_NEW_LINES);
foreach($category2 as $value)
{
echo "<option value='".$value."'>".$value."</option>";
}
?>
</select>
then add url
<script>
$(function()
{
$('#form').submit(function(e)
{
e.preventDefault();
$.ajax({
url:'folder/filename.php',
type: 'post',
data: '{ID:" . $Row[0] . "}',
success: function(result) {
console.log(result);
}
});
});
$('#drpcategory').on('change',function()
{
$("#form").submit();
});
});
try request
if(isset($_REQUEST['ID']))
The result will/should send back to the same page
Please try this code:
$.post('URL', $("#FORM_ID").serialize(), function (data)
{
alert('df);
}
I think you have an eroror syntax mistake in ajax jQuery resquest because ajax post 'http://example.com/?page=post&drpcategory=Vehicles' does not return this type url in browser Network Tab.
<?php var_dump($_POST); exit; ?> please do this statment in your php function if anything posted to php page it will dump.
Here ajax request example
$("#drpcategory").change(function(){
e.preventDefault();
var drpcategory=$(this).val();
$.ajax({
type: 'post',
data: drpcategory,
success: function(result) {
console.log(result);
}
});
});
`
It sounds like you're trying to troubleshoot several things at once. Before I can get to the immediate question, we need to set up some ground work so that you understand what needs to happen.
First, the confusion about the URL:
You are routing everything through index.php. Therefore, index.php needs to follow a structure something like this:
<?php
// cleanse any incoming post and get variables
// if all your POST requests are being routed to this page, you will need to have a hidden variable
// that identifies which page is submitting the post.
// For this example, assume a variable called calling_page.
// As per your naming, I'll assume it to be 'post'.
// Always check for submitted post variables and deal with them before doing anything else.
if($_POST['calling_page'] == 'post') {
// set header type as json if you want to use json as transport (recommended) otherwise, just print_r($_POST);
header('Content-Type: application/json');
print json_encode(array('message' => 'Your submission was received'));
// if this is from an ajax call, simply die.
// If from a regular form submission, do a redirect to /index.php?page=some_page
die;
}
// if you got here, there was no POST submission. show the view, however you're routing it from the GET variable.
?>
<html>
(snip)
<body>
<form id="form1" method="post">
<input type="hidden" name="calling_page" value="page" />
... rest of form ...
<button id="submit-button">Submit</button>
</form>
}
Now, confusion about JQuery and AJAX:
According to https://api.jquery.com/jquery.post/ you must provide an URL.
All properties except for url are optional
Your JQuery AJAX will send a post request to your index.php page. When your page executes as shown above, it will simply print {message: "Your submission was received"} and then die. The JQuery will be waiting for that response and then do whatever you tell it to do with it (in this example, print it to the console).
Update after discussion
<div class="form-group">
<label>Category</label>
<select class="form-control bg-dark btn-dark text-white" id="drpcategory" name="drpcategory" required>
<?php
$category = ''.$dir.'/template/post/category.txt';
$category = file($category, FILE_IGNORE_NEW_LINES);
foreach($category as $category)
{
echo "<option value='".$category."'>$category</option>";
}
?>
</select>
</div>
<!-- HTML to receive AJAX values -->
<div>
<label>Item</label>
<select class="" id="drpitem" name="drpitem"></select>
</div>
<script>
$(function(){
$('#drpcategory').on('change',function() {
$.ajax({
url: '/receive.php',
method: 'post',
data: $(this).serialize(),
success: function(result) {
workWithResponse(result);
}
});
});
});
function workWithResponse(result) {
// jquery automatically converts the json into an object.
// iterate through results and append to the target element
$("#drpitem option").remove();
$.each(result, function(key, value) {
$('#drpitem')
.append($("<option></option>")
.attr("value",key)
.text(value));
});
}
</script>
receive.php:
<?php
// there can be no output before this tag.
if(isset($_POST['drpcategory']))
{
// get your items from drpcategory. I will assume:
$items = array('val1' => 'option1','val2' => 'option2','val3' => 'option3');
// send this as json. you could send it as html, but this is more flexible.
header('Content-Type: application/json');
// convert array to json
$out = json_encode($items);
// simply print the output and die.
die($out);
}
Once you have everything working, you can take the code from receive.php, stick it in the top of index.php, and repoint the ajax call to index.php. Be sure that there is no output possible before this code snippet.
Related
I have a PHP script which Edit and Delete cars on my website. Now I want to make Edit and Delete buttons inside a dropdown, and I did but its adding dropdown just to the first car from the row, since the ID is the same for every dropdown. Now I know how to get the unique ID from every car from PHP but how can I achieve it in JavaScript. I will show you my code.
PHP:
$id = $row["id"];
<div class='dropdown'>
<button onclick='myFunction()' class='dropbtn'>Settings</button>
<div id='myDropdown".$id."'class='dropdown-content'>
".($featured!=1 ? "<a title='Make ".$title." Featured'href='forms/addfeatured.php?id=".$id."'>Make Featured</a>" : "<a title='Remove ".$title."' href='forms/removefeatured.php?id=".$id."'>Remove Featured</a>")."
<a title='Delete ".$title."' href='forms/deletecars.php?id=".$id."'>Delete</a>
</div>
JavaScript:
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
So how can I have different ID in javascript so I can open dropdowns for each entry?
Only use , No need to technically learn AJAX or JSON !
You Just need to use the simple functions which has been prepared for use and has been put in the libraries. And set a few parameters that they need.
The important thing is that, You should know PHP runs on the server machine, not your browser or your PC.
So the PHP variables too.. They are not in your machine to easily put them in a JS variable.
At his point we need to communicate with the server to send them(using AJAX function) in a proper format(using JSON function) for us to use.
So, Your question :
How to add ID from PHP script to JavaScript code?
has the easiest solution just with these functions:
(At your browser page):
$.ajax({ .. some parameters .. });
$(document).ready(function() {
$.ajax({
type: 'post', //Transfer Protocol
url: 'serving.php', //Address of Server Page
dataType: 'json', //Data Structure
data: {action: 'demo'},
success: function(output) {
$variables = output;
}
});
});
and
(At your PHP page on the server)
json_encode(.. some data ..);
$variables = array("Chevy", "BMW", "Ford");
echo json_encode($variables ); // Encoded variable array
Unfortunately your codes and description are not clear for me to help directly in your project.
But I attach a simple practical Example :(in Jquery)
// carSelection.html page
<!DOCTYPE html>
<html lang="en">
<head>
<script
src="https://ajax.googleapis.com/ajax/libs
/jquery/2.1.1/jquery.min.js"> //jquery CDN
</script>
</head>
<body>
<div style="margin:2em">
<form id="myForm">
<select id="selectNumber">
<option>Choose a car</option>
</select>
</form>
</div>
<script>
var $cars = '';
$(document).ready(function() {
$.ajax({
type: 'post',
url: 'carServs.php',
dataType: 'json',
data: {action: 'demo'},
success: function(output) {
$cars = output;
var option = '';
for (var i=0;i<$cars.length;i++){
option += '<option value="'+ $cars[i] +
'">' +
$cars[i] + '</option>';
}
$('#selectNumber').append(option);
}
});
});
</script>
</body>
</html>
And
// carServs.php page
<?php
// ...
$cars = array("Chevy", "BMW", "Ford");
echo json_encode($cars);
//...
?>
just remeber to attach the jquery CDN at your code, In the head section or just before ending the body tag </body>
And if you insist to have it in JavaScript, It's possible just with a few changes in syntax.
I have a problem concerning my code which should change content in a div onclick "More News articles" as the change will happen only once. I see in Chrome Developer mode that it fires every click a request. What goes wrong?
Output.php
<?php
require_once('../pe13f/SSI.php');
require_once ('../PE13/smf_2_api.php');
?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
function MakeRequest(id)
{
$.ajax({
url : 'display.php',
data:{"id":id},
type: 'GET',
success: function(data){
$('#streaminnern').html(data);
}
});
}
</script>
<div id="stream" class="bg4 roundedcrop shadow">
<div class="ph25 pv20">
<h1>News</h1>
<input id="streamcnt" name="streamcnt" type="hidden" value="" />
</div>
<div id="streamadd"></div>
<div id="streaminnern">
<?php
$num_recent = 5;
echo $num_recent;
?>
</div>
<div onclick="MakeRequest(<?php echo $num_recent; ?>);" id="streammore">More News articles</div>
</div>
backend php display.php
<?php
$num_recent = $_GET['id']+5;
echo $num_recent;
?>
Greetings Emil
Check the source that is produced by output.php. You'll find there onclick="MakeRequest(5);". Basically - on every click you call MakeRequest(5) which always fires call display.php?id=5 (you probably see that in your dev console).
Try something like this:
<script>
var lastId = 0; // var that stores last fetched ID
function MakeRequest(id)
{
if(!lastId) // if there is no last ID use the one from initial onclick
lastId = id;
$.ajax({
url : 'display.php',
data:{"id":lastId}, // note that we are using the lastId var
type: 'GET',
success: function(data){
$('#streaminnern').html(data);
lastId = data; // save fetched ID in our global var
}
});
}
</script>
The request is always the same. Suppose $num_recent is initially set to 5.
Then as per your code MakeRequest(5) will be executed. And your ajax call updates a div with class streaminnern. So the new id has no impact on the next ajax call. For the ajax request to be sent updated value you may set
$.ajax({
url : 'display.php',
data:{"id":$('#streaminnern').html()},
.................
});
I have a class which returns a set of data from the database. The class is called by ajax and the results need to be returned back to the index.php so that I can format and display the results in a table format.
Problem: I'm unable to return the results throug ajax and back to a php variable.
Any help you can provide would be greatly appreciated.
<php
class Questions
{ public function displayQuestions()
{
return $this->questionArray;
} // contains set of data from db
}
?>
Return the dataset from the class and pass it to the $var so that I can format the data for display
index.php:
<html>
<body>
<div id="questiondev" ><?php $var[] = returned by ajax ?> </div>
<div id="questionButton">
<form method="POST" name="form_questions" action="">
<TEXTAREA NAME="saveqa" id="saveqa"></TEXTAREA>
<BUTTON class="btn_save" id ="btn_save" NAME="btn_save">Ask</BUTTON>
</form>
</div>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function() {
$('#btn_save').on('click', function() {
$.ajax({
type: "POST",
cache: false,
url: "testData.php",
dataType: "json",
success:function(info){
$('#questiondev').html(info[0]);
console.log(" reponse :"+ info);
}
});
});
$('#btn_save').trigger("click");
});
</script>
</body>
</html>
add
data:$("form").serialize(), U need to serialize the form
<div id="questionButton">
<form method="POST" name="form_questions" action="">
<TEXTAREA NAME="saveqa" id="saveqa"></TEXTAREA>
<BUTTON class="btn_save" id ="btn_save" NAME="btn_save">Ask</BUTTON>
</form>
</div>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function() {
$('#btn_save').on('click', function() {
$.ajax({
type: "POST",
cache: false,
url: "testData.php",
data:$("form").serialize(),
dataType: "json",
success:function(info){
$('#questiondev').html(info[0]);
console.log(" reponse :"+ info);
}
});
});
$('#btn_save').trigger("click");
});
</script>
</body>
</html>
It doesn't look like you're echoing your results in json format. It appears that if your query is successful, $questionArray gets set, but is not echoed. Plus you can't just echo $questionArray - it must be output in json format for the Ajax code to accept it.
Try this - after $questionArray is set:
$encodedJSON = json_encode($questionArray);
echo $encodedJSON;
you can't insert result of AJAX request into PHP variable like this. When you run php page web server willl render it, and then javascript is run by browser, which means, that you can't edit PHP variables from javascript, because PHP runs on server and JS runs on client.
Why do you want to do this? Maybe it is flaw in app design, give more information and maybe we can help you more so you won't need to do this. If you want to format data, then format them before you send them back to AJAX :)
I am using php/ajax to submit a form without page refresh. Here are my files-
coupon.js
jQuery(document).ready(function(){
jQuery(".appnitro").submit( function(e) {
$.ajax({
url : "http://174.132.194.155/~kunal17/devbuzzr/wp-content/themes/street/sms.php",
type : "post",
dataType: "json",
data : $(this).serialize(),
success : function( data ) {
for(var id in data) {
jQuery('#' + id).html( data[id] );
}
}
});
//return false or
e.preventDefault();
});
});
sms.php
<?php
//process form
$res = "Message successfully delivered";
$arr = array( 'mess' => $res );
echo json_encode( $arr );//end sms processing
unset ($_POST);
?>
and here is code for my html page -
<form id="smsform" class="appnitro" action="http://174.132.194.155/~kunal17/devbuzzr/wp-content/themes/street/sms.php" method="post">
...
</form>
<div id="mess" style="background:green;"></div>
Now when i click on submit button nothing happens and firebug shows following under console panel -
POST http://174.132.194.155/~kunal17/devbuzzr/wp-content/themes/street/sms.php
404 Not Found 1.29s `jquery.min.js (line 130)`
Response
Firebug needs to POST to the server to get this information for url:
http://174.132.194.155/~kunal17/devbuzzr/wp-content/themes/street/sms.php
This second POST can interfere with some sites. If you want to send the POST again, open a new tab in Firefox, use URL 'about:config', set boolean value 'extensions.firebug.allowDoublePost' to true
This value is reset every time you restart Firefox This problem will disappear when https://bugzilla.mozilla.org/show_bug.cgi?id=430155 is shipped
When i set 'extensions.firebug.allowDoublePost' to true then following results show up -
POST http://174.132.194.155/~kunal17/devbuzzr/wp-content/themes/street/sms.php
404 Not Found 1.29s `jquery.min.js (line 130)`
Response -
{"mess":"Message successfully delivered"}
CaN anyone help me in fixing this firebug error of 404 not found. And why is it showing jquery.min.js (line 130) along side?
P.S -do not worry about http://174.132.194.155/~kunal17/devbuzzr/wp-content/themes/street this is my base url
You may want to try putting the e.preventDefault() statement before the $.ajax call.
EDIT:
My x.html, corresponds to your HTML page
<!DOCTYPE html>
<html>
<head>
<title>x</title>
<script
type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
</script>
<script type="text/javascript" src="/so/x.js"></script>
</head>
<body>
<form id="smsform" class="appnitro" action="/so/x.php">
<input type="text" name="zz">
<input type="submit">
</form>
<div id="mess" style="background:green;"></div>
</body>
</html>
My x.js, corresponds to your coupon.js
jQuery(document).ready(function(){
jQuery(".appnitro").submit( function(e) {
e.preventDefault();
$.ajax({
url : "/so/x.php",
type : "post",
dataType: "json",
data : $(this).serialize(),
success : function( data ) {
for(var id in data) {
jQuery('#' + id).html( data[id] );
}
}
});
//return false or
//e.preventDefault();
});
});
My x.php, corresponds to your sms.php
<?php
$res = "Message successfully delivered.";
$arr = array('mess'=>$res);
echo json_encode($arr);
unset($_POST);
?>
This actually works in my environment, although I do not have the rest of the HTML markup or the additional PHP form processing code. The "Message successfully delivered." shows up in green directly below the input field.
When inside the Ajax call this refers to the Ajax object you need to do this
var __this = this;
Before going into the Ajax call, then it would be
data : __this.serialize()
Or look up the use of context within an Ajax call in Google. Or serialise your data into a variable before going into the Ajax call.
I have been trying to create a simple calculator. Using PHP I managed to get the values from input fields and jump menus from the POST, but of course the form refreshes upon submit.
Using Javascript i tried using
function changeText(){
document.getElementById('result').innerHTML = '<?php echo "$result";?>'
but this would keep giving an answer of "0" after clicking the button because it could not get values from POST as the form had not been submitted.
So I am trying to work out either the Easiest Way to do it via ajax or something similar
or to get the selected values on the jump menu's with JavaScript.
I have read some of the ajax examples online but they are quite confusing (not familiar with the language)
Use jQuery + JSON combination to submit a form something like this:
test.php:
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript" src="jsFile.js"></script>
<form action='_test.php' method='post' class='ajaxform'>
<input type='text' name='txt' value='Test Text'>
<input type='submit' value='submit'>
</form>
<div id='testDiv'>Result comes here..</div>
_test.php:
<?php
$arr = array( 'testDiv' => $_POST['txt'] );
echo json_encode( $arr );
?>
jsFile.js
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 ) {
for(var id in data) {
jQuery('#' + id).html( data[id] );
}
}
});
return false;
});
});
The best way to do this is with Ajax and jQuery
after you have include your jQuery library in your head, use something like the following
$('#someForm').submit(function(){
var form = $(this);
var serialized = form.serialize();
$.post('ajax/register.php',{payload:serialized},function(response){
//response is the result from the server.
if(response)
{
//Place the response after the form and remove the form.
form.after(response).remove();
}
});
//Return false to prevent the page from changing.
return false;
});
Your php would be like so.
<?php
if($_POST)
{
/*
Process data...
*/
if($registration_ok)
{
echo '<div class="success">Thankyou</a>';
die();
}
}
?>
I use a new window. On saving I open a new window which handles the saving and closes onload.
window.open('save.php?value=' + document.editor.edit1.value, 'Saving...','status,width=200,height=200');
The php file would contain a bodytag with onload="window.close();" and before that, the PHP script to save the contents of my editor.
Its probably not very secure, but its simple as you requested. The editor gets to keep its undo-information etc.