Jquery ajax call a php script with require once - javascript

I have an ajax request like :
$.ajax({
type: "GET",
url: "services/Test.class.php",
data: "call=getTest",
success: function (data) {
alert(data);
},
error: function (response) {
alert("Error getting php file");
}
});
So, in my class ( Test.class.php ), I have a getTest() function and a require_once('OtherPHP'),
When I test this code, I have an error in require once :
No such file or directory
in my alert(data)
how can I fix it?

It seems like you've included a wrong path of OtherPHP file in Test.class.php. Use file_exists() function to make sure that given path really exists before including/requiring in Test.class.php
if (file_exists(`OtherPHP.php`)) {
require_once(`OtherPHP.php`)
} else {
echo "The file `OtherPHP.php` does not exist";
}

You cant able to call the class directly from ajax,
create new php file say test.php
in test.php
include("Test.class.php");
$test = new Test();
$test ->getTest(); //print the getTest outpout here
Javascript:
$.ajax({
type: "GET",
url: "test.php",
.....

Related

Passing value to php from local storage using Ajax

I.m want to pass the values from js to php that is stored in local storage
js
let cartItems = localStorage.getItem("productsInCart");
var jsonString = JSON.stringify(cartItems);
$.ajax({
url:"read.php",
method: "post",
data: {data : jsonString},
success: function(res){
console.log(res);
}
})
php
<?php
print_r($_POST)
?>
on .php im getting just "array ()"
using #reyno's method with all the code in the same file called 'store_user_order.php'
<?php
if(isset($_POST["data"])) {
print_r($_POST["data"]);
} else {
?>
<button>SEND</button><br/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js"> </script>
<script>
const cartItems = localStorage.getItem("productsInCart");
const jsonString = JSON.stringify(cartItems);
$("button").click(function() {
$.ajax({
url: 'store_user_order.php',
method: 'post',
data: {
data: jsonString
},
success: function(res) {
$('body').append(res);
},
error: function(err) {
$('body').append(err);
}
});
})
</script>
<?php } ?>
This should work if you have items in the localstorage
While testing, for checking values use method: "get", make sure that your test values aren't huge - you will see submitted values in the address bar.
For testing (php + MySQL) I always use this method:
success ? changes() : errors_list();`
I don't use js, so deal with syntax yourself, please.
on .php im getting just "array ()"
You received an empty $ _POST array - nothing was sent.
Because there was nothing to send, or there was an error sending

JQuery/AJAX Unable to Get Response from PHP file

I am trying to run a server side python script for my wordpress site. I can call the python file inside a php function and run it on the site as shortcode. So, the php file is working. The issue I am having is building my JQuery and getting the response from the php file. I am trying to do a hello_world set-up to debug the issue
AJAX Query:
function myFunction() {
alert("Testing button");
}
function HelloWorldShortcode() {
jQuery(document).ready(function($) {
$.ajax({
dataType: 'json',
method: 'POST',
url: "http://localhost/wp-content/helloworld.php",
data: {
action: 'helloworld'
},
error: function(data) {
alert("bad");
},
success: function(response) {
alert(response);
}
});
})
}
and the php file:
<?php # -*- coding: utf-8 -*-
ini_set('display_errors', 1);
function hello_world() {
$test = 'hello';
return $test;
}
if (isset($_POST['helloworld'])) {
return hello_world();
}
I have also tried using GET instead of POST. When I access the php file in the browser I do not get any errors and the success part of the ajax query is being reached, as i do not get any error messages. What can I do to access the hello_world() function inside of the php file and display the output?
Thanks
You are using the value of the parameter, not the parameter itself...
if (isset($_POST['action'])) {
echo hello_world();
// Or json_encode(hello_world()); for returning an Array
}
or
if ($_POST['action'] == 'helloworld') {
return hello_world();
// Or json_encode(hello_world()); for returning an Array
}
You would do something like:
if (isset($_POST['helloworld'])) {
echo hello_world();
// Or json_encode(hello_world()); for returning an Array
}

jQuery Ajax post is not working

I know that there is a lot of questions like this out there, but I have been surfing them and other website for like 4 hours trying to figure this out. I am trying to get main.js to post the data via ajax and then the php should echo that data. If it does not work, it will echo "null". It keeps echoing "null" instead of "John". I know that the jquery and main.js links work, I have tested them. Here is main.js:
$(document).ready(function(){
$.post("index.php", { test: "John"} );
});
And here is the php part of index.php:
<?php
$var = "null";
if(isset($_POST['test'])) {
$var = $_POST['test'];
}
echo $var;
?>
I hope you can solve my problem, and thank you in advance.
You are missing the callback function with the response from the server.
$.post( "index.php",{ test: "John"}, function( data ) {
alert(data);
});
Or you can do something like this:
$.post( "index.php",{ test: "John"})
.done(function( data ) {
alert( "Data Loaded: " + data );
});
Please check the documentation Documentation
Give this a shot
jQuery
var available agent = 1;
jQuery.ajax({
type: "POST",
url: "your-url",
data: available_agent,
dataType: 'json',
cache: false,
contentType: false,
processData: false,
success: function(data){
owner = data['round_robin_agent'];
},
error : function () {
alert("error");
}
});
PHP Script
public function round_robin() {
//Do your work
$round_robin_agent = 'rob';
$results_array = array(
'round_robin_agent' => $round_robin_agent
);
return json_encode($results_array);
}
Download HTTP Trace chrome extension, traceback ajax call and share a screenshot.
https://chrome.google.com/webstore/detail/http-trace/idladlllljmbcnfninpljlkaoklggknp

laravel pdf file download from ajax request (laravel 5)

My html code is like this :
<i class="fa fa-file-pdf-o"></i>
My javascript code is like this :
function showAjaxPdf(file_path)
{
var file_path = file_path.replace(/\\/g,"/");
//example : file_path = assets/images/myfile.pdf
$.ajax({
type: "POST",
data: 'file_path=' + file_path,
url: "news/test",
success: function(response)
{
$('#test').html(response);
}
});
}
My function test in controller :
public function postTest(Request $request)
{
$file_path = $request->input('file_path');
return response()->download($file_path);
}
When I click on the pdf icon, no response.
I wish, when click on the pdf icon, appear like this:
how to keep when click pdf icon, the image appears like it?
Thank you
What I have done is, written two separate route one to verify and one to download.
On success of one ajax I have triggered window.open(downloadUrl,'_blank') to download in separete window.
It is not the way asked but it prevents any upcoming errors as verify url will sort that
$.ajax({
url: verifyUrl,
type: 'get',
cache: false,
data: null,
error: function (err){$('#ajax_loader_div').hide();},
success: function(response) {
console.log(response);
$('#ajax_loader_div').hide();
if (response.status == 'success')
{
window.open(downloadUrl,'_blank');
}else if(response.status == 'error')
{
//show error
}
}
});
for that you need to set the header with response object.
Please see the below code.
$headers = array(
'Content-Type'=> 'application/pdf'
);
$file_path = $request->input('file_path');
//TODO: you have to split the file name from url
return Response::download($file_path, '<filename>', $headers);
I hope this code will help you
return Response::download($file_path, '<filename>', $headers);
It's return response, not download file!

How to pass value from javascript to php in same page

Im tying to implament a preloader for swf based on this Post, but im getting trouble passing the javascript value to a php variable.
<script type="text/javascript">
var swfJSPreLoaderConfig = {
'assets':['swf/test.swf'],
'assetLoaded': function( asset){
alert(asset);
},}
</script>
The alert in the above code shows only when the swf file test.swf is fully downloaded. the value that im trying to get in php is asset ( this value contain the swf file path, in this example is swf/test.swf. the alert fires always when the swf files is fully dowloaded and it works very good.)
i tried something like this to get it in a php variable. but no lucky.
$filename = $_REQUEST['asset'];
also i tired using ajax but nothing.
<script type="text/javascript">
var swfJSPreLoaderConfig = {
'assets':['swf/test.swf'],
'assetLoaded': function( asset){
$.ajax ({
type: "post",
url: "index.php",
data: { 'asset': asset },
success: function()
{
alert(asset);
}
});
},}
</script>
and then
$filename = $_REQUEST['asset'];
Whats worng?
Try this,
data: { 'asset': asset },
success: function(response)
{
alert(response);
}
instead of,
data: { 'asset': asset },
success: function()
{
alert(asset);
}
});
PHP:
echo $filename = $_REQUEST['asset'];
Change from
url: "index.php"
to
url: "index.php?asset="+asset
Then in PHP, use:
echo $_GET['asset'];
to confirm that you are sending the correct value

Categories

Resources