Error with AJAX and PHP referencing - javascript

I've been looking at this for a while and I think the major issue is the file i am referencing but I am not sure. I am working with a large amount of php files scattered all over the project folder but in the immediate folder I am working with files NavBar.php which is called using a require() statement in layout.php
here's the code I am having trouble with (btw all of this code is in NavBar.php):
<?php
$db=mysql_connect('localhost','root','');
if(!$db) {
die('Could not connect: '.mysql_error());
}
$connection_string=mysql_select_db('shipreq_stagetest',$db);
$selectSQL='SELECT * FROM color_patterns';
$queryset=mysql_query($selectSQL);
$num=mysql_num_rows($queryset);
if(0==$num) {
echo "No record";
exit;
} else {
while($row=mysql_fetch_assoc($queryset)) {?>
<li class= "list_item" onclick="<?php $indx = $_POST['pat_id'];?>">
<?php echo($row['name']);?></li><?php
}
}
?>
I know the sql calls are outdate and I should change it to PDOs I will make the switch as soon as I can figure out why the AJAX isn't working. this php code makes a db call and retrieves some data which displayed in the li (new li generated for each row in the table)(dropdown) and when a user clicks it I want to use this JS function to save the index of the clicked li to a php variable (hence the AJAX, I am really new to AJAX so I am having trouble figuring it out):
<script>
$(document).on('click', '.list_item', function() {
var indx = $(this).index();
$.ajax({ // add ajax code here
type: 'POST',
url: 'layout.phtml',
data: {pat_id: indx}, // send parameter like this
success: function(response) {
console.log(response);
}
});
});
</script>
I think the major issue might be the file I am referencing since NavBar.php is referenced by layout.phtml which is probably required by some other document in the hierarchy. this is the error I get in the console when I click on the li:
jquery.min.js:4 XHR finished loading: POST "http://localhost/shiprequest/layout.phtml".send # jquery.min.js:4ajax # jquery.min.js:4(anonymous function) # shiprequest?lang=en:235dispatch # jquery.min.js:3r.handle # jquery.min.js:3
shiprequest?lang=en:240
( ! ) Fatal error: Uncaught exception 'Zend_Acl_Exception' with message 'Resource 'shiprequest_layout.phtml' not found' in C:\sgm\library\Zend\Acl.php on line 364
( ! ) Zend_Acl_Exception: Resource 'shiprequest_layout.phtml' not found in C:\sgm\library\Zend\Acl.php on line 364
Call Stack
#TimeMemoryFunctionLocation
10.0006145888{main}( )..\index.php:0
20.0018168016require_once( 'C:\sgm\application\bootstrap.php' )..\index.php:5
30.11182860576Zend_Controller_Front->dispatch( )..\bootstrap.php:124

From the message error provided by you:
Uncaught exception 'Zend_Acl_Exception' with message 'Resource
'shiprequest_layout.phtml' not found
Validate if shiprequest_layout.phtml exist.
You probably wanted to write shiprequest_layout.html and not .phtml
<script>
$(document).on('click', '.list_item', function() {
var indx = $(this).index();
$.ajax({ // add ajax code here
type: 'POST',
url: 'layout.html', <------ here
data: {pat_id: indx}, // send parameter like this
success: function(response) {
console.log(response);
}
});
});
</script>
EDIT from Comments:
If you file is really layout.phtml, then your error is in file Acl.php (C:\sgm\library\Zend\Acl.php) at line 364. Line 364 is trying to find shiprequest_layout.phtml if this file do not exist, you will get this error.
You probably mean layout.phtml instead of shiprequest_layout.phtml

Related

Loading php file when execute and pass variable through Ajax

I'm sorry but I'm having a hard time setting up something simple but that doesn't work for me. I'm trying to put a code that counts the number of clicks on a phone number ( the last 4 hidden digits that appear ) then record this data in my DB. I set up the JAVASCRIPT at the bottom of my PHP page where I will listen if there is a click ( Addeventlistener.... ) on the phone number.
I understood that we can not execute PHP code in a JS script, OK, so I execute an Ajax code to send to a PHP file the values to insert in a new entry to my DB. Except that during the execution the functions that open a connection to the DB are not recognized while in the same way I use others functions in the same PHP file that selects and returns me data from the DB.
Is the difference that they are two different types of request SELECT and INSERT or it is because I send the data through Ajax that the PHP files that load the function of DB connection are not loaded?
AJAX Script
<script>
var phoneclick = document.querySelector(".data-phone");
var baseUrl = "public_html/oc-content/themes/delta/"
phoneclick.addEventListener("click", function() {
var item_id = 8111;
var ajaxPhoneClick = 1;
$.ajax({
url: '<?php echo osc_current_web_theme_url('model/sql_projet.php'); ?>',
type: "GET",
data: {
id: '1111'
},
success: function(data) {
console.log(data);
}
});
});
</script>
PHP FIle
$itemId = $_GET['id'];
$conn = DBConnectionClass::newInstance();
$data = $conn->getDb();
$comm = new DBCommandClass($data);
$db_prefix = DB_TABLE_PREFIX;
$query = "INSERT INTO {$db_prefix}t_item_stats (item_id,phone_clicks) VALUES ($itemId,1) ";
$result = $comm->query($query);
The error i get is this Fatal error: Uncaught Error: Class 'DBConnectionClass' not found in /Applications/XAMPP/
I want to know the reason why this error is throwing and what should i do to bypass this

AJAX call returns undefined in Header / form-data

I am trying to get the contents from some autogenerated divs (with php) and put the contents in a php file for further processing. The reason for that is I have counters that count the number of clicks in each div. Now, I ran into a problem. When I echo back the data from the php file, the call is made, but I get undefined in the form-data section of the headers, and NULL if I do var_dump($_POST). I am almost certain I am doing something wrong with the AJAX call. I am inexperienced to say the least in AJAX or Javascript. Any ideas? The code is pasted below. Thanks for any help / ideas.
The AJAX:
$(document).ready(function(e) {
$("form[ajax=true]").submit(function(e) {
e.preventDefault();
var form_data = $(this).find(".test");
var form_url = $(this).attr("action");
var form_method = $(this).attr("method").toUpperCase();
$.ajax({
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
$("#resultcart").html(returnhtml);
}
});
});
});
The PHP is a simple echo. Please advise.
Suppose you have a div
<div id="send_me">
<div class="sub-item">Hello, please send me via ajax</div>
<span class="sub-item">Hello, please send me also via ajax</span>
</div>
Make AJAX request like
$.ajax({
url: 'get_sorted_content.php',
type: 'POST', // GET is default
data: {
yourData: $('#send_me').html()
// in PHP, use $_POST['yourData']
},
success: function(msg) {
alert('Data returned from PHP: ' + msg);
},
error: function(msg) {
alert('AJAX request failed!' + msg);
}
});
Now in PHP, you can access this data passed in the following manner
<?php
// get_sorted_content.php
if(!empty($_POST['yourdata']))
echo 'data received!';
else
echo 'no data received!';
?>
It's sorted. Thanks to everyone. The problem was I didn't respect the pattern parent -> child of the divs. All I needed to do was to wrap everything in another div. I really didn't know this was happening because I was echoing HTML code from PHP.

Echo PHP message after AJAX success

I have a modal that will display when the user clicks a delete button. Once they hit the delete button I am using AJAX to subimit the form. Eveything works fine, but it is not display my success message which is set in PHP.
Here is my AJAX code:
function deleteUser(){
var id = <?php echo $userdetails['id'] ?>;
$.ajax({
type: "POST",
url: 'admin_user.php?id=' + id,
data: $('form.adminUser').serialize(),
error: function(e){
alert(e);
},
success: function () {
// This is empty because i don't know what to put here.
}
});
}
Here is the PHP code:
if ($deletion_count = deleteUsers($deletions)) {
$successes[] = lang("ACCOUNT_DELETIONS_SUCCESSFUL", array($deletion_count));
} else {
$errors[] = lang("SQL_ERROR");
}
And then I call it like this:
<div class="col-lg-12" id="resultBlock">
<?php echo resultBlock($errors,$successes); ?>
</div>
When I use AJAX it does not display the message. This works fine on other pages that does not require AJAX to submit the form.
I think you are getting confused with how AJAX works, the PHP script you call will not directly output to the page, consider the below simplified lifecycle of an AJAX request:
Main Page -> Submit Form -> Put form data into array
|
--> Send array to a script to be processed on the server
|
|----> Callback from the server script to modify DOM (or whatever you want to do)
There are many callbacks, but here lets discuss success and error
If your PHP script was not found on the server or there was any other internal error, an error callback is returned, else a success callback is fired, in jQuery you can specify a data array to be received in your callback - this contains any data echoed from your PHP script.
In your case, you should amend your PHP file to echo your arrays, this means that if a successful request is made, the $successes or $errors array is echoed back to the data parameter of your AJAX call
if ($deletion_count = deleteUsers($deletions)) {
$successes[] = lang("ACCOUNT_DELETIONS_SUCCESSFUL", array($deletion_count));
echo $successes;
} else {
$errors[] = lang("SQL_ERROR");
echo $errors;
}
You can then test you received an object by logging it to the console:
success: function(data) {
console.log(data);
}
Well, it's quite not clear what does work and what does not work, but two things are bothering me : the function for success in Ajax is empty and you have a header function making a refresh in case of success. Have you tried removing the header function ?
success: function(data) {
alert(data);
}
In case of success this would alert the data that is echoed on the php page. That's how it works.
I'm using this a lot when I'm using $.post
Your header will not do anything. You'll have to show the data on the Java script side, maybe with alert, and then afterwards redirect the user to where you want in javascript.
you need put some var in success function
success: function(data) {
alert(data);
}
then, when you read var "data" u can do anything with the text
Here is what I changed the PHP to:
if ($deletion_count = deleteUsers($deletions)) {
$successes[] = lang("ACCOUNT_DELETIONS_SUCCESSFUL", array($deletion_count));
echo resultBlock($errors,$successes);
} else {
$errors[] = lang("SQL_ERROR");
echo resultBlock($errors,$successes);
}
And the I changed the AJAX to this:
function deleteUser(){
var id = <?php echo $userdetails['id'] ?>;
$.ajax({
type: "POST",
url: 'admin_user.php?id=' + id,
data: $('form.adminUser').serialize(),
error: function(e){
alert(e);
},
success: function (data) {
result = $(data).find("#success");
$('#resultBlock').html(result);
}
});
}
Because data was loading all html I had to find exactly what I was looking for out of the HTMl so that is why I did .find.

jQuery.ajax + php 5.3 - always executing error function

(Newb here) I have a PHP function that gets 2 csv files from the server and create a new one with the difference between values contained in those files. This PHP function is inside a separate file test.php and looks like this:
<?php
require_once('libs/parsecsv-for-php-master/parsecsv.lib.php');
$csv1name = $_POST['csv1'];
$csv2name = $_POST['csv2'];
$data1 = 'data/'.$csv1name.'.csv';
$data2 = 'data/'.$csv2name.'.csv';
$csv1 = new parseCSV($data1);
$csv2 = new parseCSV($data2);
$csv = new parseCSV();
$csv->data[0] = array('label','difference');
$j = 1;
for ($i = 0; $i < count($csv1->data); $i++) {
$csv->data[$i+1] = array($j.'d',$csv1->data[$i][$csv1name] - $csv2->data[$i][$csv2name]);
if($i == 0) {$j += 20;}
else {$j += 21;}
}
$csv->save('test.csv');
?>
This function works correctly and produces the expected csv file.
I have a JavaScript function that sits on another page (namely update.html) and calls the aforementioned php function via ajax:
function callPHP() {
$.ajax({
type:"POST",
url:"test.php",
dataType:"json",
data:{csv1: '02-01-2015', csv2: '02-12-2014'},
error: function(requestObject, error, errorThrown) {
alert(error);
alert(errorThrown);
},
});
}
PROBLEM: The error function is always executed, that is, whenever I run callPHP() I get two alerts.
QUESTION: Why is it error always being called?
(Extra: Is it possible to work with the response variable? How can I debug it without having to upload my files to a server every time? Is it guaranteed that when the complete function is called, the $csv->data function was already resolved?)
Thanks for helping!!! :D
UPDATE 1: I changed the code above by removing the complete function from ajax and I added some extra parameters to the error function.
complete is always called no matter its success or error. So you are running into error condition and complete gets called anyway after error is executed. You can add additional params (jqXHR jqXHR, String textStatus, String errorThrown) in error function to figure out what the error is.
Try using success instead of complete, and add a JSON answer to your PHP script for example echo json_encode((object) array('success'=>true)); because your AJAX call has dataType:"json" parameter for a JSON response, so your AJAX call will try to parse a JSON.
PHP code:
header('Content-Type: application/json');
echo json_encode((object) array('success'=>true));
AJAX:
function callPHP() {
$.ajax({
type:"POST",
url:"test.php",
dataType:"json",
data:{csv1: '02-01-2015', csv2: '02-12-2014'},
success: function(response) {
alert(response);
},
error: function(response) {
alert(response);
},
});
}

Ajax cant find php file.. Why?

I am trying to create a ajax-login-form, but my jquery-script cant find the php file. they are in the same directory (!), but it doesn't work.
my php-file (logreg.php)
<?php
echo 'true';
?>
my script-file (logreg.js)
$("button[action=\"register\"]").click(function(){
var username = $("#login-username").val();
var password = $("#login-password").val();
var repassword = $("#login-repassword").val();
$.ajax({
type: "POST",
url: "logreg.php",
data: "name="+username+"&pass="+password+"&repass="+repassword,
success:function(html){
if(html=='true'){
}
},
beforeSend:function(){
$("button[action=\"register\"]").text("Sendet ...");
},
error: function(ts) { $("div#content").html(ts.responseText); }
});
});
why isnt this working? i am getting everytime "Error 404" (not found).
they are in the same directory
URLs are relative to the HTML document not the JavaScript file.
You should be able to load your logreg.php in your browser and get the 'true' message on your screen. So use whatever url to get to your php file, then use the same url in your js file:
url: "http://mydomain.local/logreg.php",

Categories