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.
Related
I have my form defined as follows in the PHP file (Using jquery-2.1.4.min.js) :
<form id = "testForm" action="" method="post" >
First name: <input type="text" name="FirstName" id="FirstName" value="Mickey"><br>
Last name: <input type="text" name="LastName" id="LastName" value="Mouse"><br>
<button type = "button" onclick="submit()">Submit Top Test </button>
</form>
The following functions is called when the button is clicked.
function submit(){
var firstName = $('#FirstName').val();
alert("Inside SubmitQuery "+firstName);// Work fine
var request = $.ajax({
url: 'php/<path to php file>/processPost.php',
type:'POST',
data:{title:firstName},
success: function(msg) {
alert(msg);// I can see the var_dumps here
}
});
}
In processPost.php file, I have defined the following two var_dumps :
1) var_dump(isset($_POST['title']));
2) var_dump ($_POST['title']);
I can see the values getting printed in the alert(msg) window. Same is true in the Response tab of the Network tab of developers tools window. But I want to have these variables
available in the processPost.php file so that I could use it to make a curl request to webservice call. Is it possible to get these variables inside processPost.php file?
I mean, you basically answered your own question in your question. The fact that you have this file:
processPost.php:
<?php
var_dump( $_POST['title'] );
?>
and your success: function(msg){ alert(msg); } is properly alerting "Coder" (or whatever name you submit) Literally means that the variable $_POST['title'] is available in your processPost.php file. If alert(msg) gave you nothing, or an error, then you'd know something is wrong.
success: function(msg) means that, if successful, take the output value from your url (in this case, processPost.php), and make it available to your javascript as a variable named msg.
Yes, and you already have it.
Look closer at what's happening here. You are making an Ajax request to a php file. That file processes the $_POST variable and outputs it using var_dump(). Since the came from jQuery, the response goes back to jQuery. You have used an alert() to display that message.
In your php script, you can use $_POST['title'] to create your curl request.
Please be careful that you sanitize or validate your input so you don't create an injection hole. Don't take user input and run it directly.
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.
Hi I'm new to php and jquery. Pardon my php vocabulary.
I have two events in my js file.
1) onsubmit: submits the user entered text to result.php which queries database and displays result. (result.php?name=xyz)
2) onkeyup: makes an ajax call to the same result.php which queries a url and gets json data. (result.php?key=xyz)
My question is if I can check for isset($_GET['key']) in result.php, query url and return json and the rest of the php is not parsed.
Basically is there anything like return 0 as in case of C programming.
The question may seem silly, anyway I can have 2 different php files, but I want to know if it's possible.
Thanks in advance :)
<form action = "result.php" method = "get">
<input type = "text" id = "name" >
<input type = " submit">
</form>
<script>
$('#name').on('keyup',function (e){
input_val = $(this).val();
$.ajax({
url: "result.php?key=" + input_val,
success: function(data){
alert(data);
}
});
});
</script>
If I well understand, you want to know a way to use only one PHP script being able to process either Ajax and "normal" (returning whole page) tasks.
So if yes, this can be easily achieve, using the following schema:
//... some initialization, if needed
if (isset($_GET['key'])) {
// ... do the job for creating the expected Ajax response, say $ajax_response
echo $ajax_response;
exit;
// nothing else will happen in the current script execution
}
// otherwhise you can do all "normal" job here, as usual...
From your question if i have understood properly , you want to return boolean from PHP to Ajax , you can just echo "success" or "failure" based on if condition , and catch that in ajax response and process it in JS.
You can use exit; or die(); to terminate php script. http://php.net/manual/en/function.exit.php
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
I'm a struggling learner of php and javascript and Have been searching frantically for a solutionbut to no avail. I am trying to send a json object/string from one page to another using php and then echo the results in that new page (eventually to generate a pdf using tcppdf) . So basically some javascript generates an object, pageStructure, in one page, which I then stringify:
var jsonString = JSON.stringify(pageStructure);
alert(jsonString);`
The alert pops up fine.
I now want to send (post) this to another php file getdata.php and then play around with it to construct a pdf.
I have tried posting with forms but updating the value of an input in the form with jsonString won't work.
**ADDITION - EXPLANATION OF MY PROBLEM HERE
I created a form as follows:
<form action="getdata.php" method="post">
<textarea type="hidden" id="printMatter" name="printMatter" value=""></textarea>
<button type="submit"><span class="glyphicon glyphicon-eye-open" ></span></button>
</form>
I have some code after constructing jsonString to set the value of the textarea to that value:
document.getElementById('printMatter').value = jsonString;
alert(document.getElementById('printMatter').value);
A submit button activates the form which opens the getdata.php page but I noticed two things:
(1) before sending the jsonString string is full of escapes () before every quote mark (").
(2) when getdata.php opens, the echoed jsonString has changed to include no \s but instead one of the values ('value') of an object in the json string (a piece of svg code including numerous \s) - for example (truncated because the value is a very long svg string, but this gives the idea):
{"type":"chartSVG","value":"<g transform=\"translate(168.33333333333334,75)\" class=\"arc\">...
has changed to integers - for example:
{"type":"chartSVG","value":"12"}
I don't understand how or why this happens and what to do to get the full svg code to be maintained after the form is posted.
**
I have tried using jquery/ajax as follows:
$.ajax({
url: 'getdata.php',
type: 'post',
data: {printMatter: jsonString},
success: function(){
alert('it worked');
},
error: function(){
alert('it failed')}
})
I'm getting the success response but I end up on the same page instead of getting the new php file to just echo what it is being sent!
The php script contains the following:
<?php
echo $_POST['printMatter'];
?>
But this doesn't work. Nor does trying to add a header to the php page (e.g. header('Content: application/json'). I end up staying on my original page. How do I get this to leave me on the new page (getdata.php) with an echo of the json string?
Can anyone explain what I am doing wrong or how I can get what I want?
Thank you so much.
**ADDITION
This is indicative of how I get the jsonString object:
function item(type,value) {
this.type = type;
this.value = value;
}
for (i=0;i<thePage[0].length;i++) {
pageid = thePage[0][i].id;
var entry = new item("page",pageid);
pageStructure.push(entry);
}
var jsonString = JSON.stringify(pageStructure);
So I end up with a series of pages listed out in the jsonString.
Try changing $_POST to $_GET since your AJAX request is doing a HTTP GET and not a HTTP POST.
UPDATE
This doesn't leave me on the page I want to be on. I don't want to refresh the page but just redirect to a new page that receives the posted json data.
By this is essentially a page "refresh", though perhaps "refresh mislead you because it can imply reloading the current URL. What i meant by refresh was a completely new page load. Which is essentially what you are asking for. There are a few ways to go about this...
If you data is pretty short and will not violate the maximum length for a URI on the webserver then you can jsut use window.location:
// send it as json like you are currently trying to do
window.location = 'getdata.php?printMatter=' + encodeURIComponent(jsonString);
// OR send it with typical url-encoded data and dont use JSON
window.location = 'getdata.php?' + $.serialize(pageStructure);
In this case you would use $_GET['printMatter'] to access the data as opposed to $_POST['printMatter'].
If the data has the potential to produce a long string then you will need to POST it. This gets a bit trickier since if we want to POST we have to use a form. Using JSON and jQuery that is pretty simple:
var form = '<form action="getdata.php" method="post">'
+ '<input type="hidden" name="printMatter" value="%value%" />'
+ '</form>';
form.replace('$value%', jsonString);
// if you have any visual styles on form that might then you may
// need to also position this off screen with something like
// left: -2000em or what have you
$(form).css({position: 'absolute'})
.appendTo('body')
.submit();
If we wanted to just send this as normal formdata then it would get more complex because we would need to recursively loop over pageStructure and create input elements with the proper name attribute... i wouldn't got that route.
So the final way (but i dont think it would work because it seems like youre tryign to generate a file and have the browser download it) would be to send it over AJAX and have ajax return the next url to go to:
JS
$.ajax({
url: 'getdata.php',
type: 'post',
data: {printMatter: jsonString},
type: 'json',
success: function(data){
window.location = data.redirectUrl;
},
error: function(){
alert('it failed')}
});
getdata.php
// do something with the $_POST['printMatter'] data and then...
$response = array(
'redirectUrl' =>$theUrlToGoTo
);
header('Content-Type: application/json');
print json_encode($response);
You are using AJAX. By nature AJAX will not refresh the page for example if you do this:
$.ajax({
url: 'getdata.php',
type: 'post',
data: {printMatter: jsonString},
success: function(data){
alert('it worked');
alert('You sent this json string: ' + data);
},
error: function(){
alert('it failed')}
});
Also note that i changed your type from 'get' to 'post'... The type set here will in part determine where you can access the data you are sending... if you set it to get then in getdata.php you need to use $_GET, if you set it to post then you should use $_POST.
Now if you actually want a full page refresh as you implied then you would need to do this another way. How you would go about it i cant say because you havent provided enough of an idea of what happens to get your jsonString before sending it.