AJAX Post Successful but PHP not responding - javascript

I'm having trouble with an AJAX POST to PHP call.
JS in an PHP file (tableOutput.php)
var changedArr=[];
var undoRedoArr=[];
//For editing data, http://tabulator.info/docs/3.3
$("#tabulator").tabulator({
cellEdited:function(cell){
//this is called whenever a cell's value is edited.
var value = cell.getValue();
var theID = cell.getRow().getIndex();
var ip=cell.getRow().getData();
var field = cell.getField();
var x=Object.values(ip);
console.log(ip);
changedArr.push(x);
},
});
//called when I hit a button
function saveChanges(){
$.ajax({
url: "getInfo.php/",
type:'POST',
data: {'ipString':changedArr},
success: function(){
alert("SAVED!");
},
error: function(XMLHttpRequest, textStatus, error){
alert("AJAX error: " + textStatus + "; " + error);
}
})
console.log(changedArr);
}
</script>
<?php
include "getInfo.php";
?>
PHP code in a different file (getInfo.php)
<?php
if(!empty($_POST['ipString'])){
echo '<script language="javascript">';
echo 'alert("Post")';
echo '</script>';
}
if(!empty($_REQUEST['ipString'])){
echo '<script language="javascript">';
echo 'alert("Request")';
echo '</script>';
}
?>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
</html>
Earlier in the files, I have a GET command that works.
HTML in tableOutput.php
<div class=form>
<form onsubmit="fillTable()" >
<input type="submit" name="deny" value="Denied" />
<input type="submit" name="permit" value="Permitted" />
</form>
</div>
getInfo.php
$test="'CREATE'";
if( isset( $_GET['deny'] )){
$test="'DENY'";
}
if( isset( $_GET['permit'] )){
$test="'CREATE'";
}
Tried on Fedora and Windows. Code is on a server. Browser: Firefox
The Ajax posts successfully. I get an alert box saving "SAVED!", but nothing echos on the page. If I use window.location.href instead, then the getInfo.php echos to the page. The problem is that I get redirected to the getInfo.php page, which I don't want.
How do I get the Ajax to post to the getInfo.php file? Why is it not working?

It looks like you are trying to mix two different mechanisms here (AJAX and post-back). When you use AJAX, simply echo-ing output will not insert that content into the DOM (like it does when using a full post-back). Your echo statement puts data into the output stream that is then consumed by your success function. And it will stay there unless you programmatically (using javascript/jQuery) insert it into the DOM. You can manually insert that into the DOM. There are many ways of doing that. The key is looking at your response object. This is one possibility:
function saveChanges(){
$.ajax({
url: "getInfo.php/",
type:'POST',
data: {'ipString':changedArr},
success: function(response){
alert("SAVED!");
//add the script element to the DOM body
$(response).appendTo('body');
},
error: function(XMLHttpRequest, textStatus, error){
alert("AJAX error: " + textStatus + "; " + error);
}
})
console.log(changedArr);
}

It is important to understand that when including a php file (like getInfo.php), the output is written on the client side and cannot be accessed by php anymore.
What you want is to request the getInfo.php, get its response the write it on the client side.
Client:
<script>
function saveChanges(){
$.ajax({
url: "getInfo.php/",
type:'POST',
data: {'ipString':changedArr},
success: function(textResponse /* you MUST use this parameter*/){
alert("SAVED!");
// textResponse is the string the server sends. do whatever you want with this
document.getELementById("out").innerHTML = textResponse;
},
error: function(XMLHttpRequest, textStatus, error){
alert("AJAX error: " + textStatus + "; " + error);
}
})
console.log(changedArr);
}
</script>
<div id="out"></div>
At the server side, it is important you do not include any <head> or <body> tags, otherwise you will have a new document inside your <div id="out"></div>! You should write just pure text, or something that can be put inside a div element, like a table.
Server: getInfo.php
<?php
if (isset($_POST['ipString'])) {
echo "A request has been made";
}
?>
or write pure html closing the php tags (a nice trick):
<?php
if (isset($_POST['ipString'])) {
?>
A request has been made
<?php
}
?>
If your getInfo.php file needs to have its <head> and <body> tags, you must exit() the script so the rest of the file will not be sent.
<?php
if (isset($_POST['ipString'])) {
echo "A request has been made";
exit(); // exit here so ajax doesn't get the rest of the file
}
?>
<html>
<head></head>
<body></body>
</html>
Finally, if you want to be flexible and have your client do stuff based on what the server sends, you should try JSON which converts objects to strings and vice versa.

The problem was not with the code posted.
At the beginning of getInfo.php, I forgot to add "php"
It was:
<?
instead of:
<?php

Related

Send image from php server using ajax call

The short of what I'm trying to do is search for a file and display a picture from the server. The HTML has a simple search bar that allows you to type in a search term. The JavaScript uses an ajax request to call the PHP file, and the PHP finds the image on the server and sends it back to be displayed.
What happens right now is that the image isn't displayed, and I get an icon indicating some invalid image. The ajax call appears to be working, but I think the data I'm sending back isn't correct. I've been trying to search for it but everyone seems to have a different opinion on how to do it and it's kind of confusing.
HTML
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script>
<script src="search.js"></script>
<style type="text/css"></style>
</head>
</body>
<header>
<h1>My Page</h1>
</header>
<input type=text name="search" id="searchbox" placeholder="Search...">
<input type=button value="Search" id=search><br>
<div id="images"></div>
</body>
JavaScript
$(document).ready(function() {
$("#search").on('click', function(){
$.ajax({
url: '/search.php',
type: 'POST',
data: $("#searchbox").serialize(),
success: function(data) {
$('#images').append(data);
},
error: function() {
alert('failure');
}
});
});
});
PHP
<?php
if(isset($_POST['search'])) {
$searchterm = $_POST['search'];
$image = "images/".$searchterm.".jpeg";
echo '<img src="data:image/jpeg;base64,'.base64_encode($image).'">';
}
else {
echo 'Error: image not found';
}
PS. For the moment, I'm ignoring any sort of error checking, I'm just trying to get it working and assuming the input is all valid
SUGGESTIONS:
Try this link:
Image Data URIs with PHP
<?php
if(isset($_POST['search'])) {
$searchterm = $_POST['search'];
$image = "images/".$searchterm."jpeg";
$imageData = base64_encode(file_get_contents($image));
$src = 'data: '.mime_content_type($image).';base64,'.$imageData;
echo '<img src="', $src, '">';
...
Debug the actual HTTP traffic between your jQuery/Browser and your PHP/back-end server. You can use a tool like Telerek Fiddler or Firebug, among many others.
'Hope that helps!
Use file_get_contents it will display the image on browser.
$image = "images/".$searchterm.".jpeg";
echo '<img src="data:image/jpeg;base64,'.base64_encode(file_get_contents($image)).'">';
Please change the url property in the object, used in your .ajax() method call. The path to your search.php is incorrect.
$.ajax({
url: '/search.php',
goes to:
$.ajax({
url: './search.php',

How to echo javascript into current html page from external php file

Let's say I'm currently browsing mypage.html, which in its header has a link to the following js file:
<script language="JavaScript" type="text/javascript" src="jsfile.js"></script>
In jsfile.js, there's a function keyup() that is executed when the user types something into #searchbar, whose value is then stored in search = $(#searchbar).val();
I then pass this value on to search.php as follows:
$.post( "search.php", { searchval: search }, function(sentdata){
console.log(sentdata);
});
where the content of search.php reads:
<?php
if(isset($_POST[searchval])){
$search = $_POST[searchval];
echo "input value is $search";
echo "<script type='text/javascript'> alert('its working') </script> ";
}
?>
However, instead of an alert pop up (or anything else that would normally be executed in JS), the second echo simply prints " alert('its working') " into the console.
How can I modify search.php to allow it to inject actual js into myfile.html? Note that I've also tried wrapping the js code in tag.
Related question: why is it that when I omit console.log(sentdata), search.php does no longer echo anything into the console?
How I can modify search.php to allow it to inject actual js in myfile.html?
First of all, you need to modify your javascript file:
$.post( "search.php", { searchval: search }, function(sentdata){
eval(sentdata);
});
And no need for javascript tags, just echo a valid Javascript code:
if(isset($_POST[searchval])){
echo "alert('its working');";
}
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/eval
you can do this
$.post( "search.php", { searchval: search }, function(data){
alert(data); // this will alert the data which will print on search.php
});
and in the php file echo the data you want to print like
if(isset($_POST[searchval])){
echo 'its working. i got'.$_POST[searchval];
}

Using AJAX to check variables in database, if true, header to a certain page, PHP, JAVASCRIPT

I'm trying to use AJAX to check variables in the database, and if it's true, then it should make it header to a certain page, except in this testing phrase, I'm not checking any variables. I'm just testing if it'll header off to that certain page if I call the function. I started at test1.php, but it should've called the ajax function, and immediately header off to test3.php, but it didn't. I'm not sure what I did wrong. Please take a look:
ajax.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
function nopassAjax(url,timeout) {
$.ajax({
type: "POST",
url: url,
error: function(xhr,status,error){alert(error);},
success:function(data) {
setTimeout(function() { timeoutAjax(url,timeout); }, timeout);
}
});
}
</script>
test1.php
<?php
include('ajax.php');
echo "<script>";
echo "nopassAjax('test2.php',1000);";
echo "</script>";
?>
test2.php
<?php
//checks some stuff in the database
//if true, header off to test3.php
header("Location: test3.php");
?>
test3.php
<?php
echo "Hello";
?>
From your question I'm assuming you want to redirect to the page that's returned from your AJAX call. You can't do this from PHP alone.
Javascript:
$.ajax({
method: "POST",
url: someUrl
}).fail( function( error ) {
alert( error );
}).done( function( response ) {
window.location = response;
});
PHP:
<?php
echo "test3.php";
?>

AJAX PHP function onchange select box

I have a problem about which I am very confused. I have a select box with s dynamically generated using a mysqli query:
$result = mysqli_query($db, "SELECT * FROM `users` WHERE `user_id` > 0");
echo '<html><form name="contacts" method="post"><select name="contacts"><option value="Contact list" onchange="func()">Contact List</option>';
while($row = $result->fetch_assoc()){
echo '<option value = '.$row['user_name'].'>'.$row['user_name'] . '</option>';
}
echo '</select></form>';
I am completely new to AJAX, but I need to use jquery and ajax to pass the this.value variable to a php variable for use in a later query.
Here is my script (most of which was found online):
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
$("#contacts").change(function() {
//get the selected value
var selectedValue = this.value;
//make the ajax call
$.ajax({
url: 'function.php',
type: 'POST',
data: {option : selectedValue},
success: function() {
console.log("Data sent!");
}
});
});
</script>
Now, when I click a value in the select box, nothing happens. There are no warnings or errors, etc.
Please help me.
p.s. function.php does exist. It is just a simple echo for now (for testing purposes)
UPDATE: HERE IS FUNCION.PHP:
<?php
/*$val = $_REQUEST['selectedValue'];
echo $val;*/
function function(){
$val = $_REQUEST['selectedValue'];
echo $val;
}
?>
UPDATE: Thank you everyone for all your help. I have now got it to work in that the network section of chrome inspect shows the function.php being requested however I still don't get the echo (I used external .js files to get it to work). My J query function is also successful (the success function echoes into the console)
Your select box has no ID and you are watching the change event of $("#contacts").
Change:
echo '<html><form name="contacts" method="post"><select name="contacts"><option value="Contact list" onchange="func()">Contact List</option>';
to:
echo '<html><form name="contacts" method="post"><select name="contacts" id="contacts"><option value="Contact list">Contact List</option>';
^^^^^^^^^^^^^ here
You also only need one event handler, so I have removed the inline one which doesn't seem to do anything anyway.
Edit: If the select is created using ajax as well, you need event delegation:
$("body").on('change', '#contacts', function() {
^^^^ for example
Edit 2: Your variable is called $_REQUEST['option'] and not $_REQUEST['selectedValue']. You are also not calling your -badly named - function so you will not get any output from php except from an error like Parse error: syntax error, unexpected 'function' ....
Call onchange function in select tag as below
echo '<form name="contacts" method="post"><select name="contacts" onchange="func(this.value)"><option value="Contact list">Contact List</option></form>';
Javascript src should be in head of the html page.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
Add the above one in head of html. Update javacript as below
As onchange function is called in the select tag itself, following is enough
<script>
function func(selectedValue)
{
//make the ajax call
$.ajax({
url: 'function.php',
type: 'POST',
data: {option : selectedValue},
success: function() {
console.log("Data sent!");
}
});
}
</script>
Updated php: If you must want to get value from function, you must call it. Otherwise, simply, you can make as below
<?php
if($_REQUEST['option'])
{
$val=$_REQUEST['option'];
echo $val;
}
?>
In .php file, receive it first-
$val = $_REQUEST['selectedValue'];
echo $val;
set an id attribute in your php code for the select tag and
please don't use the same value for the name attribute in form and select tags !!
just change your function to a 'body'.on, and give your elements an id of 'contacts'
$("body").on('change', '#contacts', function() {
//get the selected value
var selectedValue = $(this).val();
//make the ajax call
$.ajax({
url: 'function.php',
type: 'POST',
data: {option : selectedValue},
success: function() {
console.log("Data sent!");
}
});
});

External PHP data not passing through AJAX

I'm working on creating a simple online booking system using PHP and AJAX.
The current layout is:
Each booking grabs a preset list of items then users can add additional items that they need.
To do this I have set up an AJAX button that calls a new drop down list each time its clicked. (This means a page could have 1 additional item or even 20, depending on how many they need.)
Once the additional items have been selected, they can then submit the form and will be guided to a confirmation page that is meant to list what they have chosen.
The issue:
None of the data is being carried through from any of the drop down lists that get added.
My AJAX script and php code on page 1 is:
<script>
function changeIt()
{
$.ajax({
type: "POST",
url: "details.php"
}).done(function( result ) {
$("#msg1").append( "" +result);
});
}
</script>
<form name ="addequip" id="addequip" action="confirmbooking.php" method="post">
<input type='button' value="Add Item" onClick="changeIt()"/>
<div id="msg1"></div>
<input type='submit' value='submit'/>
details.php:
<?php
require_once("dbconn.php");
$sql = "SELECT REFERENCE, DESCRIPTION FROM descEquip";
$result = mysql_query($sql,$conn);
?>
<select name="equip">
<?php while ($row = mysql_fetch_array($result)) { ?>
<option value="<?php echo $row["REFERENCE"];?>"><?php echo $row["DESCRIPTION"];?></option><?php } ?>
</select>
And lastly my confirmation page is:
<?php $item = $_POST['equip']; ?>
<?php echo $item ?>
I'm not too sure if i need to add something to the AJAX script in order for this to work as intended or if something needs to be changed in the details.php? (I'm very new to AJAX)
I have viewed a previous question 'passing form data to mySQL through AJAX' and I couldn't make it work for me.
Lastly, for additional lists (when more than 1 item is required) do I need to have a feature that states each equip list have a different name? likename="equip<?php echo $i ?> where $i = 1++;
Any tips or examples would be appreciated,
thanks.
Never assume all will work as you want it - check if sth goes wrong in your code:
var jqxhr = $.ajax(
{
type: 'GET',
async: false,
url: 'details.php',
success: function(data, textStatus /* always 'success' */, jqXHR)
{
// ok if we are here it means that communication between browser and apache was successful
alert( 'on_ajax_success data=[' + data + '] status=[' + textStatus + ']' );
$("#msg1").innerHTML( result );
}
,
error: function(jqXHR, textStatus, errorThrown)
{
alert( 'ERROR: [operation failed]' );
}
});
Moreover - use Firefox with Firebug installed so that you can see your ajax queries/responces.

Categories