I want to call PHP page using AJAX but I don't want to reload PHP classes each time, for example, on first time running AJAX, PHP page load and set data, but on second time running AJAX, php get the same data from first time.
function test() {
$.ajax({
url: "./test.php",
method: "post",
success: function(data) {
$(document).find("body").append(`<p>${data}</p>`);
}
});
}
<button type="button" onclick="test()">Click Me!</button>
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
//test.php
class Test{
private $name = null;
public function setName($name){
$this->name = $name;
}
public function getName(){
return $this->name;
}
}
$class = new Test;
if( $class->getName() == null ){
echo "oops";
$class->setName("pong");
} else {
echo $class->getName();
}
// Fire off the request to /form.php
request = $.ajax({
url: "/form.php",
type: "post",
data: serializedData
});
// Callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
// Log a message to the console
});
// Callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// Log the error to the console
console.error(
"The following error occurred: "+
textStatus, errorThrown
);
});
// if the request failed or succeeded
request.always(function () {
//add your logic
});
Related
I know the jQuery load syntax which is
$("#count").load("demo_test.txt #p1");
this is the code I'm using for my button's onclick function
temp_user_cart.php
function resMinus(id){
if (id) {
$.ajax({
url: "temp_cart-minus.php",
type: "post",
data: {
id_minus: id
},
success:function(response) {
var employeeTable = $("#myTables").DataTable();
employeeTable.ajax.reload(null, false);
},
error: function(jqXHR, textStatus, errorThrown){
console.log(errorThrown);
}
});
return false;
}
};
After this AJAX succeed/execute I want to load the contents of cart_counter.php to this page
restaurant-order.php
<span id="cart_counter"></span>
this is cart_counter.php
<?php
session_start();
echo $_SESSION['count_count'];
?>
I have a Javascript function called when the user clicks on a button. There are multiple "bookmark" buttons on the page:
javascript:ajax_bookmark_url(1,"http://www.legitsite.com");
How can i make this more secure?
I mean a user can just type the following in the chrome console;
javascript:ajax_bookmark_url(1,"http://www.notalegitsite.com");
The above function call is bad as the user can see the url being bookmarked? Do I need to encrypt it? Any advice would be great.
I assume I need add the security component from CakePHP 3? I'm not sure
JS function:
//bookmark an articles url
function ajax_bookmark_url(id,url){
var mydata=new Object();
mydata.feed_id=id;
mydata.url=url;
jQuery.ajax({
type:'POST',
async: true,
cache: false,
data: mydata,
url: '<?= $this->request->webroot ?>feeds/bookmark',
success: function(response,textStatus, jqXHR) {
//success
alert(response);
console.log(response);
},
error: function(jqXHR, exception) {
console.log(response);
}
});
}
CakePHP 3 controller function:
public function bookmark(){
if ($this->request->is('ajax') && $this->request->is('post')) {
$myTable = TableRegistry::get('user-bookmarks');
$userBookmark = $myTable->newEntity();
$userBookmark = $myTable->patchEntity($userBookmark, $this->request->data);
//set the looged in user's id
$userBookmark->user_id=$this->Auth->user('id');
//auto generated
$userBookmark->created=Time::now();
$userBookmark->modified=Time::now();
$this->autoRender=false;
try{
if ($myTable->save($userBookmark)) {
//success
$status="Bookmark Saved.";
}
}
catch(\PDOException $e){
//should log this error
$status="error: DB Error, Bookmark already exists. ".$e;
}
catch(\Exception $e){
//should log this error
$status="error: General Exception";
}
$this->response->body(json_encode($status));
return $this->response;
}
else{
$status['msg']="Non Ajax Request";
$this->response->body(json_encode($status));
return $this->response;
}
}
I'm trying to send variables from my JavaScript to a PHP file using AJAX but it's not working. I've looked through all the similar asked questions (there are a bunch) but have yet to find a solution.
This is my first php file (one with the form, sends data to JavaScript):
<option value="imageOne" data-cuteform-image='assets/SketchThumbnails/imageOne.png></option>
<input id="inputURLID" type="text" name="inputURL">
<button type="submit" onclick="handleInputs(document.getElementById('sketch').value, document.getElementById('inputURLID').value); return false;">Submit</button>
JavaScript (where AJAX call is):
var content = {
'sketch': pickedSketch,
'songUrl': enteredURL
};
$.ajax({
type: "POST",
url: "loadSketch.php",
data: content,
success: function (data, text) {
// alert("success");
// console.log(data);
// console.log(text);
window.location.href = "loadSketch.php";
},
error: function (request, status, error) {
alert(request.responseText);
}
});
PHP (loadSketch.php):
if(isset($_POST['songUrl']))
{
$temp = $_POST['songUrl'];
echo $temp;
echo "received AJAX data";
} else {
echo "nothing in post variable";
}
When I get redirected to loadSketch.php (from the successful ajax call), "nothing in post variable" gets echoed out. Any ideas what I'm doing wrong?
Any insight is much appreciated! :)
Nothing is in songURL because when your Ajax function returns it is redirecting to the same page you just posted to. It is creating a new HTTP request to that PHP file with no data sending to it. Remove the comments on the console messages and you'll see the correct echo messages.
$.ajax({
type: "POST",
url: "loadSketch.php",
data: content,
success: function (data, text) {
alert("success");
console.log(data);
},
error: function (request, status, error) {
alert(request.responseText);
}
});
You should not use a submit button because it makes the whole page reload; instead use normal buttons and handle the click events calling your AJAX function.
HTML:
<button onclick="doAjaxFunction(param1, param2);">Calling Ajax Function<button>
JavaScript:
function doAjaxFunction(val1,val2){
$.ajax({
type: "POST",
url: "loadSketch.php",
dataType: "json",
data: {"'value1':'"+ val1+"', 'value2':'"+ val2+"'"},
success: function (data, text) {
// alert("success");
// console.log(data);
// console.log(text);
window.location.href = "loadSketch.php";
},
error: function (request, status, error) {
alert(request.responseText);
}
});
Then just pick your POST parameters in loadSketch.php and use them.
PHP:
$x = $_POST['value1'];
$y = $_POST['value2'];
I have an ajax call like so:
$.ajax({
url: '/assets/functions.php',
type: 'POST',
data: {
"functionCall": "get-uploads",
"type": type
},
dataType: 'json',
success: function (data, textStatus) {
console.log("done");
console.log(data);
console.log(textStatus);
},
error: function(textStatus, errorThrown) {
console.log("uh oh");
console.log(textStatus);
console.log(errorThrown);
}
});
Which gets sent to and handled with this:
switch($_POST['functionCall']) {
.
.
.
case "get-uploads":
$type = $_POST['type'];
$getUploads = "SELECT * FROM pp_uploads WHERE type = '$type';";
$docArray = array();
while($row = mysql_fetch_assoc($documents)) {
$docArray[] = $row;
}
echo json_encode($docsArray);
}
When I run this I get a parsing error, which from what I understand means that the returned data isn't being returned as JSON. So I changed the dataType to html, and I see that the returned data in the console is:
[{"id":"35","filename":"fdgsdf","path":"ConfiguratorTreeDiagram.pdf","type":"resources"},{"id":"36","filename":"gsrewg","path":"dhx_advertising.pdf","type":"resources"}]Array
(
[functionCall] => get-uploads
[type] => resources
)
So it looks like the data I passed into the call is being appended to the end of my data. How do I prevent that from happening?
It looks like you might be doing a print_r somewhere on an Array variable?
I am trying to use Ajax to reload data from a database. However, the Ajax doesn't call the controller action that I specified in the url:. Here is my Ajax code:
function selectFieldChanged(id){
$.ajax({
type: "POST",
url: Routing.generate('demo_ajax'),
data: id,
success: function(){
alert("Success");
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
alert('Error : ' + errorThrown);
}
});
}
$(document).ready(function(){
var id = $(this).val();
$('#form_patient').change(function(){selectFieldChanged(id)});
});
The routing.xml :
demo_ajax:
pattern: /ajax/patient
defaults: { _controller: DemoBundle:Default:index}
options:
expose: true
So, I tried to simply echo the value out in the indexAction to see whether it is called or not.
public function indexAction(Request $request)
{
if($request->isXmlHttpRequest()){
echo "xmlHttpRequest is called";
}
if($request->getMethod()=='POST'){
echo 'POST is called';
}
}
However, I didn't get anything from the indexAction but I got the alert message, `Success, from my Ajax What did I do wrong?
The success callback receives data from your server so a variable must be declared to capture it:
success: function(data){ // <-----
console.log(data);
alert("Success");
},