Sending data using Ajax to PHP - javascript

I am trying to send a string via ajax using the GET method but whenever that string contains some punctuation characters those characters do not appear when I use the echo in php.
For example if I send a string "sub + 12" the php will echo "sub 12"
If I send "&()*", php will echo an empty string.
Why does this happen?
Are there any special characters that the string cannot contain?

you encodeURIComponent(). this is demo code which you can check
something like this encodeURIComponent(yourtext)
first this html code . in text filed enter your text and check this output, this is onkeyup so enter text and check result
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>PHP, jQuery search demo</title>
<link rel="stylesheet" type="text/css" href="my.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("input").keyup(function () {
$('#results').html('');
var searchString = $("#search_box").val();
var data = 'search_text=' + encodeURIComponent(searchString);
if (searchString) {
$.ajax({
type: "GET",
url: 'edit.php',
data: data,
dataType: 'text',
async: false,
cache: false,
success: function (result) {
$('#results').html(result);
//window.location.reload();
}
});
}
});
});
</script>
</head>
<body>
<div id="container">
<div style="margin:20px auto; text-align: center;">
<form method="post" action="do_search.php">
<input type="text" name="search" id="search_box" class='search_box'/>
<input type="submit" value="Search" class="search_button"/><br/>
</form>
</div>
<div>
<div id="searchresults">Search results :</div>
<ul id="results" class="update">
</ul>
</div>
</div>
</body>
</html>
then create edit.php file
<?php
$searchquery = $_GET['search_text'];
echo $searchquery;
?>
then check result . which is working
Output is
Search results :
&()*

Use encodeURI() before sending the request.

Related

how to echo the ajax data with the help of php?

I trying to print the data which was entered by the user, and transfer that through ajax and trying to print or echo it with the help of php code, but I could not do that. enter code here
this is my code:
<html>
<head>
<title>
test ajax
</title>
<script src="jquery.js"></script>
</head>
<body>
<h2>test button</h2><br>
<form>
<input type="text" id="a"><br>
<input type="button" id="b" value="display">
</form>
<script>
$(document).ready(function() {
$('#b').click(function() {
let a = $('#a').val();
alert(a);
$.ajax({
type: "POST",
url: "same_file.php",
data: {
c: a
},
success: function() {}
});
});
});
</script>
</body>
</html>
<?php
extract($_POST);
if(isset($_POST["c"])) {
echo $_POST["c"];
}
?>
I think that, I have the problem with the php code. please give me any solution.
Try it like this
This is your Html
<html>
<head>
<title>
test ajax
</title>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<h2>test button</h2><br>
<form>
<input type = "text" id = "a" > <br>
<input type = "button" id = "b" value = "display" >
</form>
</body>
</html>
<script>
$(document).ready(function(){
$('#b').click(function() {
let a = $('#a').val();
//alert(a);
$.ajax({
type: "POST",
url: "same_file.php",
data: {c: a},
success: function(response) {
alert(response);
}
});
});
});
</script>
This is your same_file.php
<?php
//extract($_POST); code works even without this
if(isset($_POST["c"])) {
echo $_POST['c'];
}
?>
Not sure if your jquery library call is ok so I called the one on the web instead. Also your success:function() was not doing anything which is why you didn't receive anything.
Also always format your code with some indention so that it can be easier to read and comprehend by others.
You probably want to echo before the body is rendered.
But in true, unless you need to process the data the user sends, you don't need PHP at all.
And in truth, you probably don't need jQuery as well, fetch() works just fine.
$(document).ready(function() {
$('#b').click(function() {
let a = $('#a').val();
alert(a);
$.ajax({
type: "POST",
url: "same_file.php",
data: {
c: a
},
success: function() {}
});
});
});
<?php
if (isset($_POST["c"]))
{
// print/echo user data send from form.
echo $_POST["c"];
// stop the script from rendering the html below.
exit();
}
?>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<h2>test button</h2><br>
<form>
<input type="text" id="a"><br>
<input type="button" id="b" value="display">
</form>
<!-- add script element with js code here -->
</body>
</html>

why when i reload a page using AJAX the data disappears

Basically i find code on the internet to test and use it.
the problem is that when i reload the page, the data disappears.
what i want to happen is for the data or the value to just stay.
Thanks guys
Here is the code in index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Pass Data to PHP using AJAX without Page Load</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script
src="https://code.jquery.com/jquery-2.2.4.js" integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI=" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
<h2>Enter Some Data Pass to PHP File</h2>
<div class="row">
<div class="col-md-3">
<form>
<div class="form-group">
<input type="text" id="pass_data" class=" form-control">
<input type="button" class="btn btn-success" onclick="passData();" value="Set">
<p id="message"></p>
</div>
</form>
</div>
</div>
</div>
</body>
<script type="text/javascript">
function passData() {
var name = document.getElementById("pass_data").value;
var dataString = 'pass=' + name;
if (name == '') {
alert("Please Enter the Anything");
} else {
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "post.php",
data: dataString,
cache: false,
success: function(data) {
$("#message").html(data);
},
error: function(err) {
alert(err);
}
});
}
return false;
}
</script>
</html>
and here is my php code
<?php
$pass=$_POST['pass'];
echo json_encode($pass);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Pass Data to PHP using AJAX without Page Load</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script
src="https://code.jquery.com/jquery-2.2.4.js"
integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI=" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
<h2>Enter Some Data Pass to PHP File</h2>
<div class="row">
<div class="col-md-3">
<form>
<div class="form-group">
<input type="text" id="pass_data" class=" form-control">
<input type="button" id="success" class="btn btn-success" value="Set">
<p id="message"></p>
</div>
</form>
</div>
</div>
</div>
</body>
<script type="text/javascript">
$("#success").click(function () {
var name = document.getElementById("pass_data").value;
var dataString = 'pass=' + name;
if (name == '') {
alert("Please Enter the Anything");
} else {
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "post.php",
data: dataString,
cache: false,
success: function (data) {
$("#message").html(data);
localStorage.setItem("data",data);
},
error: function (err) {
alert(err);
}
});
}
return false;
})
$(document).ready(function () {
var someVarName = localStorage.getItem("data");
console.log(someVarName)
$("#message").html(someVarName);
});
</script>
</html>
First of all i changed your js code to use more jquery syntax, as you already have included it (i trigger the on click event on the script and i don't put it in in html). After that in order not to lose your variable after refresh on ajax success i pass the value of data to localstorage, and after refresh (on document ready) i retrieve it and display it in the label.
Of course every time you put a new value and display it, it over-writes the previous one, so after refresh you display the latest value put in your input field.
I am not sure I understand what you mean but...
Before this line:
<!DOCTYPE html>
enter
<?php session_start(); ?>
In this line add
<input type="text" id="pass_data" class=" form-control" value="<?php echo $_SESSION['VAL']; ?>">
and in your php file:
<?php session_start();
$pass=$_POST['pass'];
$_SESSION['VAL'] = $pass;
echo json_encode($pass);
?>

how to call a php file from javascript?

Hi I am very new to JavaScript, looking for some help. I have a form, shown below. When the user gives input and clicks submit, I want to call a php file (shown below also) to be invoked and return a hello. Here is the code I have tried, though it is not working as intended.
<html>
<head>
<script type='text/javascript' src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
</head>
<body>
<form>
<input id="name-typed" type="text" />
<input id="name-submit" type="submit" value="submit" onclick="post()"/>
</form>
<div id="result"></div>
</body>
<script>
function post() {
var hname = $('input#name-typed').val();
$.post('dat.php',{name: hname},function(data) {
$('div#result').html(data);
});
}
</script>
</html>
The PHP file dat.php looks like this:
<?php echo "hello";?>
As in my first paragraph, can anyone suggest any changes I should make?
Try this:
you can change dat.php to say:
<?php
$name = $_POST['name'];
echo "Hello ".$name;
?>
And then your html file would be:
Notice that the button type is changed to a normal button so that it just execute the function rather than submitting the form.
<html>
<head>
<script type='text/javascript' src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
</head>
<body>
<form>
<input id="name-typed" type="text" />
<button type="button" onclick="post()">Submit</button>
</form>
<div id="result"></div>
</body>
<script>
function post() {
$.ajax({
type: "POST",
url: "dat.php",
data: { name: $('#name-typed').val()
},
success: function(response) {
$('#result').html(response);
}
});
}
</script>
</html>
I haven't test but something like this:
$('form').submit(function(){
post()
return false;//block the reload of the page
})
In fact I think you just forget the return false. remvove the onclick if you use my answer

how can i replace to div using ajax and php

i want to replace result from readmore.php into <div id='box'> base on id_pages at index.php after click <a class=readmore> Read More </a>.
i tired to try how to get value from readmore.php using ajax.
this's my code
index.php
<html>
<head>
<link rel='stylesheet' type='text/css' href='style.css'>
<title> Home Page </title>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script>
$('.readmore').click(function(){
$.ajax({
type: "POST",
url: "readmore.php",
data: dataString,
success: function(returnedData) {
$( '#daleman' ).html(returnedData);
}
});
})
</script>
</head>
<body>
<?php
error_reporting(E_ERROR | E_PARSE);
include "koneks.php";
$db = new database;
$db->connectMYSQL();
//* Memulai Tampilan Menu
echo"
<div id='menu'>
<a href='manage.php'>Manage Blog</a>
</div>
";
//* Memulai Tampilan Page
$arraypage = $db->tampilPage();
foreach($arraypage as $data) {
echo"
<input type=hidden id=idnya name='idnya' value=".$data['id_pages'].">
<div id='boxpage'>
<div id='alasatas'>
</div>
<div id='alasjudul'>
".$data['judul']."
</div>
<div>
<div id='alasfoto'>
<img height='200px' src='pict/".$data['foto']."'>
</div>
<div id='alasisi'>
<div id='daleman'>
<br>
".$data['deskripsi']."
</div>
</div>
</div>
<div id='alasketerangan'>
<center>Tanggal dibuat : ".$data['tgl_dibuat']." Label : ".$data['label']." <a class='readmore' >Read More</a> </center>
</div>
</div>
</body>
</html>
";
}
?>
this my readmore.php
<?php
include "koneks.php";
$dbi = new database;
$dbi->connectMYSQL();
echo"
$_POST[idnya]
";
?>
i need help meybe to fix my code, my thanks
There are certain things missing in the code you've posted. Lets just simplify the code a little bit with some modifications.
index.php
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script> <!-- Added jQuery Reference -->
</head>
<body> <!-- Added body tag -->
<?php
echo "<input type='hidden' id='idnya' value='value_posted_for_idnya'><div id='box'> Replace Me </div> <a class='readmore' href='javascript:void(0)'>ReadMore</a>";
?>
<script>
$(document).ready(function(){ // Wrapped the script in $(document).ready function
$('.readmore').click(function(){
$.ajax({
type: "POST",
url: "readmore.php",
data: "idnya=" + $("#idnya").val(), //say you have only one field to post for now
success: function(returnedData) {
$('#box').html(returnedData);
}
});
})});
</script>
</body>
</html>
readmore.php
Can stay the same.
Try the code above and see what you get.
EDIT
If you have multiple fields to post with ajax function you can use serializeArray() method.
Simply wrap your fields with in a form tag as follows
<form id="frm">
...form controls
</form>
This time you have to specify name attributes in order for serializeArray() to work.
Then your new ajax function becomes
$(document).ready(function(){
$('.readmore').click(function(){
$.ajax({
type: "POST",
url: "readmore.php",
data: $("#frm").serializeArray(), //get all name-value pairs within form
success: function(returnedData) {
$('#box').html(returnedData);
}
});
})});
</script>
its possible that click function is not executing beacause you dont prevent default anchor action
<script>
$('.readmore').click(function(event){
event.preventDefault();
$.ajax({
type: "POST",
url: "readmore.php",
data: dataString,
success: function(returnedData) {
$('#box').html(returnedData);
}
});
})
</script>
I have modified your code a little try doing this:
<script>
$('.readmore').click(function(){
var idnya = $('#idnya').val();
$.ajax({
type: "POST",
url: "readmore.php?idnya="+idnya,
data: dataString,
success: function(returnedData) {
$('#box').html(returnedData);
}
});
})
</script>
and in your readmore.php file use $_GET['idnya'] to get this value and use it in your query.

Convert jQuery Object to String upon AJAX call

Let's say I submit a form with anything in the value of user_input like "I am free." I submit it through AJAX and it gets returned to me as a string. Ok now it's an Object... how would I turn that into a string?
Thank you,
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<title>Sin título 3</title>
</head>
<body>
<div id="result_target" style="display:none;"></div>
<form id="form_to_post" action="#" method="post">
<input type="hidden" name="url" value="example.php" />
<input type="text" name="user_input" />
<input type="submit" value="Submit" />
</form>
<script>
$(document).ready(function() {
$("#form_to_post").submit(function() {
var hiddenURL = $("input[name=url]");
var userInputForm = $("input[name=user_input]");
//var dataString = "userInput="+inputForm;
$.ajax({
type: "POST",
url: hiddenURL;
data: {userInput: userInputForm},
success: function(return_contents) {
//returns jquery object...
var output =//
$("#result_target").html(output);
}
});
});
});
</script>
</body>
</html>
use val() to get values from inputs
data: {userInput: userInputForm.val()},

Categories

Resources