Using ajax to run a php file and output php on page - javascript

I'm trying to run a PHP file with ajax and have text output from the PHP file into my container. I've looked into multiple examples but still don't get anything out of my ListTranslations.php file.
A short explanation of what is supposed to happen:
On index.php file, I run a list of all languages found in the database and fill onClick function with a specific language. On click, the ajax function should run my ListTranslations.php file and output the list of all the translations found for the specific language.
Here is the index.php where the ajax function is called:
foreach($languages as $language){
echo '' . $language . '' . ': ' . count($language) . "<br>";
}
ajax function: ( I have a content div set )
function sendLanguage(tongue) {
jQuery.ajax({
url: "ListTranslations.php",
method: 'GET',
data: {language: tongue},
contentType: 'application/json; charset=utf-8',
dataType: 'json'
}).done(function(r){
$('#content').html(response);
}).fail(function(e){
console.log(e);
});
}
ListTranslations.php file:
if($_GET["tongue"]) {
$aPoem = $poems->find(array('language'=>($_GET["tongue"])));
foreach($aPoem as $poem) {
echo '' . $poem["title"] .'<br>';
}
}
I have no clue what I'm doing wrong and why it is not working so any help is much appreciated!

First of all, declare if your div is of a class or id content:
$(".content");
$("#content");
Also, your function argument isn't used in the whole structure and you use only 'tongue' string; to pass a variable, get rid of '' like:
data: { language: tongue }
Also, any particular reason to use deprecated jQuery methods? If not, you should use this structure:
function findDifferentNameThanAjax(tongue) {
$.ajax({
url: "ListTranslations.php",
method: 'GET',
data: {language: tongue},
contentType: 'application/json; charset=utf-8',
dataType: 'json'
}).done(function(r){
$('#content').html(response);
}).fail(function(e){
console.log(e);
});
}
Alse, make sure if your ajax url is correct.

Related

Jquery throws an 'Illegal invocation' error

I'm trying to create a forum and jquery throws an 'illegal invocation' error.
Here is my jquery code:
$('#formSumbit').on('submit', function(e) {
e.preventDefault();
$.ajax({
url: 'data-get.php',
type: 'POST',
data: new FormData(this),
contentType: false,
dataType: 'json',
success: function(value) {
var serialize = $.parseJSON(value);
if (serialize.success == 'false') {
$('.alert').fadeIn().delay(3000).fadeOut();
$('.alert-msgText').html(serialize.datamsg);
}
}
});
});
And here is my PHP code:
<?php
$user = $_POST['user'];
$msg = $_POST['message'];
if(empty($user)&&empty($message)) {
$data = array(
'success' => 'false',
'datamsg' => 'Please fill the textboxes'
);
echo json_encode($data);
} else {
mysqli_query($con,"INSERT INTO forums(name,message) VALUES ('$user','$msg')");
$data = array(
'success' => 'true',
'datamsg' => 'Done!'
);
echo json_encode($data);
}
exit();
?>
When the textboxes are empty and i click the submit button, nothing seems to work and jquery throws an illegal invocation error. I don't understand what the problem is. Can you please help?
And thanks in advance!
1) You have a typo mismatch between your form and your JavaScript:
<form id="formSubmit" and $('#formSumbit') - it should be $('#formSubmit') to match the spellings.
2) Unless you are trying to upload files via this AJAX request, then you can simplify things by replacing data: new FormData(this), contentType: false, with just data: $(this).serialize(). This will get rid of the illegal invocation error.
3) Writing dataType: 'json' means that jQuery will automatically try to parse the data coming from the server as JSON, and convert it. Therefore, in your "success" function, value will already be parsed and converted to an object. In turn therefore, using $.parseJSON is not necessary. You can just access value.success directly, for instance.
Here's a fixed version:
$('#formSubmit').on('submit', function(e) {
e.preventDefault();
$.ajax({
url: 'data-get.php',
type: 'POST',
data: $(this).serialize(),
dataType: 'json',
success: function(value) {
if (value.success == 'false') {
$('.alert').fadeIn().delay(3000).fadeOut();
$('.alert-msgText').html(value.datamsg);
}
}
});
});
Working demo: https://jsfiddle.net/khp5rs9m/2/ (In the demo I changed your URL for a fake one, just so it would get a response, but you can see where I have altered it and left your settings in the commented-out part).

Unable to pass formData with other parameters in jQuery

I am trying to pass formData along with other parameters to a PHP script.
Using the $.post method, I was getting an 'Illegal Invocation' error. So I abandoned the $.post method and went to $.ajax method.
As follows:
$('#uploadBtn').on('click', function()
{
var formData = new FormData($('#uploadfile')[0]); // the form data is uploaded file
var booking = $('#bookingNum').val();
var partner = $('#partnerCode').val();
var parameters =
{
formData:formData,
booking:booking,
partner:partner
}
$.ajax({
url: 'process/customer.php',
data: parameters, // <- this may be wrong
async: false,
contentType: false,
processData: false,
cache: false,
type: 'POST',
success: function(data)
{
console.log(data);
},
error: function(jqHHR, textStatus, errorThrown)
{
console.log('fail: ' + errorThrown);
}
});
});
On the PHP side, I'm trying to get the parameters object like so:
<?php
if(isset($_POST['parameters']))
{
echo "Hello";
$value = $_POST['parameters'];
// I can get the other 2 parameters like this
$company = htmlspecialchars(trim($value['booking']));
$partner = htmlspecialchars(trim($value['partner']));
// not sure how to get the uploaded file information
}
?>
Basically, I am uploading a file to be saved to a directory. But the problem is, I cannot send anything over to the PHP side. I am getting this warning:
"jquery.js:2 [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/."
I need to be able to send the 'parameters' object over to the PHP script, then access it for processing.
How can I achieve this using the $.ajax method? Then how do I access the formData once on the PHP side?
The parameters is the object you are POSTing. the key value pairs will be based on it's properties. Try accessing them like $_POST['formData'] and $_POST['booking'].
Also... please rework your code to remove the async:false ... TBH this should never have been put into jQuery and is absolutely terrible. Don't feel bad, it's the first thing every newcomer tries when they first start using ajax, myself included. You're going to cause the UI thread to hang for the duration, preventing all user interaction during the call.
EDIT
I didn't realize you are trying to post a file at first, so this is not a complete answer as I don't think you are accessing it correctly. But The important part of this answer is that there is no parameters index of $_POST (which is why not even your echo "hello" is coming back).
if you POST an object that looks like
{
key1 : "value1",
key2 : "value2"
}
they will come through to php as
$_POST['key1'];//"value1";
$_POST['key2'];//"value2";
important to note, files posted to the server are typically found in the $_FILES superglobal. (don't know if AJAX changes that, but I imagine not)
EDIT2
Combining the two... this is the general idea. Make your html + JS look like...
$('#form').on('submit', function()
{
var form_data = new FormData();
form_data.append("file", document.getElementById('fileInput').files[0]);
var booking = $('#bookingNum').val();
var partner = $('#partnerCode').val();
form_data.append("booking ",booking);
form_data.append("partner",partner);
$.ajax({
url: 'process/customer.php',
method:"POST",
data: form_data,
contentType: false,
cache: false,
processData: false,
success: function(data)
{
console.log(data);
},
error: function(jqHHR, textStatus, errorThrown)
{
console.log('fail: ' + errorThrown);
}
});
return false;//prevent default form submission
});
<form id='form'>
<input type='file' id='fileInput' />
<label for='bookingNum'>Booking Num: </label>
<input type='text' id='bookingNum' name='bookingNum' />
<label for='partnerCode'>Partner Code:</label>
<input type='text' id='partnerCode' name='partnerCode' />
<button id='uploadBtn'>Submit</button>
</form>
and try it with your php code like
<?php
if($_POST['bookingNum']){
var_dump($_POST['bookingNum']);
}
if($_POST['partnerCode']){
var_dump($_POST['partnerCode']);
}
if($_FILES['file']){
var_dump($_FILES['file']);
}
$('#uploadBtn').on('click', function()
{
var form_data = new FormData();
form_data.append("file", document.getElementById('ID').files[0]);
var booking = $('#bookingNum').val();
var partner = $('#partnerCode').val();
form_data.append("booking ",booking);
form_data.append("partner",partner);
$.ajax({
url: 'process/customer.php',
method:"POST",
data: form_data,
contentType: false,
cache: false,
processData: false,
success: function(data)
{
console.log(data);
},
error: function(jqHHR, textStatus, errorThrown)
{
console.log('fail: ' + errorThrown);
}
});
});

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

Jquery ajax call a php script with require once

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",
.....

passing variable back from the server to ajax success

User fills input texts, presses the button Submit. The data sends to the server to be stored and result returned back. Fancybox window with result appears. My question is: how to display the result $res1 in the fancybox?
$.ajax({
type:"POST",
url:"index/success",
async:false,
data:{ name:name, password:password},
success:function ()
{
var html='$res1 from the server should be here instead of this string';//var html=$res1.
$.fancybox(
{
content: html,//fancybox with content will be displayed on success resul of ajax
padding:15,
}
);
}
});
=========================
OK, still doesn't work (returns in the fancybox the whole page+ the word "hello" on top instead of the message "hello"). Below is my update regarding the answers below, that doesn't work properly:
PHP:
<?php
$res1="hello";... // handle logic here
echo $res1; // print $res1 value. I want to display "hello" in the fancybox.
?>
AJAX
$.ajax({
type: "POST",
url: "index/success",
async: false,
data: {
name: name,
password: password
},
success: function (html) {
$.fancybox(
{
content: html,//returns hello+page in the fancybox
//if I use the string below instead of the upper one, the fancybox shows "The requested content cannot be loaded. Please try again later."
// content: console.log(html)
padding:15,
}
});
=============
New update:
Fixed!!! The problem was the data ( "hello" in the example above) was sent to the template in the framework, and template was displayed.
That's why.
Fixed.
Thank you.
Everybody.
Assuming you're using PHP:
PHP:
<?php
... // handle logic here
echo $res1; // print $res1 value
?>
AJAX:
$.ajax({
type: "POST",
url: "index/success",
async: false,
data: {
name: name,
password: password
},
success: function (html) {
// given that you print $res1 in the backend file,
// html will contain $res1, so use var html to handle
// your fancybox operation
console.log(html);
}
});
Enjoy and good luck!
$.ajax({
type:"POST",
url:"index/success",
async:false,
data:{ name:name, password:password},
success:function(html){ // <------- you need an argument for this function
// html will contain all data returned from your backend.
console.log(html);
}
});

Categories

Resources