php can not get the data send by ajax - javascript

this is the js code, ajax has two arguments, the first is url, 2nd is a object which contains type data and onsuccess. (I didn't use jQuery but the function I define myself, the code is at the end of the question)
I just want to send the 'text' string to php, so is there any problem to do like this? I also have tried change the data to data: {searchinput:"text"}, but still don't work.
ajax(
'http://localhost/test.php',
{
type: 'POST',
data: "searchinput=text",
onsuccess: function (responseText, xhr) {
console.log(responseText);
}
}
);
this is the php code, sorry for changing the code wrong while pasting it on.
$searchinput = $_POST["searchinput"];
# $db = new mysqli('localhost', 'root', '', 'text');
if (mysqli_connect_errno()) {
echo "error:can not connect database";
}
$query = "select * from text where data like'".$searchinput."%' ";
$result = $db->query($query);
then the error is
Undefined index: searchinput
I have search some method like change onsuccess function to setTimeout, and do ajax again, but it doesn't work, just send the data again but the php still can't get the data
this is the ajax function
function ajax(url, options) {
if (!options.type) {
options.type = "post"
};
var xhr = new XMLHttpRequest();
xhr.open(options.type, url, true);
xhr.send(options.data);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
options.onsuccess(xhr.responseText, xhr)
} else {
options.onfail(xhr.responseText, xhr);
}
};
}
}

Well, since you used the ajax wrong, I'm not surprised. There should be a error in the console.
jQuery AJAX is used like this:
$.ajax({
url: "http://localhost/test.php",
type: 'POST',
data: {searchinput: text},
success: function (responseText, xhr) {
console.log(responseText);
}
}
);
url is a part of the object the ajax expects, so it needs to be inside and not outside of it. Also, data is expecting another object, you gave it a plain string.
Also, as #Muhammad Ahmed stated in his answer, you are using a wrong variable in your php code.
Edit: AJAX in JavaScript without jQuery:
var request = new XMLHttpRequest();
request.open('POST', 'http://localhost/test.php', true);
request.onreadystatechange = function() {
if (this.readyState === 4) {
if (this.status >= 200 && this.status < 400) {
// worked
var data = JSON.parse(this.responseText);
} else {
// failed
}
}
};
request.send();
request = null;

$searchcon = $_POST["searchinput"];
# $db = new mysqli('localhost', 'root', '', 'text');
if (mysqli_connect_errno()) {
echo "error:can not connect database";
}
$query = "select * from text where data like'".$searchinput."%' ";
$result = $db->query($query);
In This code there is a mistake on ist line you are using variable $searchcon
and on query you are using $searchinput change ist varaible name to $searchinput instead of $searchcon. and also change your ajax code.
$.ajax({
url: "http://localhost/test.php",
type: 'POST',
data: {searchinput: text},
success: function (responseTxt, xhr) {
console.log(responseTxt);
}
}
);

send data value like below and use print_r($_POST) on php page to see values are coming or not
$.ajax(
{ url: 'test.php',
type: 'POST',
data:{
searchinput:text
},
onsuccess: function (responseText, xhr) {
console.log(responseText);
}
}
);

Try with this code you were using ajax in wrong manner. You can learn more about how ajax works and how to code for ajax over http://api.jquery.com/jquery.ajax/
$.ajax(
{
type: 'POST',
url : 'http://localhost/test.php',
data: {searchinput:text},
success: function (responseText, xhr) {
console.log(responseText);
}
}
);
and within your PHP file you need to update your typo i.e. you were getting value of your POST in $searchcon variable
$searchcon = $_POST["searchinput"];
^^^^^^^^^^
and within your query you were using
$query = "select * from text where data like'".$searchinput."%' ";
^^^^^^^^^^^^^^
it should be like
$query = "select * from text where data like'".$searchcon."%' ";
^^^^^^^^^^

Try this code :
var other_data = $('form').serializeArray();
$.ajax({
url: 'work.php',
data: other_data,
type: 'POST',
success: function(data){
console.log(data);
}
});
or
you can also pass the data in url also.
Try the code which suits your requirement.
$.ajax({
url: 'work.php?index=checkbox&action=empty',
type: 'POST',
success: function(data){
console.log(data);
}
});

Related

how to execute one ajax function before the other using jquery

i am creating two ajax functions one in the traditional method and one with jquery. but when i do this the traditional method gets called first and in return i dont get some of my desired outcomes. how can i make the traditional ajax method to be translated into jquery?
here is my traditional ajax method:
function countFollowers() {
var xmlHttp = GetXmlHttpObject();
var url = "checkFollowers.php?username=" + document.followForm.follow_id.value;
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
var r = xmlHttp.responseText.trim();
if (r != "error") {
document.getElementById('followersCount').innerHTML = xmlHttp.responseText;
error = true;
return false;
}
}
}
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
if (error == true) {
return false;
}
}
here is my jquery ajax:
jQuery(document).ready(function($) {
$('.msg-icon').on('click', function(e) {
e.preventDefault(); //prevent a normal postback and allow ajax to run instead
var follow_id = $(this).find('input[name="follow_id"]').val();
$.ajax({
data: follow_id,
type: "post",
url: "followingsystem.php?follow=" + follow_id,
success: function(data) {
}
});
});
});
here is what i come up with so far to make the two ajax functions in the same on click function:
jQuery(document).ready(function($){
$('.msg-icon').on('click', function(e){
e.preventDefault(); //prevent a normal postback and allow ajax to run instead
var follow_id = $(this).find('input[name="follow_id"]').val();
$.ajax({
data: follow_id,
type: "post",
url: "followingsystem.php?follow="+follow_id,
success: function(data) {
}
});
$.ajax({
data: follow_id,
type: "post",
url: "checkFollowers.php?username="+follow_id,
success: function(data) {
}
});
});
});
but it is still not executing the response text that is coming from my php file
php code:
<?php
include("functions.php");
include("session.php");
require("connection.php");
if(isset($_GET['username'])){
$username =$_GET['username'];
$result= $db->prepare("SELECT * FROM users WHERE username=?");
$result->bindValue(1,$username);
$result->execute();
$row = $result->fetch();
if($result){
echo "Followers </br>". $row["followers_count"];
}
else{
echo "error";
}
}
?>
how will i get it to echo the $row["followers_count"] inside my span element?
You said in the comments you wanted to run the two requests sequentially instead of in parallel. Here's an all-round better way to organise your code which both allows that, and makes the code more re-usable, more maintainable and testable, and easier to understand in general.
I've used the Promise/Deferred interface provided by jQuery and AJAX as the way to chain the requests in sequence. Notice how each call is separated into each own function (so it's re-usable), but that function returns the Deferred object from the AJAX request, so you can use it to do something else when the request finishes.
Also based on your PHP I think the call to checkfollowers needs to be a GET (because PHP checks $_GET for the input value, and that's what your original XHR call was), and also you need to set the data with an explicit "username" parameter name so it'll be recognised.
It's not clear whether your call to followingsystem.php is correct or not because I can't see the PHP code for it.
jQuery(document).ready(function($) {
$('.msg-icon').on('click', function(e) {
e.preventDefault(); //prevent a normal postback and allow ajax to run instead
var follow_id = $(this).find('input[name="follow_id"]').val();
var request = follow(follow_id); //run the initial request, get back the Deferred object representing that request.
request.done(function() { //when the first request is done, run the second one.
checkFollowers(follow_id);
});
});
});
function follow(follow_id) {
return $.ajax({
data: { follow: follow_id},
type: "post",
url: "followingsystem.php?follow=" + follow_id
});
}
function checkFollowers(follow_id) {
return $.ajax({
data: { username: follow_id },
type: "get",
url: "checkFollowers.php",
success: function(data) {
document.getElementById('followersCount').innerHTML = data;
}
});
}

Display js code in php method ajax

I run the PHP code by ajax method with the click of a button.
$(".btn_ranking").one('click', function(e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: {
name: name,
time: time
}
});
});
I would like the file.php to be able to run the js code, for example:
if ($time < $_SESSION['time']) {
[...]
}
else {
echo '<script>alert("lol");</script>';
}
And that when the button .btn_ranking on the page is pressed, an 'lol' alert will be displayed. If it is possible?
you can echo a response to the AJAX call and then run the JS according to the response..
$(".btn_ranking").one('click', function(e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: { name: name, time: time },
success: function (data) {
if(data==1){
//do this
}else if(data==2){
//do that
alert('LOOL');
}
}
});
});
PHP CODE:
if ($time < $_SESSION['time']) {
echo '1';
}
else {
echo '2';
}
You can't said to a server-side script to use javascript.
What you have to do is to handle the return of you'r ajax and ask to you'r front-side script to alert it. Something like that :
file.php :
if ($time < $_SESSION['time']) {
[...]
}
else {
echo 'lol';
exit();
}
Front-side :
$(".btn_ranking").one('click', function(e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: {
name: name,
time: time
},
success : function(data) {
alert(data);
}
});
});
When you used ajax for call php script, everything will be print in the return of the php code will be return to the HTTP repsonse and so be on the Ajax return function as params.
Ok .. First change your js code to handle answer from php script:
$(".btn_ranking").one('click', function(e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: { name: name, time: time }
success: function(data) {
console.log(data);
// check if it is true/false, show up alert
}
});
});
Then change php script (file.php), something like that:
$response = [];
if ($time < $_SESSION['time']) {
$response['data'] = false;
}
else {
$response['data'] = true;
}
return json_encode($response);
Something like that is the idea :) When u send ajax with POST method get variables from there, not from $_SESSION :)
U can see good example here

Fetching PHP Data with Javascript and assign it to an array

I've got a php script with collects data from a server and displays it in an array and after that as a json with the function.
echo json_encode($result);
Now I want to access that array with my javascript and display it. It should be saved in a var as an array so it should look like:
data = [ "xxxx" , "ssss",];
But I guess I can simply put in my function which gets the array data instead so it'd be:
data = myfunction ;
What I've tried so far:
function reqListener () {
console.log(this.responseText);
}
var oReq = new XMLHttpRequest(); //New request object
oReq.onload = function() {
};
oReq.open("get", "http://myserver.com/myscript.php", true);
oReq.send();
and
function getdata(url) {
jQuery.ajax(
{
type: "GET",
url: "http://myserver.com/myscript.php/",
dataType: "text",
success: function (response) {
var JSONArray = jQuery.parseJSON(response);
connsole.log(JSONArray);
}
});
}
But none seems to work and I get displayed 'undefined' instead of my arrays.
Would be really great if somebody has some ideas on that and can help me out.
Edit:
Since we are getting nowhere here's my php code:
<?php
error_reporting(0);
$html = file_get_contents("url here");
$dom = new DOMDocument();
$dom->loadHTML($html);
$tbodyRows = $dom->getElementsByTagName( 'tbody' )
->item( 0 ) // grab first tbody
->getElementsByTagName( 'tr' );
$result = array();
foreach( $tbodyRows as $tbodyRow )
{
$result[] = $tbodyRow->getElementsByTagName( 'td' )
->item( 2 ) // grab 3rd column
->nodeValue;
}
echo json_encode($result);
?>
Try this code:
function getdata(url) {
console.log('Started');
jQuery.ajax({
type: "GET",
url: "http://myserver.com/myscript.php",
dataType: "text",
error: function (xhr) {
console.log('Error',xhr.status);
},
success: function (response) {
console.log('Success',response);
}
});
}
Open the browser's console, and let me know about its contents. If you don't see Error or Success, your code isn't actually executing
I have done a similar thing earlier. I will describe it and I wish it will help you.
In the following code (get_categories.php), I am retrieving data from the database and add them to an array. Then return it by encoding as a JSON.
$sql = "SELECT category_name FROM category;";
$dataArray = [];
$result = $connection->query($sql);
if ($result) {
while ($row = $result->fetch_assoc()) {
$dataArray[] = $row;
}
echo json_encode($dataArray);
}
Then in my Javascript code, I can get the data as follows.
$.ajax({
url: "/get_categories.php",
type: "GET",
dataType: "json",
success: function (categories) {
for (var i = 0; i < categories.length; i++) {
console.log(categories[i]);
}
},
error: function (jqXHR, textStatus, errorThrown) {
// Error handling code
}
});

Send variable to php via ajax

I'm trying to send a input value to php via ajax but I can't seem to get this right. I'm trying to create a datatable based on the user input.
This is my code:
<input class="form-control" id="id1" type="text" name="id1">
My javascript code:
<script type="text/javascript">
$(document).ready(function() {
var oTable = $('#jsontable').dataTable(); //Initialize the datatable
$('#load').on('click',function(){
var user = $(this).attr('id');
if(user != '')
{
$.ajax({
url: 'response.php?method=fetchdata',
data: {url: $('#id1').val()},
dataType: 'json',
success: function(s){
console.log(s);
oTable.fnClearTable();
for(var i = 0; i < s.length; i++) {
oTable.fnAddData([
s[i][0],
s[i][1],
s[i][2],
s[i][3],
s[i][4],
s[i][5],
s[i][6],
s[i][7]
]);
} // End For
},
error: function(e){
console.log(e.responseText);
}
});
}
});
});
</script>
My php script:
<?php
$conn = pg_connect(...);
$id1 = $_POST["id1"];
$result = pg_query_params($conn, 'SELECT * FROM t WHERE id1 = $1 LIMIT 20', array($id1));
while($fetch = pg_fetch_row($result)) {
$output[] = array ($fetch[0],$fetch[1],$fetch[2],$fetch[3],$fetch[4],$fetch[5],$fetch[6],$fetch[7]);
}
echo json_encode($output);
?>
I don't know a lot of js but my php is correct i test it. So i guess the problem is in the javascript code.
The problem is, my datatable is not being created based on the user input.
Thank you!
change
data: {url: $('#id1').val()},
to:
type: 'POST',
data: {id1: $('#id1').val()},
However the problem might be bigger. You might not be getting the correct data from PHP. You can debug by adding the error option to your ajax() call, like this:
$.ajax({
url: 'response.php?method=fetchdata',
type: 'POST',
data: {id1: $('#id1').val()},
dataType: 'json',
success: function(s){
},
error: function (xhr, status, errorThrown) {
console.log(xhr.status);
console.log(xhr.responseText);
}
});
Then check your browser's Console for the output, this should give you some type of error message coming from PHP.
My assumption is that since you are using dataType: 'json', the ajax request expects JSON headers back, but PHP is sending HTML/Text. To fix, add the correct headers before echoing your JSON:
header('Content-Type: application/json');
echo json_encode($output);

PHP - Append New Value to Form Data for Ajax Post

I have some FormData that are going to be sent into another PHP file using Ajax Post.
var formElement = document.getElementById("form-id");
var form_data = new FormData(formElement);
var csrf_arr = csrf.split("=");
form_data.append(csrf_arr[0],csrf_arr[1]);
$.ajax({
type: "POST",
url: "your-url",
data: form_data,
processData: false,
contentType: false,
dataType: "json",
success: function(data) {
alert(data.message);
},
complete: function(data) {
location.reload();
}
})
What I'm trying to do here is to append a new single data inside the form_data
From my assumption, I could make it just by doing this
form_data.append("key","value");
But it is not sent through the ajax post or even not appended to the form_data as part of the FormData.
Am I making any mistake here or even there is certain rule for that?
Please give any help.
Thanks in advance!
Dear all of my friend,
I'm sorry. Actually it is just a mistake from myself.
I have fix this myself and found the mistake right inside my code.
-- The javascript code --
$( '#submitYours' ).on('click', function(){
var formElement = document.getElementById("form-id");
// Value of formElement consist of pair of data like:
// qst_additional_name_for_the_key=value_of_the_key
var form_data = new FormData(formElement);
form_data.append('break','break');
// to prevent confusion, i'm putting the csrf variable value here
// but i'm not using this as printed variable later, just for security check
var csrf = "your_csrf_token_name=bb6ff34c26ff938822dd339c1682bbcc";
var csrf_arr = csrf.split("=");
var x = 0;
for(x = 0; x < elementId.length; x++){
form_data.append(elementId[x], elementVal[x]);
// Appended data above is just an additional data from some array of data
// and the format is the same with formElement
// qst_additional_name_for_the_key=value_of_the_key
}
form_data.append("master_id",master_id);
form_data.append(csrf_arr[0],csrf_arr[1]);
addLoader("overlay-loader");
runInAnimate("overlay-loader", "bounceInUp");
$.ajax({
type: "POST",
url: "url.php",
data: form_data,
processData: false,
contentType: false,
dataType: "json",
success: function(data) {
alert(data.message);
},
complete: function(data) {
runOutAnimate("overlay-loader", "overlay-loader", "bounceOutDown");
location.reload();
}
})
});
-- The url.php code --
$temp = '';
$arr_in = '';
foreach($_POST as $key => $value){
if(!#$value) continue;
if(substr($key, 0, 4) == 'qst_'){ // This is the real problem.
// The only data taken from the form_data
// are the data containing string "qst_" in it
if(is_array(#$value)){
foreach(#$value as $val){
$this->yourmodel->saveAnswer(substr($key, 4), strtolower(trim(#$val)));
$temp = #$_POST[$key];
$arr_in .= #$temp;
}
}else{
$this->yourmodel->saveAnswer(substr($key, 4), strtolower(trim(#$value)));
$temp = #$_POST[$key];
$arr_in .= #$temp;
}
}else if($key == 'break'){ // remember my additional data? The string "break"
// i just have to chek it here and put into my $arr_in variable,
// so that I can use it now, because the previous conditional allow
// only data containing string "qst_"
$temp = #$_POST[$key];
$arr_in .= #$temp;
}
}
print json_encode(array('status' => 'success', 'message' => #$arr_in));
The conclusion is, nothing wrong if we just append the form_data manually
form_data.append('your_key','your_value');
Everything just the matter of how you access the data after it sent to another file.
My Mistake, everyone!
I'm sorry and thanks a lot for your help. :)

Categories