pass jquery value to php variable - php

Am a noob so hope you can help!
I've got the following jquery code:
$("#single-home-container").html(post_id);
It then displays the value I want within the HTML on the page:
<div id="single-home-container"></div>
What I would like is to pass the value into a PHP variable to I can use the info in a MySQL query.
How do I do so? It's in WordPress so no separate files
Thanks

You can use jQuery.post() or jQuery.ajax().
Here some examples:
<script>
$.post("test.php", { "func": "getNameAndTime" },
function(data){
console.log(data.name); // John
console.log(data.time); // 2pm
}, "json");
</script>
<script>
$.ajax({
url: "test.html",
context: document.body,
success: function(){
$(this).addClass("done");
}
});
</script>

You'd need to use ajax. Something like this:
JQuery:
$('.locationID').click(function(){
var post_id = $(this).attr('rel'),
$container = $("#single-home-container");
old_html = $container.html();
$container.html('loading...');
$.ajax({
url : '/path/to/php/file.php',
data:{"post_id":post_id},
type: 'post',
dataType: 'json',
success: function(data){
$container.html(data.postBody);
},
error: function(data){
// possibly notify the user of the error
$container.html(old_html);
}
});
});
That assumes you have a field in your posts table called postBody
PHP
<?php
header('Content-type: application/json');
// $query_result = do mysql query with $_POST['post_id']
echo json_encode($query_result);
exit();
?>
That assumes that you want all the fields and you're returning all the fields, including postBody - and of course you have PHP 5.2.6+ or whatever version they added json_encode().

Related

php array into JS variables with AJAX

i have a php array:
$Array= array ($eventRow['title'], $eventRow['start_date'], $eventRow['start_time'], $eventRow['end_date'], $eventRow['end_time'], $eventRow['description'], $eventRow['address']);
i am exeucing an ajax script with a html button, and i would like to get these variable's values as the following:
(document).ready(function() {
//##### send add record Ajax request to outlookimport.php #########
$(".exportOutlook").click(function() {
/*var myData = {
title:
startDate:
startTime:
endDate:
endTime:
description:
address:
username:
};*/
...
any idea how to get the values in the JS file when processing the ajax query?
after this, a php file as called by the ajax, when i would like to get the variable as the following:
$title = $_POST['title'];
$startDate = $_POST['startDate'];
...
...
any idea would be appreciated
In jQuery, it's:
$.post('outlookimport.php', myData, function (returnedData) {
//Do something
});
By including myData as the second parameter, its values will be posted to the PHP script.
Use json_encode($Array) and read the JSON response in your ajax request on success.
$.ajax({
type: 'POST',
url: 'outlookimport.php',
data: myData,
success: function(response){
console.log(response);
}
});

calling a php function using ajax after interval of time

hi i am working on a codeigniter project. I want to execute a php function after an interval of 10seconds. When a user visits that specific page after 10 seconds i want that php function to be executed. In that php function i have set a counter which adds 1 to the specific table into the database. I have tried using AJAX but didnt get the desired result. Kindly explain me with examples as i am new in ajax. Thanks in advance...
#Majid Golshadi s answer is the right answer.
Working version is here
Please in view that is loaded all the time (like header_view.php)
add this few lines
<script type="text/javascript">
var _baseUrl = "<?= base_url() ?>";
</script>
This makes that your base_url is usable in JavaScript anywhere in page (but make sure to have it somewhere on "TOP" of page)
and literraly use #Majid Golshadi s answer in this way
$(document).ready(function() {
setTimeout(function() {
$.ajax({
url: _baseUrl + "/your/controller/param",
type: 'post',
data: {"token": "your_token"}, });
}, 10000);
});
using jquery this will be the easiest and fastest way to do that
`//setting timeout to 3 seconds = 3 thousand milli seconds
setInterval(function(){
//ajax call
$.ajax({
url: _baseUrl + "/controller_name/function_name/", //the url where you want to fetch the data
type: 'post', //type of request POST or GET
data: {"data": "value"}, }); //data passed to controller
},3000);`
in your controller you may use
function function_name(){
$var = $this->input->post();//getting data passed from ajax
//process here...
echo json_encode($var)//parses and returns the processed value
}
try this
setTimeout(function(){
$.ajax({
url: "<?php echo base_url('your/controller/address');?>",
type: 'post',
data: {"token": "your_token"},
});
}, 10000);
Example
in your view
$(document).ready(function(){
setTimeout(function(){
$.ajax({
url: "<?php echo base_url('MyController/Mymethod');?>",
type: 'post',
data: {"token": "12majid18"},
});
}, 10000);
});
and in Your Controller write method like this
public function Mymethod()
{
$token = $this->input->post('token');
if ( $token == '12majid18' )
{
/*call your model and insert your data in Table*/
}
}
you can try this:
window.jQuery(function(){
var y=setInterval(function() {
window.jQuery.post(url,{"token": "your_token"},function(res){
alert(res);
});
}, 10000);
});

How to use ajax to pass a variable to a php file using POST method?

I have modified the code
to POST prodID to ProductsList.php
// its a dynamically generated drop menu
while($rowmnu2=mysql_fetch_assoc($resulmnusub2))
{
echo '<li><a id="'.$rowmnu2['liid'].'" href="#" onclick="passto(this.id)">'.$rowmnu2['title'].'</a></li>
';
}
and here is my ajax function :
function passto(val){
//window.location.href="ProductsList.php?idd=" + val;
$.ajax({
url: 'ProductsList.php',
type: "POST",
data: ({prodID: val}),
success: function(data){
//or if the data is JSON
window.location.href="ProductsList.php";
}
});
}
the passed element to the function is an integer
in the ProductsList.php I have
<?php
if(!$_POST['prodID']) die("There is no such product!");
echo $_POST['prodID'];
?>
and I get There is no such product! while there should be an INT #
why is that ?
any one knows? all the bellow suggestions are not responding correctly
$(document).ready(function() {
$("a").click(function(event) {
myid = $(this).attr('id');
$.ajax({
type: "POST",
url: "ProductsList.php",
data: {prodID: myid},
dataType: "json",
complete:function(){
window.location("ProductsList.php");
}
});
});
});
if you want to POST id , you can change:
...onclick="passto(this)"...
to
...onclick="passto(this.id)"...
That behavior is normal because you are requesting ProductsList.php twice. the first time with an AJAX request using $.ajax. for that time the id is sent correctly. The problem is that you request ProductsList.php again just after AJAX complete using window.location.href="ProductsList.php"; without sending anything. So the result is as expected, a page printing There is no such product!
You can fix the problem by replacing window.location.href="ProductsList.php"; by this one :
$('body').html(data);
or any other instruction to use properly the returned data.
You can either use my edited code or just edit yours :
echo '<li ><a id="'.$rowmnu2['link'].'" href="#">'.$rowmnu2['title'].'</a></li>';
JS part :
$('a').click(function() {
var val = $( this ).attr('id');
$.ajax({
type: "POST",
url: "ProductsList.php",
data: {prodID:val},
complete:function(){
$('body').html(data);
}
});
});

Execute php script with JS [duplicate]

Is it possibe to simply load a php script with a url with js?
$(function() {
$('form').submit(function(e) {
e.preventDefault();
var title = $('#title:input').val();
var urlsStr = $("#links").val();
var urls = urlsStr.match(/\bhttps?:\/\/[^\s]+/gi);
var formData = {
"title": title,
"urls": urls
}
var jsonForm = JSON.stringify(formData);
$.ajax({
type: 'GET',
cache: false,
data: { jsonForm : jsonForm },
url: 'publishlinks/publish'
})
//load php script
});
});
Edit:
function index() {
$this->load->model('NewsFeed_model');
$data['queryMovies'] = $this->NewsFeed_model->getPublications();
$this->load->view('news_feed_view', $data);
}
simple
jQuery and:
<script>
$.get('myPHP.php', function(data) {});
</script>
Later edit:
for form use serialize:
<script>
$.post("myPHP.php", $("#myFormID").serialize());
</script>
like this ?
$.get('myPHP.php', function(data) {
$('.result').html(data);
alert('Load was performed.');
});
There are various ways to execute a server side page using jQuery. Every method has its own configuration and at the minimum you have to specify the url which you want to request.
$.ajax
$.ajax({
type: "Get",//Since you just have to request the page
url:"test.php",
data: {},//In case you want to provide the data along with the request
success: function(data){},//If you want to do something after the request is successfull
failure: function(){}, //If you want to do something if the request fails
});
$.get
$.get("test.php");//Simplest one if you just dont care whether the call went through or not
$.post
var data = {};
$.post("test.php", data, function(data){});
You can get the form data as a json object as below
var data = $("formSelector").searialize();//This you can pass along with your request

send php variables to php file using jquery ajax?

i want to send a php variable $thread_id to php file using jquery ajax, so the php file can get all posts for $thread_id and echo it back to main file.
it doesnt work when i type:
$.get("ajaxcall_reply.php", thread_id: $thread_id, function(data) {
$("#threads").html(data);
});
how should i type?
Do you know what $thread_id is outputting? Try putting it into a variable of its own and looking at the output before putting it in the get function. It might have symbols or things that are messing up your javascript syntax. Do you have an example output? Additionally the get method returns the XMLHttpRequest object (data) so you might want to look into setting the type of data to be returned to callback function: "xml", "html", "script", "json", "jsonp", or "text".
Try this:
$.get("ajaxcall_reply.php", {thread_id: $thread_id}, function(data) { $("#threads").html(data); });
<script>
$.get(url, { get_var: '<?php echo $phpvar ?>' }, function(data) { alert(data); });
</script>
at the URL:
<?php
echo $_GET['get_var'];
?>

Categories