Please help me figure out the javaScript/jQuery equivalent of this php code.
<?php
$from = 'USD';
$to = 'INR';
$url = 'http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s='. $from . $to .'=X';
$handle = #fopen($url, 'r');
if ($handle) {
$result = fgets($handle, 4096);
fclose($handle);
}
$allData = explode(',',$result);
$dollarValue = $allData[1];
echo 'Value of $1 in Indian Rupees is Rs. '.$dollarValue;
Try this...
You can use jquery ajax to pass values to php page and get output from ajax success.
$.ajax({
type: "POST",
url: "ajax.php",
data: {from:from,to:to},
success: function(data){
alert(data);
//you can get output form ajax.php, what you expected.
}
});
ajax.php
<?php
$from = $_POST['from'];
$to = $_POST['to'];
$url = 'http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s='. $from . $to .'=X';
$handle = #fopen($url, 'r');
if ($handle) {
$result = fgets($handle, 4096);
fclose($handle);
}
$allData = explode(',',$result);
$dollarValue = $allData[1];
echo 'Value of $1 in Indian Rupees is Rs. '.$dollarValue;
Ref:http://api.jquery.com/jquery.ajax/
The equivalent of fopen in this context would be like doing an jQuery Ajax GET request, however since finance.yahoo.com is on a different domain and their server doesn't allow cross domain requests, the GET request would error. To get around this, you'd need to have the PHP script on the same domain and do a request to that.
Save Script on Server
parse.php
<?php
$response =array('result'=>'failed','message'=>'missing params');
if(isset($_GET['from']) && isset($_GET['to'])){
$from = $_GET['from'];
$to = $_GET['to'];
$url = 'http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s='. $from .'&X='. $to;
$handle = #fopen($url, 'r');
if ($handle) {
$result = fgets($handle, 4096);
fclose($handle);
}
$allData = explode(',',$result);
$dollarValue = $allData[1];
$response['result']=$dollarValue;
$response['message']="value sent";
}
echo json_encode($response);
?>
JavaScript method
function getData(from,to){
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
xhr1 = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
xhr1 = new ActiveXObject("Microsoft.XMLHTTP");
}
//path to your script
xhr1.open("GET", "http://localhost/practice/parse.php?from="+from+"&to="+to, true);
xhr1.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr1.send();
xhr1.onreadystatechange = display_data;
function display_data() {
if (xhr1.readyState == 4) {
console.log(xhr1.responseText);
//do what you want to do here
}
}
}
Related
Sorry for the title gore I am a little over my head on this one and have tried everything I can find online. I'm trying to pass data via post to my sendjs.php file and I have an issue.
The ajax success function does not apply the if statement.
Live site here: www.diysoakwells.com.au (you can add an item and checkout to test).
I'm not even sure where to start to be honest so any information would be appreciated and I will update the post with any info as requested.
app.js
$(function() {
// Get the form.
var form = $("#ajax-contact");
// Get the messages div.
var formMessages = $("#form-messages");
var spinner = $("#spinner");
var submit = $("#submit");
// Set up an event listener for the contact form.
$(form).submit(function(e) {
// Stop the browser from submitting the form.
e.preventDefault();
//display the cog animation
$(spinner).removeClass("hidden");
//hide the submit button
$(submit).addClass("hidden");
jsonObj=[];
for(i=1;i<$(".item-price").length;i++)
{
var items={};
var itemname = $(".item-name").get(i);
var itemprice = $(".item-price").get(i);
var itemquantity = $(".item-quantity").get(i);
var itemtotal = $(".item-total").get(i);
items["name"] = itemname.innerHTML;
items["price"] = itemprice.innerHTML;
items["quantity"] = itemquantity.innerHTML;
items["total"] = itemtotal.innerHTML;
jsonObj.push(items);
}
console.log(items);
var formdata = {};
formdata["textbox"] = $("#textbox").val();
formdata["name"] = $("#name").val();
formdata["phone"] = $("#phone").val();
formdata["email"] = $("#email").val();
formdata["address"] = $("#address").val();
formdata["grandtotal"] = simpleCart.grandTotal();
var x =
{
"cart" : jsonObj,
"formdata" : formdata,
"captchaResponse" : $("#g-recaptcha-response").val()
};
//jsonString = jsonObj+formdata;
var y = JSON.stringify(x);
console.log(y);
var result = jQuery.parseJSON(y);
console.log(result);
// Serialize the form data.
//var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: "post",
url: "sendjs.php" ,
//url: $(form).attr("action"),
data: y,
contentType: "application/json; charset=utf-8",
traditional: true,
success: function (response) {
if(response=="Thank You! Your message has been sent.")
{
//remove the button animation
$(spinner).addClass("hidden");
$(formMessages).removeClass("error");
$(formMessages).addClass("success");
$("#textbox").val("");
$("#name").val("");
$("#email").val("");
$("#message").val("");
$("#phone").val("");
$("#address").val("");
}
else
{
$(formMessages).removeClass("success");
$(formMessages).addClass("error");
$(spinner).addClass("hidden");
$(submit).removeClass("hidden");
}
$(formMessages).text(response);
}
});
});
});
sendjs.php
<?php
//Debugging
//ini_set( 'display_errors', 1 );
//error_reporting( E_ALL );
//replaces file_get_contents due to restrictions on server
function get_data($url)
{
$ch = curl_init();
$timeout = 5;
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
//turn url_fopen on due to restrictions on server
//ini_set('allow_url_fopen', true);
date_default_timezone_set('Australia/Perth');
$time = date ("h:i A");
$date = date ("l, F jS, Y");
$json = file_get_contents('php://input');
$obj = json_decode($json,true);
$captcha = $obj["captchaResponse"];
$captcha;
$secretKey = "scrubbed";
$ip = $_SERVER['REMOTE_ADDR'];
$response = get_data("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
//not used due to server restictions
//$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
$responseKeys = json_decode($response,true);
if(intval($responseKeys["success"]) !== 1) {
echo "Please Click on the Captcha";
return false;
}
else
{
//echo $items;
$name = $obj["formdata"]["name"];
$phone = $obj["formdata"]["phone"];
$email = $obj["formdata"]["email"];
$textbox = $obj["formdata"]["textbox"];
$address = $obj["formdata"]["address"];
$grandtotal = $obj["formdata"]["grandtotal"];
$text = "<html style='font-family:arial'>
<body>
<h1 style='color:crimson;'>DIY Soakwells</h1>
<p>This order was submitted from www.diysoakwells.com.au on $date at $time</p>
<p>$name thank you for your order inquiry. Deliveries are normally every Friday, we will be in contact shortly to discuss your order and confirm a time.</p>
<p>An invoice will be issued after delivery for payment via bank transfer.</p>
<p>In the meantime if you haven't already seen it, you can take a look at www.soakwellcalculator.com.au to confirm the number of soakwells you ordered will be adequate.</p>
<br>
<h2 style='color:crimson;'>CUSTOMER DETAILS</h2>
<p><b>Email:</b>\n$email</p>
<p><b>Name:</b>\n$name</p>
<p><b>Phone:</b>\n$phone</p>
<p><b>Delivery Address:</b>\n$address</p>
<p><b>Message:</b>\n$textbox</p>
<br>
<h2 style='color:crimson;'>ORDER DETAILS</h2>";
$items_in_cart = count($obj["cart"]);
for($i=0; $i < $items_in_cart; $i++) {
$iname = $obj["cart"][$i]["name"];
$price = $obj["cart"][$i]["price"];
$quantity = $obj["cart"][$i]["quantity"];
$total = $obj["cart"][$i]["total"];
//display looped cart data
$items .= "<p>$iname x $quantity - $price <small>ea.</small> <b>Sub Total: </b> $total .</p>";
}
$final_total ="<br>
<p><b>Total: </b>$$grandtotal <small>inc. GST</small></p>
</body>
</html>";
//Email Content
$body = $text.$items.$final_total;
// Set the email subject.
$subject = "New order from $name";
// Build the email content.
$email_content = $body;
// Build the email headers.
$email_headers = 'MIME-Version: 1.0' . PHP_EOL;
$email_headers .= 'Content-Type: text/html; charset=ISO-8859-1' . PHP_EOL;
//$email_headers .= 'To:' . $name . '<' . $email . '>' . PHP_EOL;
$email_headers .= 'From: DIY Soakwells <orders#diysoakwells.com>' . PHP_EOL;
$email_headers .= 'CC: orders#diysoakwells.com.au' . PHP_EOL;
$email_headers .= 'Reply-To: DIY Soakwells <orders#diysoakwells.com.au>' . PHP_EOL;
$email_headers .= 'Return-Path: DIY Soakwells <orders#diysoakwells.com>' . PHP_EOL;
$email_headers .= 'X-Sender: DIY Soakwells <orders#diysoakwells.com.au' . PHP_EOL;
$email_headers .= 'X-Mailer: PHP/' . phpversion() . PHP_EOL;
//$email_headers .= 'X-Priority: 1' . PHP_EOL;
//validate Email
$email_check = filter_input(INPUT_POST, $email, FILTER_VALIDATE_EMAIL);
//Recipients
$to = $email;
if (mail($to, $subject, $email_content, $email_headers, '-forders#diysoakwells.com.au')) {
// Set a 200 (okay) response code.
//http_response_code(200);
echo "Thank You. Your order has been sent and a copy mailed to your inbox.";
} else {
// Set a 500 (internal server error) response code.
//http_response_code(500);
echo "There appears to be an issue with our server, please ring 0420 903 950 or email contact#diysoakwells.com.au.";
}
}
?>
Hope someone can give me some tips.
because your condition is response == "Thank You! Your message has been sent."
and your results are
"Please Click on the Captcha", "Thank You. Your order has been sent and a copy mailed to your inbox.", "There appears to be an issue with our server, please ring 0420 903 950 or email contact#diysoakwells.com.au.".
so all of your result will do else part
I am writing a program that send bulk email to our registered users via ajax.
I want echo every loop response when it is completed and it goes to next condition.
For Example:-
I have list of 100 Emails in database. When i submitted the request to program it will start sending emails.
Prog. works something like :
<?php
foreach($emails as $email){
$status = $this->sendMail($email);
if($status == true)
{
echo "Mail Sent";
}else{
echo "Not Sent";
}
}
?>
Now i want to print "Mail Sent"/"Not Sent" again and again for every loop.
Output:-
Mail Sent
Mail Sent
Mail Sent
Not Sent
Mail Sent
Sending..
EDIT
My PHP Code is:-
<?php
public function send_message() {
$sendTo = $this->input->post('send_to');
$template = $this->input->post('template');
$subject = $this->input->post('subject');
switch ($sendTo) {
case 1:
$users = $this->getAllEmails();
break;
case 2:
$users = $this->getRegisteredUsersEmails();
break;
case 3:
$users = $this->getTemproryUsersEmails();
break;
case 4:
$users = $this->getSubscribersEmails();
break;
}
$status = $this->sendMail($users, $template, $subject);
echo "Mail Sent";
}
private function sendMail($users, $template, $subject) {
$this->load->library('parser');
$status = array();
$i = 0;
foreach ($users as $user) {
$message = $this->parser->parse('email_templates/' . $template, array('email' => $user->email, 'name' => ($user->name != '') ? "Hi " . $user->name : "Hello"), TRUE);
$response = $this->mail->send(config_item('sender_mail'), config_item('sender_name'), $user->email, $subject, $message);
$status[$i]['email'] = $user->email;
$status[$i]['status'] = ($response == 1) ? 1 : 0;
$i++;
}
return $status;
}
?>
My Ajax Code :-
<script type="text/javascript">
$("#send_mail").submit(function(){
$.ajax{
url:"<?php echo base_url('promotion/send_message'); ?>",
type:"post",
data:$(this).serialize(),
success:function(data){
$("#status").html(data);
}
}
});
</script>
You have to do your loop with javascript/jquery rather than PHP. To have no overflow on server-side you should probably only call the function on success by using recursion. This way it will be synchronous.
jQuery
var emails = [
'lorem#stackoverflow.com',
'ipsum#stackoverflow.com',
'foo#stackoverflow.com'
];
index = 0;
var sendMail = function(email){
$.ajax({
url:"sendMail.php",
type: "POST"
data: { emailId: email}
success:function(response) {
index++;
document.write(response);
if(emails[index] != undefined){
sendMail(emails[index]);
}
}
});
}
sendMail(emails[index]);
PHP
$status = $this->sendMail($$_POST['email']);
$msg = $status ? "Mail Sent" : "Not Sent";
echo $msg;
I want to print the response when each time "$this->mail->send" function is called in "sendMail()"
As your code above, $status should be return in ajax function like a json object array.so I try this one ...
private function sendMail($users, $template, $subject) {
$this->load->library('parser');
$status = array();
$i = 0;
foreach ($users as $user) {
$message = $this->parser->parse('email_templates/' . $template, array('email' => $user->email, 'name' => ($user->name != '') ? "Hi " . $user->name : "Hello"), TRUE);
$response = $this->mail->send(config_item('sender_mail'), config_item('sender_name'), $user->email, $subject, $message);
$status[$i]['email'] = $user->email;
$status[$i]['status'] = ($response == 1) ? 1 : 0;
$i++;
}
echo json_encode($status);
}
Ajax Code
<script type="text/javascript">
$("#send_mail").submit(function(){
$.ajax{
url:"<?php echo base_url('promotion/send_message'); ?>",
type:"post",
dataType : "json",
data:$(this).serialize(),
success:function(data){
$.each(data,function(i,v){
$("#status").append(v.status);
}
}
}
});
</script>
function registration_ajax(){
$this->load->library('form_validation');
$this->form_validation->set_rules('email','email','required|is_unique[register.email]');
if($this->form_validation->run() == FALSE){
$data = '{"status":"false","message":"Email already exists"}';
}
else
{
$email=$this->input->post('email');
$data= array(
'email'=>$email
);
$last_id = $this->model->registeration($data);
if ($last_id>0) {
$this->send_email($email);
$data = '{"status":"true","message":"Email Created successfully"}';
}
}
echo $data;
}
public function send_email($to='',$username="",$from='khadija#precisetech.com.pk')
///function send_mail()
{
$this->load->library('encrypt');
$toEmail = $this->encrypt->encode($to);
$toEmail = str_replace('/','forwardSlash',$toEmail);
$toEmail = str_replace('=','equalSign',$toEmail);
$toEmail = str_replace('+', 'plusSign', $toEmail);
$this->load->library('email');
$config['protocol'] = 'smtp';
$config['smtp_host'] = 'sadasds';//pust mail.com.pk
$config['smtp_port'] = '25334';
$config['smtp_user'] = 'example';
$config['smtp_pass'] = 'example1';
$config['charset'] = 'utf-8';
$config['mailtype'] = 'html';
$config['validation'] = FALSE; // bool whether to validate email or not
$this->email->initialize($config);
$message = '<h1 align="center">Hellow</h1>';
$message = '<html><body style="color:#000; font-weight:normal; font-size:13/14px;"><p style="color:#000;">Hi!</p>';
$message .= '<table rules="all">';
$message .= "<p>Congratulations! You have almost completed your registration on Electronic Mall.<br><br>Click on link here to confirm your email address<br> 10.10.10.44<br><br>Thank you for joining us and becoming part of world's largest local classified sites.In our website, you can enjoy simple ad posting, easy searching and endless local listing for products.We appreciate you for choosing us in online market place.<br> Wishing you alot of success on your classified journey.Get started now!<br><br></p>";
$message .= "<p>Regards,<br>The Electronic Mall Team</p>";
$message .= "</table>";
$message .= "</body></html>";
$this->email->from($from);
$this->email->to($to);
$this->email->subject('Confirmation Email');
$this->email->message($message);
if(!$this->email->send()){
echo $this->email->print_debugger();
die();
}else{
}
}
////ajx code
//////////////////
<script>
$(document).ready(function(){
$('#registration_form').on('submit',function(e){
var email = $('#email').val();
$.ajax({
url: "<?=base_url('controller/registration_ajax')?>",
// url: "<?=base_url('controller/register')?>",
type: "POST",
datatype: "JSON",
data: {email: email},
success: function(res){
var data = $.parseJSON(res);
var status = data.status;
var message = data.message;
if(status == 'true'){
/// $('#myModal').modal('hide');
$('#message_sent').html(message);
}
else{
$('#message').html(message);
}
}
});
e.preventDefault();
});
});
</script>
I want that after email is sent successfully then this message should be displayed
$data = '{"status":"true","message":"Email Created successfully"}';
When I commented the mail sending function then it display the successful message, I want that the message should be display after sending email.
have you tried returning a value from your send_email function?
if(!$this->email->send()){
return 'success';
}else{
$this->session->set_flashdata('message', 'To complete registration, click the link in email we just send you at khadija#precisetech.com.pk');
redirect('controller/login_register','refresh');
die();
}
then in your :
if ($last_id>0) {
$res = $this->send_email($email);
if($res === 'success'){
$data = '{"status":"true","message":"Email Created successfully"}';
}
}
I am developing a smart tv app that plays live streams. App itself works fine, when i provide a valid xml playlist to it.
But when i use php to generate xml file (wich also generates fine), it doesnt work.
I get an error:
TypeError: 'null' is not an object (evaluating 'this.XHRObj.responseXML.documentElement')
Here is my php file that generates videoList.xml, it works 100%.
In short words, this script checks if MAC address in database, and if it is, then it writes videoList.xml with walid live streaming links.
SamsungAPI.php
<?php
$MAC = $_GET['MAC'];
require_once('../config.php');
//Remove brackets form array
$_INFO = preg_replace('/[{}]/', '', $_INFO);
$mysqli = new mysqli($_INFO['host'], $_INFO['db_user'], $_INFO['db_pass'], $_INFO['db_name']);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$sql="SELECT * FROM users WHERE admin_notes = '$MAC' ";
$rs=$mysqli->query($sql);
$rows=mysqli_num_rows($rs);
if ($rows == 1) {
//MAC FOUND
$row = mysqli_fetch_array($rs);
$username = $row['username'];
$password = $row['password'];
$file = "videoList.xml";
$txt_file = file_get_contents('http://' . $_SERVER['HTTP_HOST'] . '/get.php?type=starlivev3&username=' . $username . '&password=' . $password . '&output=hls');
$rows = explode("\n", $txt_file);
if(empty($rows[count($rows)-1])) {
unset($rows[count($rows)-1]);
$rows=array_map('trim',$rows);
}
$handle = fopen($file, "w+") or die('Could not open file');
fwrite($handle, "<?xml version=\"1.0\"?>"."\n");
fwrite($handle, "<rss version=\"2.0\">"."\n");
fwrite($handle, "<channel>"."\n");
foreach($rows as $row => $data)
{
//get row data
$row_data = explode(',', $data);
//replace _ with spaces
$row_data[0] = str_replace('_', ' ', $row_data[0]);
//generate playlist content
fwrite($handle, "<item>"."\n");
fwrite($handle, "<title>{$row_data[0]}</title>"."\n");
fwrite($handle, "<link>{$row_data[1]}</link>"."\n");
fwrite($handle, "<description> Reserved for EPG </description>"."\n");
fwrite($handle, "</item>"."\n");
}
fwrite($handle, "</channel>"."\n");
fwrite($handle, "</rss>");
fclose($handle);
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
} else {
//MAC NOT FOUND
echo "MAC NOT FOUND";
}
mysqli_close($mysqli); // Closing Connection
?>
Then in samsung smart tv videoplayer app, i have xml parser like this:
Server.js
var Server =
{
/* Callback function to be set by client */
dataReceivedCallback : null,
XHRObj : null,
url : "http://myvalidhost.com/samsungAPI.php?MAC=02000027000b"
}
Server.init = function()
{
var success = true;
if (this.XHRObj)
{
this.XHRObj.destroy(); // Save memory
this.XHRObj = null;
}
return success;
}
Server.fetchVideoList = function()
{
if (this.XHRObj == null)
{
this.XHRObj = new XMLHttpRequest();
}
if (this.XHRObj)
{
this.XHRObj.onreadystatechange = function()
{
if (Server.XHRObj.readyState == 4)
{
Server.createVideoList();
}
}
this.XHRObj.open("GET", this.url, true);
this.XHRObj.send(null);
}
else
{
alert("Failed to create XHR");
}
}
Server.createVideoList = function()
{
if (this.XHRObj.status != 200)
{
Display.status("XML Server Error " + this.XHRObj.status);
}
else
{
var xmlElement = this.XHRObj.responseXML.documentElement;
if (!xmlElement)
{
alert("Failed to get valid XML");
}
else
{
// Parse RSS
// Get all "item" elements
var items = xmlElement.getElementsByTagName("item");
var videoNames = [ ];
var videoURLs = [ ];
var videoDescriptions = [ ];
for (var index = 0; index < items.length; index++)
{
var titleElement = items[index].getElementsByTagName("title")[0];
var descriptionElement = items[index].getElementsByTagName("description")[0];
var linkElement = items[index].getElementsByTagName("link")[0];
if (titleElement && descriptionElement && linkElement)
{
videoNames[index] = titleElement.firstChild.data;
if(linkElement.firstChild.data.substring(0,4) !="http"){
alert("asdasdasd "+linkElement.firstChild.data.substring(0,4));
var rootPath = window.location.href.substring(0, location.href.lastIndexOf("/")+1);
var Abs_path = unescape(rootPath).split("file://")[1]+linkElement.firstChild.data;
videoURLs[index] = Abs_path;
}
else{
videoURLs[index] = linkElement.firstChild.data;
}
videoDescriptions[index] = descriptionElement.firstChild.data;
}
}
Data.setVideoNames(videoNames);
Data.setVideoURLs(videoURLs);
Data.setVideoDescriptions(videoDescriptions);
if (this.dataReceivedCallback)
{
this.dataReceivedCallback(); /* Notify all data is received and stored */
}
}
}
}
Does anyone have any idea why doesnt it accept my generated xml file?
Regards
M
I figured it out, in php headers content type was wrong.
Changed
header('Content-Type: application/octet-stream');
to
header('Content-Type: application/xml');
Now it works perfect!
Sending a javaScript array to a PHP file and then storing the elements in a mySQL database.
Currently I'm getting errors in for my "httpSend.responseText" alert. Saying Notice: Undefined index: name in .. line 8
Notice: Undefined index: address in .. on line 9
Warning: mysqli_query() expects parameter 1 to be mysqli, resource given in .. on line 12
I'm not sure if the array is sending correctly or being received correctly.
var name = "John";
var address = "UK";
var sendInfo = {
Name: name,
Address: address
};
var httpSend = new XMLHttpRequest();
var php = "http://server/~name/folder/insertOffer.php";
httpSend.open("POST", php, true);
httpSend.onreadystatechange = function() {//Call a function when the state changes.
if(httpSend.readyState == 4 && httpSend.status == 200) {
alert(httpSend.responseText);
}
}
httpSend.send(sendInfo);
PHP
<?php
include("mysqlconnect.php");
$name = $_POST['name'];
$address = $_POST['address'];
mysqli_query($connection,"INSERT INTO offerSelected (Id, Url) VALUES ('$name', '$address')");
?>
mysqlconnect looks like this
<?php
$connection = mysql_connect("localhost", "user", "pass");
if(!$connection){
die('Could not connect to server: ' . mysql_error());
}
mysql_select_db("database", $connection);
?>
Try this :
var name = "John";
var address = "UK";
var sendInfo = {
Name: name,
Address: address
};
var params = "sendInfo=" + JSON.stringify(sendInfo);
var httpSend = new XMLHttpRequest();
var php = "http://server/~name/folder/insertOffer.php";
httpSend.open("POST", php, true);
httpSend.onreadystatechange = function() {//Call a function when the state changes.
if(httpSend.readyState == 4 && httpSend.status == 200) {
alert(httpSend.responseText);
}
}
httpSend.send(params);
PHP code:
<?php
include("mysqlconnect.php");
$sendInfo = json_decode($_POST['sendInfo']);
$name = $sendInfo ['name'];
$address = $sendInfo ['address'];
mysqli_query($connection,"INSERT INTO offerSelected (Id, Url) VALUES ('$name', '$address')");
?>
why are you using single quotes to wrap variables '$name' and '$address' change your code to this may be this will help you:
<?php
include("mysqlconnect.php");
$name = $_POST['name'];
$address = $_POST['address'];
mysqli_query($connection,"INSERT INTO offerSelected (Id, Url) VALUES ('".$name."', '".$address."')");
?>
Try this:
<?php
include("mysqlconnect.php");
$name = $_POST['Name']; // NOTE THE CASE CHANGE HERE AS THIS IS WHATS DEFINED IN YOUR JS
$address = $_POST['Address'];
mysqli_query($connection,"INSERT INTO offerSelected (Id, Url) VALUES ('".$name."','".$address."')");
?>
Where is $connection being defined?