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
Related
Is it possible to get data php with Ajax without display them ? Simply stock data in JS variable?
I need this data to manipulate dates but no show it.
When I tried to simply return data without echo, etc. Data ajax in JS is empty
Ps : sorry my English is bad
try it this way
File *.php
<?php
$var_1 = null;
$var_2 = null;
/** ... */
$response = new stdClass;
$response->var_1 = $var_1;
$response->var_2 = $var_2;
echo json_encode($response);
?>
File *.html or *.js
<script>
var state = {};
$.ajax({
url: 'getData.php',
type: 'post',
dataType: 'json',
success: function (response) {
console.warn(response);
state = response;
}
});
</script>
Assuming you are trying to pass data from a PHP file to HTML/JS where it happens that your PHP file is also included in the HTML that's why it's displaying the echo (if I understood correctly!)
Using AJAX PHP example from w3school.
HTML sample file:
<?php include "PHP_SAMPLE_FILE.php" ?>
<header>
<meta name="temp_files" content="<?= htmlspecialchars($jsonData) ?>">
<!-- The rest of HTML content -->
JS sample file:
if (str.length == 0) {
// do something if there was nothing entered
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if (this.responseText.includes('{')){
result = JSON.parse(this.responseText);
// do something if response is JSON
} else {
// do something if response is null
}
}
}
xmlhttp.open("GET", "PHP_SAMPLE_FILE.php?q="+str, true);
xmlhttp.send();
}
PHP sample file:
$q = $_REQUEST["q"] ?? $_POST["q"] ?? "";
$sql = "GET SOMETHING FROM DATABASE";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$json[] = $row;
}
}
$jsonData = json_encode($json ?? null);
if($q != ""){
echo $jsonData;
}
What happens exactly is that once the page loads initially it won't display the output of the PHP query as we have surrounded the echo with an if statement that requires to have query value (q) to search and it shouldn't be empty (""). Of course, assuming that once the page is loaded the data is shared with the client-side through defined PHP variables using various approaches, using a meta tag in the header for instance.
Once the data is received from the PHP file through echo, we use the JSON.parse function to parse it as in this scenario JS receives it as a string.
Hope that helped :)!
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 am trying to fetch JavaScript variable "i" in my PHP Code within a JavaScript function in the below code, I find problem in retrieving records, either first record or the last record repeats instead of all records in database.. can you guys help me out ?
Thanks
<?php
$query21 = $mysqli->query("SELECT * FROM register");
$nr = mysqli_num_rows($query21);
while ($row = mysqli_fetch_assoc($query21)) {
$results[] = $row;
}
?>
<script language="javascript" type="text/javascript">
var intervalID = 0;
var time = 10;
MsgPop.displaySmall = true;
MsgPop.position = "bottom-right";
$(document).ready(function(){
var test = MsgPop.open({
Type: "success",
AutoClose: true,
Content: "Welcome to MsgPop!"});
MsgPop.live();
});
function showMessages(){
var n = '<?php
echo $nr;
?>';
var i = 0;
while (i < n){
var name = '<?php
echo $results[i]['name'];
?>';
MsgPop.open({
Type: "success",
Content: name,
AutoClose: false});
i++;
}
</script>
First you have to create a php file which return same array. File contain
$query21 = $mysqli->query("SELECT * FROM register");
$nr = mysqli_num_rows($query21);
while ($row = mysqli_fetch_assoc($query21)) {
$results[] = $row;
}
echo json_encode($results);
exit;
Now you have to call this file using ajax from your javascript code.
$.ajax({
type: "POST",
url: "sql.php", //your file url
})
.done(function (data) {
//you get your array data(json format)
});
now you get that array in ajax response in json format and you can do anything with this data.
Impossible: PHP is a server side language that runs only at server. but javascript is a client side script it only run at your browser only. Php only gives response depends on your requests. The roll of php is end at server. But the javascript work with your response only, that is javascript can work at browser only.
You could try using AJAX, or else it isn't happening. Like said PHP is server-side only... Good luck!
PHP cannot fetch javascript variables. You should try another strategy.
At the server side (PHP), try to store $resuts in a javascript variable.
var results = '<?php echo json_encode($results); ?>';
Then at the browser side, try to access the data with javascript functions.
var name = results[i]['name'];
I have a table in which the details are fetched from the DB.
if(mysql_num_rows($sql) > 0)
{
$row_count_n=1;
while($rows=mysql_fetch_assoc($sql))
{
extract($rows);
$options1 = select_data_as_options("project_resources", "name", $resource_allocated);
$options2 = select_data_as_options("project_roles", "name", $role);
echo "<tr>";
echo "<td><select name='ra_$row_count_n'><option value=''>-- Select --$options1</option></select></td>";
echo "<td><select name='role_$row_count_n'><option value=''>-- Select --$options2</option></select></td>";
echo "<td><input type='text' name='start_date_tentative_$row_count_n' class='date_one' value=$tentatively_starts_on /></td>";
echo "</tr>";
$row_count_n++;
}
}
I wanted to update the table when required, am doing this using Ajax by collecting data from the form using Jquery and saving it on button click.
$("#save_changes_id").click(function()
{
// To retrieve the current TAB and assign it to a variable ...
var curTab = $('.ui-tabs-active'); // in NEWER jQueryUI, this is now ui-tabs-active
var curTabPanelId = curTab.find("a").attr("href");
if(curTabPanelId == "#tab_dia")
{
var curTab = $('#sub_tabs .ui-tabs-active');
var curTabPanelId = curTab.find("a").attr("href");
}
responseData = doAjaxCall($(curTabPanelId + " form"));
if(responseData == 1)
showMessage('status_msg', 'Project details updated successfully', 'green');
else
showMessage('status_msg', 'Error: Please check all the fields', 'red');
});
function doAjaxCall(objForm)
{
var values = objForm.serialize();
$.ajax({
url: ajaxURL,
type: "post",
data: values,
async: false,
success: function(data)
{
responseData = data;
},
error:function()
{
alert('Connection error. Please contact administrator. Thanks.');
}
});
return responseData;
}
Ajax code is as below:
case "allocate_ba_details":
for($i=1; $i<=$row_count; $i++)
{
$resource = $_REQUEST["ra_$i"];
$role = $_REQUEST["role_$i"];
$start_date_tentative = $_REQUEST["start_date_tentative_$i"];
$already_available_check = mysql_num_rows(mysql_query("select * from project_allocate_ba where project_id = $pdid"));
if($already_available_check > 0)
{
$sql = ("UPDATE project_allocate_ba SET resource_allocated='$resource', role='$role', tentatively_starts_on='$start_date_tentative' WHERE project_id=$pdid");
}
}
echo $sql;
break;
As I am new to this am not sure how to pass the row name in order to update a particular row.
Please suggest a solution. Thanks in advance.
firstly use PDO or some php framework that has nice API to work with mysql. Second don't use success/error callback in jquery is too deprecated. Instanted use done/fail.always.
I understand that you want update row in html table data from the server ?
In success callback simply update the table using jquery text method for jquery object. You don't paste all code so i write example:
in server.php
<?php
[...]
$already_available_check = mysql_num_rows(mysql_query("select * from project_allocate_ba where project_id =" . intval($pdid)));
[...]
echo $already_available_check;
?>
This code return the integer, so in doAjaxCall:
function doAjaxCall(objForm)
{
var values = objForm.serialize();
$.ajax({
url: ajaxURL,
type: "post",
data: values,
async: false,
success: function(data)
{
if(typeof data !== 'undefined' && $.isNumeric(data)) {//check that server send correct anserw
$('whereIsData').text(data);
}
},
error:function()
{
alert('Connection error. Please contact administrator. Thanks.');
}
});
}
Now in success method you populate some DOM element using text method. You cannot simply return data from ajaxCall method because $.ajax is asynchronized method and responseData has value only when ajax request ends, so always return undefined in you example. You must present responseData to the user in success callback method.
For one thing...
$sql = ("UPDATE project_allocate_ba SET resource_allocated='$resource', role='$role', tentatively_starts_on='$start_date_tentative' WHERE project_id=$pdid")
needs single quotes around $pdid
Also don't echo the $sql. Instead do your inspection and form a response.
$response = array();
if(EVERYTHING_IS_GOOD){
$response['status'] = 'good to go';
}else{
$response['status'] = 'it went horribly wrong';
}
echo json_encode($response);
I am trying to insert multiple records through JS function.JS function calls action of another YII controller that performs insertion.
I am reading the data from a MySql table performing some actions on data and saving the changed data to an array post_data. Later I am converting this array to url format and passing as parameter to JS function. This function has ajax to call another controller to perform insertion.
I am trying to insert to 2 tables. 1st contact_details table is inserted and then engineer table is inserted, so I want this ajax call to run in serial way. i.e, I want next insertion to start only after the previous insertion is complete.
My code is:
<script>
function call_migration_api(post_data)
{
//console.log( 'post data in js func = '+post_data);
//var db_data = post_data.serialize();//tried this, but not working.
var db_data = post_data;
$.ajax({
type: "POST",
url:"http://localhost/amica_migration/rapport/chs/Migrationapi/createengineer",
data: db_data,
success: function(server_response)
{
console.log(server_response)
}//end of success
});//end of $.ajax
}//end of function.
</script>
<?php
//reading all values in $post_data array.
foreach ( $post_data as $key => $value)
{
$post_items[] = $key . '=' . $value;
}
$post_string = implode ('&', $post_items);
echo "<script>call_migration_api('$post_string');</script>";// Call to AJAX function.
?>
Migration API code:
<?php
public function actionCreateEngineer()
{
$engineer_model=new Engineer();
$contactdetails_model=new ContactDetails();
//****** RETRIVING CONTACT DETAILS ***********
$contactdetails_model->address_line_1= $_POST['address_line_1'];
$contactdetails_model->town= $_POST['town'];
$contactdetails_model->postcode_s= $_POST['postcode_s'];
$contactdetails_model->postcode_e= $_POST['postcode_e'];
$contactdetails_model->telephone= $_POST['telephone'];
$contactdetails_model->email= $_POST['email'];
//********** SAVING CONTACT ***************
if($contactdetails_model->save())
{
echo "<br>Contact Model Saved";
$engineer_model->contact_details_id=$contactdetails_model->id;
$engineer_model->delivery_contact_details_id=$contactdetails_model->id;
//****** RETRIVING ENGINEER DETAILS ***********
$engineer_model->first_name=$_POST['first_name'];
$engineer_model->last_name=$_POST['last_name'];
$engineer_model->active=$_POST['active'];
$engineer_model->id=$_POST['engg_id'];
//****** SAVING ENGINEER DETAILS ***********
if($engineer_model->save())
{
echo "<br>Engineer saved";
}
else
{
echo "<br>Engineer not saved******** ENGG ERROR = ";
print_r($engineer_model->getErrors());
}
}//end of if contact save.
else
{
echo "<br>Contacts NOT SAVED ///////// CONTACT ERROR = ";
print_r($contactdetails_model->getErrors());
}
}//end of create engineer.
?>