Let's suppose you're sending data through ajax. The server will process it (PHP) and sends a feedback that you can grab using Complete: function(data) { //WRITE HTML TO DIV $('#somehing').html(data) }
The question is:
is there a way to modify data (edit, delete) before passing it to an html element?
Here's a simple example of what I mean :
//php side
echo 'Invalid email';
echo 'Enter your username';
echo 'fine';
echo 1;
echo 2;
// Jquery and Ajax
$.ajax({
type: 'POST',
url: 'render.php',
data:values,
complete: function(data) {
$('#something').html(data) /* all those messages in php will be printed
into #something including the numbers. how to delete or edit those numbers
from appearing in #something? */
}
});
Try this to remove the numbers like,
complete:function(data){
data=data.replace(/\d+/,''); // Regular expression without quotation marks.
// or you can replace the something text like
// $('#something').text(function(){
// return this.innerText.replace(/\d+/,'');
// });
alert(data);
}
Data is returned as basically just a string the way you say you are doing it "receive it as 'html'" You should be able to use simple javascript to control it right out of the gate, for example the way I do things sometimes is this:
the PHP returns something like:
echo $variable_1 . ":" . $variable_2
Then when I get that as data it is just a string that says
variable 1:variable 2
So what I do next is I separate the variables by the colon
var var1 = data.split(":")[0];
var var2 = data.split(":")[1];
Now, this is just a simple example. I'm not exactly sure what you're returning, but it seems that you're searching for an index of 1 instead of "1". This could make a difference. Try searching for 1 in quotes, this would then be searching through a string.
Related
Originally I wanted to use node.js, but after an entire day of frustration, I switched to using jquery and mySQL. The logins seem to be working, but something is wrong in the way it is handling variables. All I want to do is update the database with two things: score and name. Here is the code I modded for my project in PHP:
<?php
$db = "myDatabaseNameIsCorrect";//Your database name
$dbu = "soIsMyUsername";//Your database username
$dbp = "AndMyPassword";//Your database users' password
$host = "localhost";//MySQL server - usually localhost
$dblink = mysql_connect($host,$dbu,$dbp);
$seldb = mysql_select_db($db);
if(isset($_GET['name']) && isset($_GET['this.score'])){
//Lightly sanitize the GET's to prevent SQL injections and possible XSS attacks
$name = strip_tags(mysql_real_escape_string($_GET['name']));
$score = strip_tags(mysql_real_escape_string($_GET['this.score']));
$sql = mysql_query("INSERT INTO `$db`.`scores` (`id`,`name`,`score`) VALUES ('','$name','$score');");
if($sql){
//The query returned true - now do whatever you like here.
echo 'Your score was saved. Congrats!';
}else{
//The query returned false - you might want to put some sort of error reporting here. Even logging the error to a text file is fine.
echo 'There was a problem saving your score. Please try again later.';
}
}else{
echo 'Your name or score wasnt passed in the request. Make sure you add ?name=NAME_HERE&score=1337 to the tags.';
}
mysql_close($dblink);//Close off the MySQL connection to save resources.
?>
And here is the JS! that runs the PHP:
let gameoverScene = new Phaser.Scene('GameOver');
gameoverScene.create = function(){
this.laughSound=this.sound.add('laughSound')
this.gameW = this.sys.game.config.width;
this.gameH = this.sys.game.config.height;
this.goToTitle=function(){
var name = prompt('Enter your name');
jQuery.ajax({
type: "POST",
url: 'savescores.php?name=' +name +'&score=' + this.score,
dataType: 'text',
data: {functionname: 'add', arguments: [name, this.score]},
success: function (obj, textstatus) {
if( !('error' in obj) ) {
yourVariable = obj.result;
}
else {
console.log(obj.error);
}
}
});
this.scene.start('Title')
};
I also tried changing the data type and that didn't work, but I'm not ruling it out yet as a problem.
Here are links to the project and the database:
www.igglepud.com/DeerDefender/Testing
www.igglepud.com/DeerDefender/Testing/getscores.php
This is the error I get:
gameover.js:20 Uncaught TypeError: Cannot use 'in' operator to search for 'error' in
Your name or score wasnt passed in the request. Make sure you add ?name=NAME_HERE&score=1337 to the tags.
at Object.success (gameover.js:20)
at fire (jquery.js:3268)
at Object.fireWith [as resolveWith] (jquery.js:3398)
at done (jquery.js:9305)
at XMLHttpRequest.<anonymous> (jquery.js:9548)
So, the error you're getting is because, in the JavaScript, obj (or the parameter in obj's position) is a string, not an array.
You can see some examples here of how you can properly check for and catch errors.
Edit:
So, in regards to your question about the score variable.
It's important to note that there are 2 types of variables at play here.
The first one is PHP GET variables. PHP GET variables are set via the following format:
var=value
You can set these variables by calling a PHP script like this:
script.php?var1=value1&var2=value2&var3=value3 // etc...
You can access them like this:
echo $_GET["var1"];
echo $_GET["var2"];
echo $_GET["var3"];
Which produces the result:
value1
value2
value3
The second variable at play is a JavaScript variable. Those can only be accessed in JavaScript. a JavaScript variable means nothing in PHP.
So, let's examine what you're doing from the JavaScript:
url: 'savescores.php?name=' +name +'&score=' + this.score,
For the purpose of explaining let's say name = Chipster, and this.score = 123.
What this code will do is try to open the following file:
savescores.php?name=Chipster&score=123
Remembering that PHP GET variables are set by the format script.php?var1=value1&var2=value2&var3=value3 // etc... we can see that there are 2 GET variables available from the PHP script called name and score. Thus, to access score from PHP you need to do it like this:
echo $_GET["score"];
This will output 123 in our example.
This may not solve your problem, but one issue I see with your code is calling strip_tags (or another function that alters the string) after it has already been quoted for insertion with mysql_real_escape_string may defeat the purpose of mysql_real_escape_string. It should be the very last function called on data before it's inserted.
Also, if score is an integer string, intval serves just as well as mysql_real_escape_string for sanitizing integers for insertion.
EDIT: You're also checking for GET variables in the PHP when the submission method used in the jQuery is POST. Try looking at $_POST instead of $_GET on the PHP side. You don't need to put variables in a query string if you're putting them in the request body via POST either.
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'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.
im trying to write a code where i will be able to send a variable that contains a mathematical equation through ajax and have it computed using php
the problem that i am getting is that once the php it returns the variable to jquery it doesnt compute it and still returns it as an equation
this is how i made it
jquery
$(".equals").click(function(e){
e.preventDefault();
var firstnum= $("#firstnum").val();
var secnum= $("#secnum").val();
var operator= $('#operator').val();
var compute = firstnum+operator+secnum;
content = {compute:compute}
$.ajax({
url:'compute.php',
type:'POST',
data:content,
success:function(response){
console.log(response);
}
});
});
php
<?php
$compute =$_POST['compute'];
echo $compute;
?>
for example the content of my variable compute is...
10+10
the php will still return it as is
what i want to happen is once it comes back from php it will return as
20
is there a way to make this happen?
thanks
If you want PHP to compute it, you should write something like this. Because when you send 10+10, PHP sees it as a string.
Javascript:
$(".equals").click(function(e){
e.preventDefault();
var firstnum= $("#firstnum").val();
var secnum= $("#secnum").val();
var operator= $('#operator').val();
content = {first_number:firstnum,second_number:secnum,operator:operator}
$.ajax({
url:'compute.php',
type:'POST',
data:content,
success:function(response){
console.log(response);
}
});
});
And at the PHP:
<?php
$content = $_POST['content'];
if( '+' == $content['operator'] ){
echo $content['first_number'] + $content['second_number'];
}
else if( '-' == $content['operator']){
//extraction
}
// so on..
?>
You must have a calculator script on server side in PHP.
The mathematical expression must be parsed. You could use something like this
http://20xxproductions.com/code-samples?s=phpsc
for parsing more complex expressions.
If you have to process simpler ones you can specifiy an operator and give both numbers as extra POST variables.
I have a little contact form, where I would like to ask the user to calculate and enter the correct value in order to prevent spam. Now, when the send button is clicked, I fire a php script, where I change the calculation values. I would like to echo these values and show them as the new placeholder in case of both, success, as well as failure.
$("#send_button").click(function() {
var url = "contact.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#contact_form").serialize(), // serializes the form's elements.
success: function(data)
{
var txt = "<?php echo 'Spam protection: Calculate ($first_num + $second_num) x $multiplier';?>";
$("#form_info_label").css('color','#0ed68d');
$("#form_info_label").text(data);
$("#user_answer").attr("placeholder",txt);
},
error: function(data) {
var txt = "<?php echo 'Spam protection: Calculate ($first_num + $second_num) x $multiplier';?>";
alert(txt);
$("#form_info_label").css('color','#f2275e');
$("#form_info_label").text("Error. Please try again.");
$("#user_answer").removeAttr('value');
$("#user_answer").attr("placeholder",txt);
}
});
return false; // avoid to execute the actual submit of the form.
});
However my placeholder ends up not interpreting it as php code, but just simply copies the text. So my placeholder then ends up displaying:
<?php echo 'Spam protection: Calculate ($first_num + $second_num) x $multiplier';?>
I ended up returning a json-encoded array with my desired values from php back to javascript and parsed the response there.
You'll need PHP tags
var txt = "<?php echo 'Spam protection: Calculate ($first_num + $second_num) x $multiplier'; ?>";
You actually have it right in the error handler, so you probably just forgot, and now you've edited the question to include them ?
If you have PHP tags, and it's still not being parsed, the file the javascript is in is not being parsed by PHP.
Remember on comuputers to use the * for multiply things, not the x.
And it´s also not clear, what your function "Calculate($param)" does, but usally you don´t need a function for adding one variable to another. But the brackets still needed...
In my case the PHP tag was not interpreted by js either. A solution I found was:
In my php file I defined the variable in a non-visible div:
?>
<div id="first_num" style="display: none">
<?php echo $first_num; ?>
</div>
<?php
In the jquery file I read the div value like this:
var first_num= $("#first_num").text().trim();
First of all what adeneo already said: .js files are not parsed by PHP.
Secondly PHP variables will not be expanded when they occur in single quoted strings. http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.single
You should use either double quotes or
echo 'Spam protection: Calculate ('.$first_num.' + '.$second_num.') x '.$multiplier;