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];
}
Related
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
I have a list from the database and I want to implement edit functionality where in onclicking a table column, the column becomes editable and on clicking out of column, the value gets updated.
I have used AJAX for this purpose. My code is as under:
Page1.php
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>
function showEdit(editableObj)
{
$(editableObj).css("background","#FFF");
}
function saveToDB(editableObj,column,id)
{
$.ajax(
{
url: "page2.php",
type: "POST",
data:'column='+column+'&editval='+editableObj.innerHTML+'&id='+id,
success: function(data)
{
$(editableObj).css("background","#FDFDFD");
}
});
}
</script>
The column of my table is as under:
<td contenteditable="true" onBlur="saveToDB(this, 'exmid','<?php echo $p0; ?>')"
onClick="showEdit(this);"><?php echo $p3 ?>
Note: $p0 contains the serial no of row from mysql database table and $p3 contains the displayed text.
The code for page2.php is:
<?php
include_once 'includes/db_connect.php';
?>
<?php
$result = mysql_query("UPDATE examlist1 set " . $_POST["column"] . " = '".$_POST["editval"]."' WHERE sno=".$_POST["id"]);
?>
Problem:
When I click on the column it becomes editable. Using alert() inside saveToDB() I have checked that the function is called on clicking out of the column and also values of column and id are correct.
Then I tried the alert() function inside $.ajax and it was not called. I am not sure whether ajax is running or not. This is the first time I am trying to use ajax in a php code myself.
Please suggest what is the problem and what is the solution? The code is being implemented on a Linux based server hosted at Godaddy using PHP 5.4.
Also I would like to set the background color on fail. How to write it inside ajax block?
If you are getting the correct values when alerting.In your page2.php. Use mysqli instead of mysql and also use $connection object in mysqli_query().
<?php
include_once 'includes/db_connect.php';
$column=$_POST["column"];
$editval=$_POST["editval"];
$id=$_POST["id"];
$result = mysqli_query($connection,"UPDATE examlist1 SET $column='$editval' WHERE sno=$id");//$connection is database connection variable
if ($result)
{
echo json_encode(array('success'=>true));
}
else
{
echo json_encode(array('success'=>false));
}
?>
Here is Javascript: Try 100% works (Define what you want on if/else statement)
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>
function showEdit(editableObj)
{
$(editableObj).css("background","#FFF");
}
function saveToDB(editableObj,column,id)
{
$.ajax(
{
url: "page2.php",
type: "POST",
data:'column='+column+'&editval='+editableObj.innerHTML+'&id='+id,
success: function(data)
{
var res=eval(data);
//if success then
if (res.success)
{
//write JS code that you want after successful updation
$(editableObj).css("background","#FDFDFD"); //<- according to problem
}
//if fails then
else
{
//write JS code that you want after unsuccess
}
}
});
}
</script>
I have the following script in a HTML file that is called when the document is loaded:
<script>
$(document).ready(function(){
setInterval(function() {
$.get('check_session.php', function(data) {
alert('Load was performed.');
});
}, 5000);
});
</script>
The alert message will be called on the interval, but the PHP is not actually called because nothing is echoed.
PHP file: check_session.php
<?php
//check_session.php
session_start();
echo '<script language="javascript">';
echo 'alert("successful")';
echo '</script>';
echo $_SESSION['user_token'];
if(isset($_SESSION['user_token']))
{
echo '0'; //session not expired
}
else
{
echo '1'; //session expired
}
?>
Essentially, I am trying to call the PHP file, check_session.php, on a five second interval. This is one of my first times implementing jQuery, and after much research, I am still lost.
Any suggestions as to why the php file is not called are appreciated.
---UPDATE:
From Network tab:
Check data parameter
<script>
$(document).ready(function(){
setInterval(function() {
$.get('check_session.php', function(data) {
alert('Load was performed.');
console.log('data: '+data)
});
}, 5000);
});
</script>
the problem might be here: $.get needs URL and other optional params. you are simply giving filename. I think you should add appropriate path also. try it !!
I have function frm_trigger_entry_update this is the php function which is run in background i mean this is ajax php function.
In this function i have write some jquery or javascript function which will alert some text message.
In bellow snippet code you can see my function code.
<?php
function frm_trigger_entry_update($atts)
{
//here i have some php code which run properly
}
?>
I have tried bellow snippet logic but its not work for me mean the alert box is not showing after calling this function.
<?php
function frm_trigger_entry_update($atts)
{
//here i have some php code which run properly
?>
<script>
jQuery(document).ready(function($){
alert("my message");
});
</script>
<?php
}
?>
So how can alert the box in this php function any one have any idea.
Use JS and Php Separately.
First ajax call from your JS file:
$.ajax({url: "frm_trigger_entry_update function's Url",
success: function(result) {
alert(result);
}
});
In php Function, from where you should send your message:
function frm_trigger_entry_update($atts) {
echo "my message";
}
Consider following is your ajax call
$.ajax({url: "URL to frm_trigger_entry_update",
success: function(result)
{
alert(result);
}
});
Your PHP function
<?php
function frm_trigger_entry_update($atts)
{
echo "my message";
}
?>
Try this:
echo "<script>alert('test');</script>";
Note : The best practice to do this with Ajax because function is in
server side so you should call it to server from Client using Ajax
Create one file eg: "frm_trigger_entry_update.php"
IN "frm_trigger_entry_update.php" put your function
function frm_trigger_entry_update($atts)
{
//here i have some php code which run properly
echo $atts;
}
// Call to that function
frm_trigger_entry_update("ATTRIBUTE_VALUE");
Write Ajax on your HTML
$.ajax({
type: 'get',
url: 'PATH to frm_trigger_entry_update.php',
success: function(data) {
alert(data);
}
});
You will get output Alert as ATTRIBUTE_VALUE
In your php function you need to return the output :
<?php
function frm_trigger_entry_update($atts)
{
return "<script>
jQuery(document).ready(function($){
alert('my message');
});
</script>";
}
And then where you want to apply this script you can display the output of your function :
<?php
...
$script = frm_trigger_entry_update($ats);
echo $script;
However in my opinion, this is not a good practice, you should put your javascript in a js function, in a js file and include your js file in your document or call it when needed.
Calling a php function via ajax is really impossible because ajax uses a url for php file and not a php function.
Though your code works and will alert if you call it via php.The code below will alert what ever string you put in the parameter of your function.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<?php
function frm_trigger_entry_update($atts)
{
//here i have some php code which run properly
?>
<script>
jQuery(document).ready(function($){
alert("<?php echo $atts;?>");
});
</script>
<?php
}
//calling the function and passing a simple string
frm_trigger_entry_update("Alert Message");
?>
</body>
</html>
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!");
}
});
});