sending data to php with ajax.send - javascript

Can someone help me with sending this data to a .php page where I could receive it on my PHP page
javascript:
postToSql(){
var ajax;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
ajax=new XMLHttpRequest();
}
else
{
// code for IE6, IE5
ajax=new ActiveXObject("Microsoft.XMLHTTP");
}
ajax.onreadystatechange=function()
{
if (ajax.readyState==4 && ajax.status==200)
{
alert(ajax.responseText); //receiving response
}
};
var name = $("#entry_1274804157").val();
//alert(name);
var company= $("#entry_1828184698").val();
var phone=$("#entry_2039177352").val();
var email=$("#entry_1545475878").val();
var comments=$("#entry_1846523632").val();
var params = {
"name":name,
"company":company,
"phone":phone,
"email":email,
"comments": comments
};
//var jsonText = JSON.stringify(params);
ajax.open("POST", "view/templates/includes/insertgoogle.php", false);
ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
ajax.send("totalJsonStr="+params);
//alert(totalJsonStr);
// alert(params);
return true;
}
</script>
HTML:
<form action="https://docs.google.com/asgsasdfasg/formResponse" method="POST" id="" target="_self" onsubmit="return postToSql();">
EDIT:
This is how I am receiving it:
if(isset($_POST['totalJsonStr']))
{
$jsonVal = json_decode($_POST['totalJsonStr']);
$jsonVal2 = json_decode($jsonVal);
var_dump($_POST['totalJsonStr']);
var_dump($jsonVal);
var_dump($jsonVal2);
$name = $jsonVal2->{'name'};
$company= $jsonVal2->{'name'};
$phone= $jsonVal2->{'name'};
$email= $jsonVal2->{'name'};
$comments= $jsonVal2->{'name'};
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
mysql_query("INSERT INTO `testgoogle` ( Name, Company, Phone, Email, Comments )
VALUES ('$name','$company', '$phone', '$email', '$comments')");
Print "Your information has been successfully added to the database.";
return;
}
else
{
die("No Data Found");
}

Where do you create the "ajax" object?
var ajax;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
ajax=new XMLHttpRequest();
}
else
{// code for IE6, IE5
ajax=new ActiveXObject("Microsoft.XMLHTTP");
}
from here: http://www.w3schools.com/ajax/ajax_xmlhttprequest_create.asp

If you want to use $_GET then,
Remove:
ajax.open("POST", "view/templates/includes/insertgoogle.php", true);
Add:
ajax.open("GET", "view/templates/includes/insertgoogle.php", true);
Helpful link: http://www.degraeve.com/reference/simple-ajax-example.php

Using POST Method,
The perfect solution would be, store all values in an array and send the array as a json request using json.stringify().
In php, Use json_decode() to decode your json string.
UPDATE
Add this to your javascript,
<script type="text/javascript">
function postToSql(){
var ajax;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
ajax=new XMLHttpRequest();
}
else
{// code for IE6, IE5
ajax=new ActiveXObject("Microsoft.XMLHTTP");
}
ajax.onreadystatechange=function()
{
if (ajax.readyState==4 && ajax.status==200)
{
alert(ajax.responseText); //receiving response
}
}
var name = "1234";
var company= "1234";
var phone="1234";
var params = {
"name":name,
"company":company,
"phone":phone,
};
var jsonText = JSON.stringify(params);
ajax.open("POST", "view/templates/includes/insertgoogle.php", true);
ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
ajax.send("totalJsonStr="+jsonText);
}
</script>
<form action="https://docs.google.com/asgsasdfasg/formResponse" method="POST" id="" target="_self" onsubmit="postToSql();return false;">
Add this to php
<?php
if(isset($_POST["totalJsonStr"]))
{
$jsonVal = json_decode($_POST["totalJsonStr"]);
print $jsonVal->{'name'};
print $jsonVal->{'company'};
print $jsonVal->{'phone'};
}
else
{
die("No Data Found");
}
?>

since nothing was working for me, I finally used jquery ajax which worked.

Related

Undefined _POST variable when using XMLHttpRequest()

I am trying to use Ajax to insert data into database with POST method. But php can not recognize the post variables.
ajax:
function createUser() {
var _id=document.getElementById('new_id').value;
var _name=document.getElementById('new_name').value;
var params = "id="+_id+"&name="+_name;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function() {
console.log(xmlhttp);
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
if(xmlhttp.responseText=="")
alert("New User is created!");
else
document.body.innerHTML=xmlhttp.responseText;
}
};
xmlhttp.open("POST","resource/create_profile.php",true);
xmlhttp.send(params);
}
php:
<?php
$id = $_POST["id"];
$name = $_POST["name"];
$conn = oci_connect(....);
$query = "....";
$result = oci_parse($conn, $query);
oci_execute($result);
oci_close($conn);
?>
if i uncomment the request header content type then nothing happens, no error is shown. if i comment it then php shows error. i am giving a screenshot.
http://imgur.com/CdKO84V
what am i supposed to do? if i use get method then it is working good but i can not use it since i need to upload file.
At last I have found the solution! I had to add the setRequestHeader() method below the open method. So in the end the code looks like:
xmlhttp.open("POST","resource/create_profile.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

Ajax returning blank response

I'm working on a simple script where I just want to see request and response that is sent to server and then recieved at client via Ajax. The server is always returning Status 500. What am I doing wrong?
Below is my script.
Javascript:
<script>
function loginJs()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","http://my-website.com/ajax_exp.php",true);
xmlhttp.onreadystatechange=function()
{
alert("State "+xmlhttp.readyState+" Status "+xmlhttp.status);
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert(xmlhttp.responseText);
}
}
xmlhttp.send();
}
</script>
ajax_exp.php
<?php
header('Access-Control-Allow-Origin: http://my-website.com/ajax_exp.php');
add_action('wp_ajax_my_action', 'my_action');
add_action('wp_ajax_nopriv_my_action', 'my_action');
function my_action()
{
$username = 'username';
$password = 'password';
echo $username;
die();
}
?>
1) try removing
header('Access-Control-Allow-Origin: http://my-website.com/ajax_exp.php');
add_action('wp_ajax_my_action', 'my_action');
add_action('wp_ajax_nopriv_my_action', 'my_action');
replacing with
my_action();
You can easily trace the error;
2) Check console log for any javascript errors.
Path is the problem provide your server path ajax/ajax_exp.php
<script>
function loginJs()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","ajax/ajax_exp.php",true);
xmlhttp.onreadystatechange=function()
{
alert("State "+xmlhttp.readyState+" Status "+xmlhttp.status);
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert(xmlhttp.responseText);
}
}
xmlhttp.send();
}
</script>
If anyone else is having the same issue, this is what I did and now it works!
Javascript
Replaced xmlhttp.send(); with xmlhttp.send(null);
PHP
<?php
$username = "user";
$password = "password";
print $username;
?>

Using Ajax to pass Json variable and decode

I have a AJAX script which i was using previously and was able to retrieve data from viewCommentsJson.php as such[{"comments":"Greta"},{"comments":"John"}]. I was wondering if its able to decode the return value such that it display it properly ?
Thanks in advance
Greta John
Main.php
<a onclick="showUser('.$row['ID'].')" method = "POST" action= "viewCommentsJson.php">Show Comments</a>
<script>
function showUser(str) {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("Post","viewCommentsJson.php?q="+str,true);
xmlhttp.send();
}
</script>
viewCommentsJson.php
$com = $_REQUEST["q"];
include 'connectDatabase.php';
//opening sql table
$selected = mysql_select_db("2000",$dbhandle)
or die("Could not select 2000");
$arr = array();
$data = mysql_query("SELECT comments FROM comment WHERE ID = '$com'");
$rows = array();
while($r = mysql_fetch_assoc($data)) {
$rows[] = $r;
}
print json_encode($rows);
Since you don't mind a jQuery solution, here is how it can be done
function showUser(str) {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
$.ajax({
type:'post',
url: 'viewCommentsJson.php',
data:{q:str},
success:function(data)
{
data = $.parseJSON(data);
var response;
$.each(data, function(index, value){
response += value+'<br />';
});
$('#txtHint').html(response);
}
});
}
You can refer $.ajax and $.parseJSON for more information.
Note: Your SELECT comments FROM comment WHERE ID = '$com' is prone to SQL injection. At the very least, you should sanitize all incoming data before using it in your query directly.
<a onclick="showUser('1')" href="#?">Show Comments</a>
<script>
function showUser(str) {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
data = eval(xmlhttp.responseText);
for(i=0;i<data.length;i++){
document.getElementById("txtHint").innerHTML = document.getElementById("txtHint").innerHTML + data[i].comments;
}
}
}
xmlhttp.open("Post","viewCommentsJson.php?q="+str,true);
xmlhttp.send();
}
</script>
<div id="txtHint"></div>
First of all remove method and action from A tag and used above code now. Removed some typos

I made a request to the Twitter API. How can I get the JSON response from my PHP script to my JavaScript?

I'm doing a Twitter API request that returns JSON of all tweets containing #awkward . Here's the successful response on a server: http://babbage.cs.missouri.edu/~atgvyc/php/election_tweets/index.php
But I want to be able to use that JSON in my JavaScript and parse through it with a for-loop to pull out certain information (particularly the geotags and location). I thought I could do this with AJAX and then JSON.parse, but it's not working the way I thought it would.
Any suggestions?
Here's my PHP script:
<?php
require_once('TwitterAPIExchange.php');
$settings = array(
'oauth_access_token' => "XXX",
'oauth_access_token_secret' => "XXX",
'consumer_key' => "XXX",
'consumer_secret' => "XXX"
);
$url = 'https://api.twitter.com/1.1/search/tweets.json';
$getfield = '?q=#awkward&geocode=38.949926,-92.330037,35mi&result_type=recent';
$requestMethod = 'GET';
$twitter = new TwitterAPIExchange($settings);
echo $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();
?>
Here's my HTML:
<!DOCTYPE html>
<html>
<head>
<title>Sample elections tweets</title>
<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var json = JSON.parse(xmlhttp.responseText);
//here's where i'd like to put a for-loop
}
}
xmlhttp.open("GET","index.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">Request data</button>
<body>
Ok, I think I know what you are trying to do now. There really isn't an out of the box "for each" like there is in php, which is why a lot of frameworks implement there own (jQuery's $.each()), or make prototypes. But, you may be able to do what you need with the below. You can replace all the console.log() with alert() if you want, but it gets hectic not being in Chrome's dev tools (f12 on most machines). Also, if Dale Musser is still there tell him hello! MIZ
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var json = JSON.parse(xmlhttp.responseText);
//log entire json struct to developer console for easy viewing
console.log(json);
//you can reference individual pieces of json by doing something like
//json.statuses or json.statuses[2]
var statuses = json.statuses;
for(var i=0;i<statuses.length;i++){
var curStatus = statuses[i];
//access bits directly
var tweetAuthor = curStatus.user.name;
var tweetTime = curStatus.created_at;
//iterate hashtags
var hashtags = curStatus.entities.hashtags;
for(var k=0;k<hashtags.length;k++){
console.log("Hashtag: " + hashtags[k].text);
}
//iterate all elements of tweet
for(var key in curStatus){
var attrName = key;
var attrValue = curStatus[key];
console.log("attribute name: " + attrName);
console.log("attribute key: " + attrValue);
if(attrName = "text") {
//Do something with tweet texts... like:
//document.getElementById("statuses").appendChild(attrValue);
}
}
}
}
}
xmlhttp.open("GET","index.php",true);
xmlhttp.send();
}

How to make Ajax send JSON to PHP script

I am working on a webpage that needs to store data on the server in a .json file.
Here is what I have tried so far:
Javascript code:
// variable j = our json
var j;
function loadDoc(){
var xmlhttp;
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
j = xmlhttp.responseText;
}
}
xmlhttp.open("GET","things.json",true);
xmlhttp.send();
}
loadDoc();
function rewrite(){
var xhr;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
};
};
xhr.open("POST", "write.php", true);
xhr.send("data=" + j);
};
The PHP file:
<?php
$data = $_POST['data'];
file_put_contents('things.json', $data);
?>
Note, in other parts of my code the j variable is changed.
My problem is that after the PHP script is making the JSON file blank. Am I doing anything wrong? Is php receiving the JSON properly? If so, how can I fix that?
Cheers!
If you vote down, please tell me why.
To POST data like an HTML form, add an HTTP header with setRequestHeader(). (w3school page)
so it must be :
xmlhttp.setRequestHeader("Content-type","application/json");

Categories

Resources