I have PulsePro as CMS used. The template is on PHP, but the include parts are in HTML. The php mailer contains an Ajax Script, which I have implemented in the layout.php file. I have some different forms with different receiver email addys. Now, I want to define a variable for following string. This variable it will taken from the different include parts, e.g.
Here the link in the include files.
<?php $variable ="ajax1.php"; ?>
This is the ajax code in the layout.php file:
ajaxSubmit = function(){
var frmData = $("#ifgForm").serialize();
$.ajax({
**url: "/includes/ajax.php", This is the original part, but here should be the variable
data: frmData,
type: "POST",
dataType: "json",
success: function(response){
$("#f1_upload_process").hide();
$(".event-submit-btn").show();
Thanks for your support.
You can output the string inside ifgForm like this
<form id="ifgForm">
<!-- [....] -->
<input type="hidden" value="<?=$variable?>" name="variable" id="variable">
<!-- [....] -->
</form>
So u can find in the new variable field with other form fields data
Related
Hello everyone I am new to php.
I have been trying out this thing when a user enter a product name need to validate that the product is valid or not.
For that purpose I have used onchange event when the text is entered.The onchange function will call the javascript function.From javascript function I am calling the php which is in the same file.So when I am entering the product name somehow the php function is not working.
Here is my code :
<?php
include 'conf.php';//it contains the php database configuration
session_start();
$quantityRequired=0;
$productName_error="";
if(is_ajax()){
if(isset($_POST["productName"])){
$productName=$_POST["productName"];
$row=mysqli_query($conn,"SELECT * from OrderDetails where ProductName='".$productName."'");
if($row)
{
$result=mysqli_fetch_assoc($row);
$quantityRequired=$result["Quantity"];
}
else
{
$productName_error="The product name is not valid or product does not exist";
echo $productName_error;
}
}
}
function is_ajax() {
$flag=(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
return $flag;
}
?>
<html>
<head>
<title>Order Page </title>
<script type = "text/javascript"
src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
<label for="userName">Username</label><br>
Product Name<input type="text" name="productName" id="productName" onchange="validateProduct()"><?php echo $productName_error?><br>
Quantity Required<input type="text" name="quantityRequired" id="quantityRequired"><br>
Availability<input type="text" name="availability">
<p id="demo"></p>
</form>
<script>
function validateProduct()
{
$.ajax({
type: "POST"
});
}
</script>
</body>
</html>
so the code is when the user enters the product name.The function validate product is called.From validate product it will call the php which is in the same file. is_ajax() function is used to check whether it is the ajax request or not.
A PHP library for Ajax
Jaxon is an open source PHP library for easily creating Ajax web applications. It allows into a web page to make direct Ajax calls to PHP classes that will in turn update its content, without reloading the entire page.
Jaxon implements a complete set of PHP functions to define the contents and properties of the web page. Several plugins exist to extend its functionalities and provide integration with various PHP frameworks and CMS.
How does Jaxon work
Define and register your PHP classes with Jaxon.
$jaxon->register(Jaxon::CALLABLE_OBJECT, new MyClass);
Call your classes using the javascript code generated by Jaxon.
<input type="button" onclick="JaxonMyClass.myMethod()" />
check link https://www.jaxon-php.org/docs.html
There may be other problems I haven't spotted, but the first thing that jumps out to me is that your server-side code runs conditionally:
if(isset($_POST["productName"]))
And that condition was never satisfied because you didn't send any values in the AJAX request:
$.ajax({
type: "POST"
});
Send the value(s) you're looking for:
$.ajax({
type: "POST",
data: { productName: $('#productName').val() }
});
You may also need to specify a couple other options if they don't default correctly. Explicit code is generally better than implicit in many cases:
$.ajax({
url: 'yourUrl.php',
type: "POST",
dataType: 'html',
data: { productName: $('#productName').val() }
});
In general you'll probably want to check the documentation for $.ajax() and see what you can and should tell it. You'll also want to take a look at your browser's debugging tools to see more specifically why and how it fails when testing these things.
Speaking of things you should do, you should read this and this. Your code is wide open to SQL injection attacks at the moment, which basically means that you are executing as code anything your users send you.
var data1 = "Something";
$.ajax({
url: "script.php",
type: "POST",
data: { data1: data1 }
}).done(function(resp) {
console.log( resp )
}).fail(function(jqXHR, textStatus) {
alert("Request failed: " + textStatus + " - Please try again.")
})
Here you have a script that will send the data1 variable across to the php script. The resp in the done portion is the return you send back from the php script.
If you want to send more data just add it { data1: data1, data2: data2 } and so on.
Just adjust to suit your needs.
I am trying to UPLOAD multiple file using Post jQuery method but I get an error of undefined index when trying to view the array result. Tried to search the answers but still unable to do it. What is the correct way to do this. Below are the example of my codes,
HTML
<input type="file" name="others[]" multiple="multiple">
jQuery
$(document).ready(function(){
$("#submit").click(function(){
var array = [$("input[name='others']").val()],
others = {
"upload[]": array,
},
id = $("input[name='id']").val();
$.post('updated-file-others.php',
{
others : others,
id : id
}, function(data){
$("#result_post").html(data);
});
});
});
PHP
if(isset($_POST['id'])){
$id = $_POST['id'];
$others = array($_FILES['upload']['name']);
}
echo "<pre>"; print_r($others); echo "</pre>";
A couple of things
$("input[name='others']") doesnt match others[] in your HTML. Why dont you use an id and match it?
You might need to ensure that you have
enctype="multipart/form-data" inside your form.
whats the output of $("input[name='id']").val(); You have not provided any clue in your code.
Refer to php documentation on file upload - Uploading multiple files
Refer to this stackoverflow question - Multiple file upload in php
I would suggest formatting your desired array as a JSON string, and then using php_decode to convert it to an array.
$json = '["apple","orange","banana","strawberry"]';
$ar = json_decode($json);
echo $ar[0]; // apple
More info about JSON with PHP can be found here:
http://www.dyn-web.com/tutorials/php-js/json/decode.php
The file upload via ajax using $.post doesn't work this way, to achieve this, you must configure the ajax call as follows:
$.ajax({
type: 'POST',
url: your_url,
data: new FormData($('#form-id').get(0)),
processData: false, //set it to false to send a DOMDocument, or other non-processed data
contentType: false //pass false to tell jQuery to not set any content type header
}).done(function (data) {
alert('success');
})
This will send you the entire form to the server, and there you can process the files and other fields as you want.
You can read a little more about the processData and contentType configuration in the jQuery ajax documentation
Please let us know if this work for you,
Greetings
I have this piece of code in PHP (path: ../wp-content/plugins/freework/fw-freework.php)
<div id="new-concept-form">
<form method="post" action="../wp-admin/admin.php?page=FreeWorkSlug" class="form-inline" role="form" onsubmit="addNewConcept()">
<div class="form-group">
<label for="new_concept_text">Nuovo concetto:</label>
<input type="text" class="form-control" id="new_concept_text">
</div>
<div class="form-group">
<label for="new_concept_lang">Lingua:</label>
<select class="form-control" id="new_concept_lang">
<option>it</option>
<option>en</option>
<option>de</option>
<option>fr</option>
</select>
</div>
<button type="submit" class="button-aggiungi btn btn-default">Aggiungi</button>
</form>
</div>
When the button is pressed, this javascript is called (it works as the alert is showed and the data is retrieved correctly):
var ajaxphp = '../wp-content/plugins/freework/fw-ajaxphp.php';
function addNewConcept()
{
conceptName = document.getElementById('new_concept_text').value;
lang = document.getElementById('new_concept_lang').value;
alert('Inserting: ' + conceptName + " " + lang);
$.ajax({
type: 'POST',
url: ajaxphp,
async: true,
dataType: 'json',
data: {conceptNm : conceptName, conceptLang : lang },
success: function() {
alert("-------------------------------- Data sent!!");
console.log("-------------------------------- Data sent!!");
}
});
return true;
}
Now, as you can see in the javascript, I would like to call another PHP file through ajax ( the alert and the console.log in the success function are not called / can't be reached).
<?php
// HTML Page -> JavaScript -> fw-ajaxphp.php -> XML Vocabulary
echo 'alert("PHP called")';
// echo $_POST['conceptNm'];
// TODO change vocab when done testing
$xml_file = '../wp-content/plugins/freework/fw-custom-vocabulary-test.xml';
$xml_vocab = new DOMDocument;
if (isset($_POST['conceptNm']) && isset($_POST['conceptLang']))
{
// ADD NEW CONCEPT
echo 'alert("PHP chiamato")';
// irrelevant business code here...
echo 'alert("Modifica avvenuta")';
}
?>
JQuery/Bootstrapp ecc... are all included both in the master html file and in the HTML-generator PHP file (work correctly).
Yet, I can't seem to call this php file which holds all the server logic as response to the button. The business code is irrelevent, as the button trigger hould at least call the alert outside of the if condition.
I have followed all answers on stack-overflow relative to this issue, yet it's not working. I also tried to add the full path to the variables but nothing. As you can see, all my files are in this folder: Files on Server.
So why can't I call that server-side PHP script?
Thank you.
EDIT: I solved this by using a completely new approach! I leave jQuery away, I will recharge the page everytime someone submits the form and I will retrieve the data throught POST in the very same file that generates the HTML. Why coulnd't I call the server from javascript? Frankly I don't know. In other cases it has always worked. Thank you all anyway.
This is your problem:
$.ajax({
type: 'POST',
url: ajaxphp,
async: true,
dataType: 'json',
^^^^^^^^^^^^^^^^ Wrong data type
Then you do:
<?php
// HTML Page -> JavaScript -> fw-ajaxphp.php -> XML Vocabulary
echo 'alert("PHP called")';
...
You are specifying that the returned data type is json. However, in your php script you are echoing strings so your ajax call will fail as jQuery cannot parse the returned data as json.
Removing the dataType line should solve your problem but note that then you cannot use the returned data as an object. But that should not matter in this specific example as you are not using the returned data at all.
I want to know whether I can retrieve data from database in .js file using php code written in same .js file. I have a passwordvalidation.js file. In that file, by using onblur event or onclick event, I want to compare the password values with the stored value in password. Now I have password verification code in php and I can compare passwords using that function. But I want to compare it while user entering new password in field. And I want to write ajax and php code in same .js file. But I don't know how to achieve that. Please help on this. Thank you.
use jquery
$.ajax({
url: 'test.php',
success: function(data) {
$('.result').html(data);
}
});
If you want to use any value which is assigned to any PHP variable, use a hidden input type, set php variable in it and call the value from js function
<input type="hidden" id="my_value" value="<?php echo $myvar; ?>" />
In js function
var phpval = document.getElementById("my_value").value;
Now you can retrive the PHP variable value inside JS function ( var phpval)
I have a editor embeded in the html page
<div id="editor">
Problem Statement goes hereā¦
</div>
I basically want to store the contents written in editor to a file(preferably in rich text format). I used a script (given below) for storing the contents in a string.(This I used by referring to HTML div text to save and display )
<script type='text/javascript' src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
var StoreEditorContent; //declare a variable to save Content
document.getElementById('save').addEventListener("click", SaveText); // adding event listner for onclick for Saving text
function SaveText(){
StoreEditorContent = document.getElementById('editor').innerHTML; // Save the Content into
document.getElementById('editor').innerHTML = ""; // to blank the editor Content
window.onload = function(){
$.ajax({
url: "submit_request.php",
type: "GET",
success: function writeMsg(StoreEditorContent){
//Not sure if this part is right.
}
});
}
}
</script>
This of course is storing in the contents in a string StoreEditorContent. I now want to pass this string to a php function which will write this(StoreEditorContent) to a file.The php file that contains function to write is given below
<?php
function writeMsg($msg){
$file = "myfile.txt";
file_put_contents($file, $msg);
}
?>
I know I need to use ajax here, but cannot figure out how? Any help appreciated.
You need to provide a data: option to $.ajax():
$.ajax({
url: "submit_request.php",
type: "POST",
data: { content: StoreEditorContent },
success: function (response) {
// Do something with the response sent from PHP
}
});
Then your PHP can do:
writeMsg($_POST['content']);
You should use POST rather than GET for large requests because the limit on GET parameters is relatively small.