I know that there are so many to find on the internet, however, I have been trying this for hours now, and still not working, Maybe the community could help me out:)
http://jsfiddle.net/dkk2nqyg/14/
I've got a little explanation in the jsfiddle, else, you can take a look in my previous question, JavaScript array splice
Basicly, I want the values from selected ( 3 picked up cards )
in php, because I want to mail those values;)
$.ajax({
url: 'data.php', //I actually want it to be on same page, trying this for debugging
type: 'post',
data: {data : selected},
success: function(data) {
alert("worked");
}
});
in the data.php :
<?php
$data = json_decode(stripslashes($_POST['data']));
foreach($data as $d){
echo $d;
}
?>
I would like that I don't even need that data.php but just 1 page, so in the index.php, is that even possible?
Edit: Please, link a JsFiddle, would really help!
First the ajax request should be within the click handler
$('#mail').click(function () {
console.log($('#dvDest .flipper').get())
var selected = $('#dvDest .flipper').map(function () {
return $(this).data('src')
}).get();
alert(selected)
$.ajax({
url: 'data.php', //I actually want it to be on same page, trying this for debugging
type: 'post',
data: {
data: selected
},
success: function (data) {
alert("worked");
}
});
})
then in server side loop through the array like(Not sure about the PHP syntax)
<?php
foreach($_POST['data'] as $d){
echo $d;
}
?>
you can write a condition as if request object have post values then
$data = json_decode(stripslashes($_POST['data']));
foreach($data as $d){
echo $d;
}
else your homepage display code
So,index.php is enough
For using a single page, eg: index.php
at the top of index.php you do:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Your code goes here
exit();
}
Related
here is my simple code
$.ajax({
url:'action.php',
method: 'POST',
data:{getcart:1},
success:function(response){
$('#getcart').html(response);//want to display $return_value (from action page)
$('#getcart2').html(response);//want to display $return_value2 (from action page)
}
});
Here i am sending request to action.php
and if in action.php i have echo two variables separately for example.
$return_value = " //Some html here "; echo $return_value;
$return_value2= "//some other html"; echo $return_value2;
So the question is in ajax i have function with argument response . how i will be able to receive these both variables from php and display it in different divs.
i hope you guys help me. thanks.
Send the responses as JSON.
In PHP
$return = array( $return_value, $return_value2 );
echo json_encode($return);
In Javascript
var response = JSON.parse(response);
$("#getcart").html(response[0]);
$("#getcart2").html(response[1]);
your could return a json from action
echo json_encode(array('cart' => $return_value, 'cart2' => $return_value2));
then in your js,
$.ajax({
url:'action.php',
method: 'POST',
data:{getcart:1},
dataType: 'json',
success:function(response){
$('#getcart').html(response.cart1);//want to display $return_value (from action page)
$('#getcart2').html(response.cart2);//want to display $return_value2 (from action page)
}
});
You need to use json_encode in order to get multiple records or data.
action.php
<?php
header('Content-Type: application/json');
$array = array(
'var1'=> 'var value 1',
'var2'=> 'var value 2'
// more variables to go
);
echo json_encode($array);
?>
and then read your variables in JS
dataType: 'json',
success:function(response){
console.log(response.var1);
console.log(response.var2);
$('#getcart').html(response.var1);
$('#getcart2').html(response.var2);
}
You can use json_encode to create an object like:
$array = [
"return_value" => " //Some html here ",
"return_value2" => "//some other html",
];
echo json_encode($array)
Then add dataType: 'json' to your ajax options. The response then will be an object like:
{
"return_value" => " //Some html here ",
"return_value2" => "//some other html",
}
Where you can access the specific values with e.g. response.return_value2 and thus separate them.
I can't seem to get AJAX POST or GET working with my CAKEPHP site. I am trying to create autocomplete but can't seem to submit or fetch the data using ajax. I can get auto complete working using tags but I cannot display the data from my table. I am not sure what is going wrong if i'm not using the right url or some other problem.
Here is my search.ctp
<?php use Cake\Routing\Router; ?>
<?php echo $this->Form->input('id', ['type' => 'text']); ?>
<script>
$.ajax({
type: "POST",
url: "<?php echo Router::url(array('controller' => 'Invoices', 'action' => 'search')); ?>",
success: function(response) {
$("#id").autocomplete({ source: response });
}
});
</script>
Here is my search function in my InvoicesController.
public function search()
{
$this->loadComponent('RequestHandler');
if ($this->request->is('ajax'))
{
$name = $this->request->query['term'];
$resultArr = $this->Invoices
->find()
->where(
['Invoices.id LIKE' => ($name . '%')],
['Invoices.id' => 'string']
);
$resultsArr = [];
foreach ($resultArr as $result)
{
$resultsArr[] = (strval($result['id']));
}
$this->set('resultsArr', $resultsArr);
// This line is what handles converting your array into json
// To get this to work you must load the request handler
$this->set('_serialize', ['resultsArr']);
}
}
This is the error that is produced when I try to type in an ID.
This is what i want to produce which I have been able to do by using an array in search.ctp
and here is my table I am trying to fetch the IDs from.
There are two methods.
$this->request->query('term');
$_REQUEST['term'];
I have a function in a compare.php that takes a parameter $data and uses that data to find certain things from web and extracts data and returns an array.
function populateTableA($data);
So to fill array I do this
$arrayTableA = populateTableA($name);
now this array is then used to iterate tables..
<table id="tableA">
<input type="text" name="search"/><input type="submit"/>
<?php foreach($arrayTableA as $row) { ?>
<tr>
<td><?php echo $row['name']?></td>
<td><?php echo $row['place']?></td>
</tr>
</table>
Now what I want to do is to enter some data on input and then through jquery ajax
function populateTableA($data);
should be called and $array should be refilled with new contents and then populated on tableA without refreshing the page.
I wrote this jquery but no results.
$(document).on('submit',function(e) {
e.preventDefault(); // Add it here
$.ajax({ url: 'compare.php',
var name = ('search').val();
data: {action: 'populateTableA(name)'},
type: 'post',
success: function(output) {
$array = output;
}
});
});
I have been doing web scraping and the above was to understand how to implement that strategy... original function in my php file is below
function homeshoppingExtractor($homeshoppingSearch)
{
$homeshoppinghtml = file_get_contents('https://homeshopping.pk/search.php?category%5B%5D=&search_query='.$homeshoppingSearch);
$homeshoppingDoc = new DOMDocument();
libxml_use_internal_errors(TRUE);
if(!empty($homeshoppinghtml)){
$homeshoppingDoc->loadHTML($homeshoppinghtml);
libxml_clear_errors();
$homeshoppingXPath = new DOMXPath($homeshoppingDoc);
//HomeShopping
$hsrow = $homeshoppingXPath->query('//a[#class=""]');
$hsrow2 = $homeshoppingXPath->query('//a[#class="price"]');
$hsrow3 = $homeshoppingXPath->query('(//a[#class="price"])//#href');
$hsrow4 = $homeshoppingXPath->query('(//img[#class="img-responsive imgcent"])//#src');
//HomeShopping
if($hsrow->length > 0){
$rowarray = array();
foreach($hsrow as $row){
$rowarray[]= $row->nodeValue;
// echo $row->nodeValue . "<br/>";
}
}
if($hsrow2->length > 0){
$row2array = array();
foreach($hsrow2 as $row2){
$row2array[]=$row2->nodeValue;
// echo $row2->nodeValue . "<br/>";
}
}
if($hsrow3->length > 0){
$row3array = array();
foreach($hsrow3 as $row3){
$row3array[]=$row3->nodeValue;
//echo $row3->nodeValue . "<br/>";
}
}
if($hsrow4->length > 0){
$row4array = array();
foreach($hsrow4 as $row4){
$row4array[]=$row4->nodeValue;
//echo $row3->nodeValue . "<br/>";
}
}
$hschecker = count($rowarray);
if($hschecker != 0) {
$homeshopping = array();
for($i=0; $i < count($rowarray); $i++){
$homeshopping[$i] = [
'name'=>$rowarray[$i],
'price'=>$row2array[$i],
'link'=>$row3array[$i],
'image'=>$row4array[$i]
];
}
}
else{
echo "no result found at homeshopping";
}
}
return $homeshopping;
}
As mentioned in the comments PHP is a server side language so you will be unable to run your PHP function from javascript.
However if you want to update tableA (without refreshing the whole page) you could create a new PHP page that will only create tableA and nothing else. Then you could use this ajax call (or something similar) -
$(document).on('submit','#formReviews',function(e) {
e.preventDefault();
$.ajax({
url: 'getTableA.php', //or whatever you choose to call your new page
data: {
name: $('search').val()
},
type: 'post',
success: function(output) {
$('#tableA').replaceWith(output); //replace "tableA" with the id of the table
},
error: function() {
//report that an error occurred
}
});
});
Hi You are doing it in wrong way.You must change your response to html table and overwrite older one.
success: function(output) {
$("#tableA").html(output);
}
});
In your ajax page create a table with your result array
You are in a very wrong direction my friend.
First of all there are some syntax error in your JS code.
So use JavaScript Debugging
to find where you went wrong.
After that Basic PHP with AJAX
to get a reference how ajax and PHP work together
Then at your code
Create a PHP file where you have to print the table part which you want to refresh.
Write an AJAX which will hit that PHP file and get the table structure from the server. So all the processing of data will be done by server AJAX is only used for request for the data and get the response from the server.
Put the result in your html code using JS.
Hope this will help
I am trying to implement a timer. I learned this idea from a SO post.
<?php
if(($_SERVER['REQUEST_METHOD'] === 'POST') && !empty($_POST['username']))
{
//secondsDiff is declared here
$remainingDay = floor($secondsDiff/60/60/24);
}
?>
This is my php code. My php,html and JS codes are in the same page. I have a button in my html. When a user clicks on the html page, It will call a Ajax function
//url:"onlinetest.php",
//dataType: 'json',
beforeSend: function()
{
$(".startMyTest").off('click');
setCountDown();
}
It will call setCountDown() method, which contains a line at the very beginning
var days = <?php echo $remainingDay; ?>;
When i run the page, it says[even before clicking the button] "expected expression, got '<'" in the above line. My doubt is
Why this php variable get replaced before i am triggering the button. Please let me know hoe to solve this or how to change my idea.
The problem is, since initial load, $_POST values aren't populated (empty on first load),
That variable you set is undefined, just make sure you initialize that variable fist.
<?php
// initialize
$remainingDay = 1;
if(($_SERVER['REQUEST_METHOD'] === 'POST') && !empty($_POST['username']))
{
//secondsDiff is declared here
$remainingDay = floor($secondsDiff/60/60/24);
echo json_encode(array('remaining_day' => $remainingDay);
exit;
}
?>
<script>
var days = <?php echo $remainingDay; ?>;
$('.your_button').on('click', function(){
$.ajax({
url: 'something.php',
dataType: 'JSON',
type: 'POST',
beforeSend: function() {
// whatever processes you need
},
success: function(response) {
alert(response.remaining_day);
}
});
});
</script>
That is just the basic idea, I just added other codes for that particular example, just add/change the rest of your logic thats needed on your side.
You can pass a php variable into JS code like
var jsvariable ="<?php echo $phpvariable ?>";
NOTE:
If you ever wanted to pass a php's json_encoded value to JS, you can do
var jsonVariable = <?php echo $json_encoded_value ?>; //Note that there is no need for quotes here
Try this,
var days = "<?php echo $remainingDay; ?>";
I finally could receive a response from my AJAX PHP call.
But now in return I get my full HTML site instead of a JSON object or string.
What is wrong here?
var request = $.ajax({
url: "mysite.php",
type: "POST",
data: {select:requestStr},
dataType: "html"
});
request.done(function( data ) {
console.log(JSON.stringify(data));
});
I send a simple string to my php class. This is what I get from the response-text in my developer tool from the browser:
data=Test
On PHP site I just return that respone:
<?php
$myData = array();
$myData['data'] = "test";
if (isset($_POST)) {
$myData['data'] = $_POST;
}
echo json_encode($myData);
exit();
?>
And this is the console.log from the response:
"<!DOCTYPE html>\r\n<html>\r\n<head> ... </html>\"Test\""
EDIT
I only need the end of the response and that is "Test" but not the whole HTML file.
UPDATE
I extracted my PHP class and wrote a Little Version like the PHP code above.
But now my response is an empty object {"data":[]}
Hey put type="Json" instead of the "text"
Put a exit(); after echo json_encode($myData);