Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

angular 2 post to a database works on firefox but not on chrome

Posted on 2016-07-28
16
Medium Priority
?
61 Views
Last Modified: 2016-08-05
so this drive me insane :)
the same code work on firefox but not on chrome.

i test angular 2 "ajax calls", this time sending data to insert into the database, and send back the inserted item.

so this is in the service:
  addUser(){
    var theparams = JSON.stringify({
      name: "fabian",
      address: "dizingoff 99, NY",
      lat: 33.060143,
      lng: 39.770557
    });
    var params = 'user=' + theparams;
    var headers = new Headers();
    headers.append('Content-type', 'application/x-www-form-urlencoded');

    return this._http.post('http://localhost:80/ang2router/public/addContact.php', params,{
      headers: headers
    })
    .map(res => res.json());

  }

Open in new window


this is hard coded for testing obviously.
then i call it on a button click:
      this._httpsService.addUser()
      .subscribe(
        data => this.postData = data,
        error => alert(error),
        () => console.log("Finished")
      );

Open in new window


then the php file that insert it into the database and get it back:
$value = json_decode($_POST['user']);
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Headers: X-Requested-With');
header('Content-Type: application/json');
//var_dump($value->name);

        $db_name  = 'mydb';
        $hostname = 'localhost';
        $username = 'myusername';
        $password = 'mypass';

        // connect to the database
       $dbh = new PDO("mysql:host=$hostname;dbname=$db_name", $username, $password);



    // a query get all the records from the users table
    $sql = 'INSERT INTO markers ( name, address,lat, lng ) 
        VALUES ( "' . $value->name .'" , "'.$value->address.'", '.$value->lat.' , '.$value->lng.' );';

    
    $stmt = $dbh->prepare( $sql );

   
    $check = $stmt->execute();

    $last_id = $dbh->lastInsertId();

    $sql2 = "SELECT * FROM markers WHERE id=$last_id ";

   
    $stmt = $dbh->prepare( $sql2 );

    
    $stmt->execute();

    // fetch the results into an array
    $result = $stmt->fetchAll( PDO::FETCH_ASSOC );
                                                        
    echo json_encode($result);

Open in new window


in firefox all goes well, the data is in the database and i get the last inserted id back.
but on chrome not. i attach what i get on chrome.

best regards
Screenshot--65-.png
Screenshot--66-.png
0
Comment
Question by:derrida
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 8
  • 8
16 Comments
 
LVL 84

Expert Comment

by:Dave Baldwin
ID: 41733631
Chrome doesn't like 'localhost' for a number of functions including cookies.  Try changing your links to the IP address of the machine and see if that works.  I only use 'localhost' when it is actually required.  I normally use the machine IP address because then the pages are accessible from other machines on the network.
0
 
LVL 1

Author Comment

by:derrida
ID: 41733694
hi
no change. and add to it that if i don't do a switch statement it works. but once i use that post veriable, it works of FF but not on chrome.
0
 
LVL 84

Expert Comment

by:Dave Baldwin
ID: 41733699
What 'switch statement'?
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 1

Author Comment

by:derrida
ID: 41733718
sorry, that was about another issue i have :) forget about the switch statement.
0
 
LVL 1

Author Comment

by:derrida
ID: 41734199
so when i var_dump my $_POST array:
in chrome: array(0) {
}
empty.
in firefox:
array(1) {
  ["user"]=>
  string(82) "{"name":"Moses","address":"dizingoff 29, NY","lat":23.060143,"lng":29.770557}"
}
0
 
LVL 84

Expert Comment

by:Dave Baldwin
ID: 41734232
For test purposes, I would create an HTML form page and see what you get when you submit that.  Like below... note that I put quotes around the "lat / lon" values to get it to work.  It works the same in both Firefox and Chrome.

ChromePOSTtest.html
<!DOCTYPE html>
<html>
<head>
<title>Chrome POST test form</title>
</head>
<body>
<h1>Chrome POST test form</h1>
<form action="addContact.php" method="post">
<input type="text" name="user" value='{"name":"Moses","address":"dizingoff 29, NY","lat":"23.060143","lng":"29.770557"}' />
<input type="submit" name="submit" value="submit" />
</form>
</body>
</html>

Open in new window


addContact.php
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<title>addContact.php</title>
</head>
<body>
<?php 
$value = json_decode($_POST['user']);
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Headers: X-Requested-With');
header('Content-Type: application/json');
var_dump($_POST['user']);
var_dump($value);
?>
</body>
</html>

Open in new window

0
 
LVL 84

Assisted Solution

by:Dave Baldwin
Dave Baldwin earned 2000 total points
ID: 41734241
Let's try this again, I might have found something.  I added the 'true' option to 'json_decode' and it seems to work without the quotes.  It now shows the lat/lon as floats in both browsers.

ChromePOSTtest1.html
<!DOCTYPE html>

<html>
<head>
<title>Chrome POST test form</title>
</head>
<body>
<h1>Chrome POST test1 form</h1>
<form action="addContact.php" method="post">
<input type="text" name="user" value='{"name":"Moses","address":"dizingoff 29, NY","lat":23.060143,"lng":29.770557}' />
<input type="submit" name="submit" value="submit" />
</form>
</body>
</html>

Open in new window


addContact.php
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<title>addContact.php</title>
</head>
<body>
<?php 
$value = json_decode($_POST['user'], true);
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Headers: X-Requested-With');
header('Content-Type: application/json');
var_dump($_POST['user']);
var_dump($value);
?>
</body>
</html>

Open in new window


From http://php.net/manual/en/function.json-decode.php ...
assoc

    When TRUE, returned objects will be converted into associative arrays.
0
 
LVL 1

Author Comment

by:derrida
ID: 41734249
well yes, it does work, in that "regular" way ( by the way, with quotes or without the added quotes).
But once I do that in the angular 2 way, works in FF but not in chrome. notice that i'm hard coding the values, since I just want to learn to pass the data in the angular 2 way.

I have no idea why it is passed in FF but not in chrome.
0
 
LVL 84

Expert Comment

by:Dave Baldwin
ID: 41734260
Are you going to try adding 'true' to the json_decode statement?  I'm not going to try to duplicate your angular code because most of is not posted and I don't have your database.  For testing I always simplify things to something that works and work from there to build something more complicated.
0
 
LVL 1

Author Comment

by:derrida
ID: 41734266
oh i have tried it with the true. same thing: works on FF not in chrome.
0
 
LVL 84

Expert Comment

by:Dave Baldwin
ID: 41734271
Then you need to make a test version of your code that is as simple as possible so you can figure out what is and isn't working.  Maybe an 'angular' version of my demo programs.  After all Chrome works, Firefox works, PHP works.  It's just the combination with your code that isn't working.
0
 
LVL 1

Author Comment

by:derrida
ID: 41734470
so fixed it. and i put it here for anyone else who will encounter the issue.

the problem is that the post array in php expect a key value pair. and that's not what i sent.
so you either send a key value pairs, or if you want to keep the json format, in your php, since there is no key, do:
$theobject = json_decode(key($_POST));
echo $theobject->action;

Open in new window


now it works on chrome and firefox.
0
 
LVL 84

Expert Comment

by:Dave Baldwin
ID: 41734492
Interesting.  So how did you rewrite the addUser() function?
0
 
LVL 1

Accepted Solution

by:
derrida earned 0 total points
ID: 41734535
not a lot to rewrite it:
    let theparams = JSON.stringify({
      name: "Moses",
      address: "dizingoff 29, NY",
      lat: 23.060143,
      lng: 29.770557
    });
    let headers = new Headers();
    headers.append('Content-Type','application/x-www-form-urlencoded;charset=utf-8');

    return this._http.post(
      'http://localhost:80/ang2router/public/addUser2.php',
      theparams,
      {headers: headers}
    )
    .map(res => res.json());

Open in new window


i'm not sure i can give myself the points :)
0
 
LVL 84

Expert Comment

by:Dave Baldwin
ID: 41735026
No, but you can give yourself credit.  Although if you feel that I helped you, you can give me some credit.
0
 
LVL 1

Author Closing Comment

by:derrida
ID: 41743970
icame with the answer
0

Featured Post

[Webinar] Lessons on Recovering from Petya

Skyport is working hard to help customers recover from recent attacks, like the Petya worm. This work has brought to light some important lessons. New malware attacks like this can take down your entire environment. Learn from others mistakes on how to prevent Petya like worms.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Today, still in the boom of Apple, PC's and products, nearly 50% of the computer users use Windows as graphical operating systems. If you are among those users who love windows, but are grappling to keep the system's hard drive optimized, then you s…
In this blog, we’ll look at how improvements to Percona XtraDB Cluster improved IST performance.
This Micro Tutorial will demonstrate how to add subdomains to your content reports. This can be very importing in having a site with multiple subdomains.
Want to learn how to record your desktop screen without having to use an outside camera. Click on this video and learn how to use the cool google extension called "Screencastify"! Step 1: Open a new google tab Step 2: Go to the left hand upper corn…

609 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question